Skip to main content
Use @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

  1. Install the package:
  2. Set GRAVITY_API_KEY in the environment of your app.
You do not need a separate package for the pixel. gravityPixel is part of @gravity-ai/api.

Overview

  1. Start the pixel. gravityPixel() tracks sessions and visitors. Start it one time when your app starts.
  2. 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.
  3. 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

The pixel manages sessions, visitor IDs, and attribution, the same as the browser 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

A terminal app has no incoming HTTP request, so pass an object with body and headers as the first argument. gravity.getAds() never throws. On any failure, ads is an empty array.

Full example

FAQ

No. Start gravity.getAds() at the same time as your model call. It never throws.
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 }).

Troubleshoot