@gravity-ai/api in a terminal app to track sessions and request ads. The package contains gravityPixel(), a pixel for terminal apps. For the terms on this page, see Core concepts.
Before you start
- Your app runs on Node.js, Bun, or Deno.
- You have a Gravity API key and a pixel ID. Get them from your dashboard under Settings → Platform Settings.
Install
-
Install the package:
-
Set
GRAVITY_API_KEYin the environment of your app.
gravityPixel is part of @gravity-ai/api.
Overview
- Start the pixel.
gravityPixel()tracks sessions and visitors. Start it one time when your app starts. - Prepare the context.
gravityContext()collects device data and session data. Give it the visitor and session IDs from the pixel, so that Gravity can link tracking to ad requests. - Request ads.
gravity.getAds(req, messages, placements)reads the context and returns matched ads. Run it at the same time as your model call.
Step 1: Start the pixel
gr-pix.js). It keeps its state in local files, not in cookies. It saves the state when the process stops.
pixel.start() adds handlers for SIGINT and SIGTERM. These handlers save the pixel state and then stop the process with exit code 0.Step 2: Prepare the context
gravityContext() finds the device data of the terminal (OS, time zone, and locale) for you. These parameters are required:
Step 3: Request ads
body and headers as the first argument.
gravity.getAds() never throws. On any failure, ads is an empty array.
Full example
FAQ
Does the ad request block my model response?
Does the ad request block my model response?
No. Start
gravity.getAds() at the same time as your model call. It never throws.Where does the API key go?
Where does the API key go?
Set
GRAVITY_API_KEY as an environment variable. The Gravity class reads it. You can also pass it in the constructor: new Gravity({ apiKey: process.env.MY_KEY }).