> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trygravity.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript and React SDKs

> Request Gravity ads from JavaScript or TypeScript, and show them in React.

Use `@gravity-ai/api` on your server to request ads, and `@gravity-ai/react` in your client to show them. For the terms on this page, see [Core concepts](https://docs.trygravity.com/introduction/concepts.md).

## Before you start

* You have a Gravity API key. Get it from your dashboard under **Settings → Platform Settings**.
* Your server runs Node.js (or another runtime with `fetch`), and your client uses React 17 or later.
* You have a chat endpoint on your server that calls your model.

## Install

1. Install the packages:

   ```bash theme={null}
   npm install @gravity-ai/api @gravity-ai/react
   ```

2. Set `GRAVITY_API_KEY` in your server environment.

> [!WARNING]
>
> Do not reference `GRAVITY_API_KEY` in client code. A bundler can put the value into your public JavaScript.

## Step 1: Prepare the context in the client

In your client, call `gravityContext()` and send the result to your server with the messages:

```ts theme={null}
import { gravityContext } from '@gravity-ai/api';

const gravity_context = gravityContext({
  sessionId: chatSession.id,
  user: { userId: currentUser.id },
});

await fetch('/api/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ messages, gravity_context }),
});
```

`gravityContext()` collects the device data, the session, and the consent signal from the page. In the browser it reads TCF (`__tcfapi`) and US Privacy (`__uspapi`), and from version 1.5.0 also GPP (`__gpp`) and GPC (`navigator.globalPrivacyControl`). Privacy signals are required, so on a server or behind a cross-origin CMP frame, pass `consent` yourself (`gdprApplies`, `tcfString`, and `usPrivacy`; from 1.5.0 also `gpc`, `gpp`, and `gppSid`). An explicit `consent` replaces the detected object as a whole, with no field merge (see [Send privacy signals](https://docs.trygravity.com/ai-platforms/privacy-signals.md)). `user.userId` is required. In a browser with the [Gravity pixel](https://docs.trygravity.com/ai-platforms/pixel.md), `sessionId` is optional: the SDK uses the pixel session. Send the complete `gravity_context` object to your server.

## Step 2: Request ads on the server

Start the ad request at the same time as your model call:

```ts theme={null}
import { Gravity } from '@gravity-ai/api';

const gravity = new Gravity();

app.post('/api/chat', async (req, res) => {
  const { messages } = req.body;

  const adPromise = gravity.getAds(req, messages, [
    { placement: 'below_response', placement_id: 'YOUR_PLACEMENT_ID' },
  ]);

  const llmResponse = await callYourLLM(messages);
  const { ads } = await adPromise;

  res.json({ response: llmResponse, ads });
});
```

`gravity.getAds()` reads `gravity_context` from `req.body`, adds the end user's IP address from the request headers, and sends the last two messages to Gravity. It never throws. On no-fill or on an error, `ads` is an empty array.

The result is `{ ads, status, elapsed, requestBody, error }`. `status` is the HTTP status from Gravity, or `0` for a network error or a missing API key.

### Options

Pass these options to `new Gravity()`. You can also pass them as the fourth argument of `getAds()` for one call.

| Option | Default | Description |
| - | - | - |
| `apiKey` | `process.env.GRAVITY_API_KEY` | Your Gravity API key. |
| `production` | `false` | Set to `true` for live ads. When `false`, Gravity returns test ads and does not bill. |
| `timeoutMs` | `4000` | The request timeout in milliseconds. |
| `relevancy` | `0.2` | The minimum relevancy, from 0 to 1. |
| `excludedTopics` | None | Topics that ads must not match. |
| `alwaysReturn` | `false` | For test ads only. Return a default test ad instead of no ad. |
| `supportsSpec` | `true` | Set to `false` if you draw ads with your own code. |
| `enableFrames` | The value of `supportsSpec` | Sends `supportsFrames: true`, so the engine can serve [rich frame and carousel ads](https://docs.trygravity.com/ai-platforms/ad-formats.md#rich-frame). Set to `false` if your client can't show them. |
| `gravityApi` | `https://server.trygravity.ai/api/v1/ad` | The ad endpoint URL. |

### User tags and model usage

Add `tags` to the user when you prepare context:

```ts theme={null}
const gravity_context = gravityContext({
  sessionId: chatSession.id,
  user: { userId: currentUser.id, tags: { plan: 'free' } },
});
```

Tags are optional. See [Understand what your users earn you](https://docs.trygravity.com/ai-platforms/user-earnings.md) for the rules.

> [!NOTE]
>
> `@gravity-ai/api` doesn't have a model `usage` option. To report model usage, send it in a direct HTTP request to the ad API: see [Report model usage](https://docs.trygravity.com/ai-platforms/request-ads.md#report-model-usage).

## Step 3: Show the ad in React

Give the ad to `GravityAd`:

```tsx theme={null}
import { GravityAd } from '@gravity-ai/react';

export function ChatResponse({ response, ads }) {
  return (
    <div>
      <p>{response}</p>
      {ads[0] && <GravityAd ad={ads[0]} />}
    </div>
  );
}
```

You see the ad under the response. `GravityAd` draws the placement design, shows a built-in card when no design is available, records the impression and the click, and shows the ad label.

Show the slot only when `ads` has an ad. Keep one stable `sessionId` for each conversation.

## Ad units

On placements where Gravity has turned on [ad units](https://docs.trygravity.com/ai-platforms/ad-units.md), an SDK version that supports them works with no code change:

* `getAds()` tells Gravity what `GravityAd` can draw: `units.v1` and `image` on every placement, `frame.gfb1` when `enableFrames` is on, `action.prompt` on a placement with `supportsPromptAction: true`, and `connect.mcp` on a placement with `supportsMcpConnect: true`. In a browser it also sends the page's font and theme.
* `GravityAd` draws the ad's `unit` with the layout that fits its container's live width, and re-flows when the width crosses a layout boundary. The unit takes the page's light or dark surface, text color, and font. `--gravity-accent` and `--gravity-radius` set its button color and corner radius.
* A `rich_frame` unit shows in the frame host, an `action_card` button runs `onPrompt`, and a `connect_card` button runs `onConnect`. A unit type or version that the SDK doesn't know shows as a plain text card.
* Impressions and clicks are tracked as for every other ad, and `GravityAd` sends the [unit events](https://docs.trygravity.com/ai-platforms/ad-units.md#unit-events) for you. Ads without a `unit` show as before.

### Send the slot from the browser

When `getAds()` runs on your server, Gravity doesn't know the slot width and assumes a typical one. To fit the unit to the real slot, call `getPlacementContext` from `@gravity-ai/react` on the slot's container in the client, send the result to your server, and spread it into the placement:

```tsx theme={null}
// Client
import { getPlacementContext } from '@gravity-ai/react';

const placement_context = getPlacementContext(slotRef.current, {
  promptAction: !!onPrompt,
  mcpConnect: !!onConnect,
});
// Send placement_context to your server with messages and gravity_context.
```

```ts theme={null}
// Server
const { ads } = await gravity.getAds(req, messages, [
  { placement: 'below_response', placement_id: 'YOUR_PLACEMENT_ID', ...req.body.placement_context },
]);
```

`getPlacementContext` returns the slot width (and its maximum height when the container sets one), the page's font and theme, and the capabilities that `GravityAd` draws. The `frames` option defaults to `true`, to match `enableFrames`. It never throws. On the server it returns only `capabilities`.

### Turn ad units off

| To | Do this |
| - | - |
| Get no units for any placement | Set `supportsSpec: false` in the `getAds()` options. `getAds()` then sends no capabilities, and you also get no server-rendered designs. |
| Get no `rich_frame` units | Set `enableFrames: false`. |
| Choose the capabilities yourself | Set `capabilities` on the placement. `getAds()` sends the value you set, unchanged. For example, `['units.v1']` gets units without images. |
| Keep your own look | Pass `variant` to `GravityAd`. It draws that bundled look and ignores `unit`. |

## Custom renderer

Use `GravityAd` if you can. If you draw ads with your own code, do these things:

1. Send `supportsSpec: false` in the `getAds()` options.
2. Load `ad.impUrl` once when the ad becomes visible.
3. Open `ad.clickUrl`, not `ad.url`, when the user clicks the ad.
4. Show a clear ad label.

## Troubleshoot

| Problem | Cause and fix |
| - | - |
| `ads` is always empty and `status` is `0` | The API key is missing, or the network request failed. Set `GRAVITY_API_KEY` on the server, and read `error` in the result. |
| `ads` is empty and `status` is `204` | No ad matched. To test your UI, set `alwaysReturn: true` with `production: false`. |
| `status` is `401` | The API key is not valid. Copy it again from the dashboard. |
| `gravityContext()` throws "requires user.userId" | Pass `user: { userId }`. |
| `gravityContext()` throws "requires sessionId" | Pass `sessionId`, or load the Gravity pixel on the page. |
| The dashboard shows your server as the device | Your server did not forward `gravity_context`. Send it from the client, and pass the original `req` to `getAds()`. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.