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

# React SDK

> Get started with our SDK built for React applications

> [!NOTE]
>
> We are preparing a new v4 release of the React SDK. The documentation below covers the current shipping version — once v4 lands, this page will be updated.

> [card] [React Demo Project](https://github.com/kontextso/sdk-react-demo/tree/v3)
>
> See how easy it is to integrate high-performance ads into your React app using our lightweight SDK.

## Requirements

* **React**: 18.3.1 or later

## Getting started

### 1. Installation

> [!NOTE]
>
> To get started, you will need to set up a [publisher account](https://docs.kontext.so/publishers.md#getting-started-is-easy) to get a `publisherToken` and `code`.

```bash theme={null}
npm install @kontextso/sdk-react@3
```

### 2. Initialize AdsProvider

The `AdsProvider` handles all data-fetching logic and must have access to the chat messages. Place it high enough in your component tree so it can contain all ad placements.

```tsx theme={null}
import * as React from 'react'
import { useState } from 'react'
import { AdsProvider } from '@kontextso/sdk-react'

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  createdAt: Date
}

function App() {
  const [messages, setMessages] = useState<Message[]>([])

  return (
    <AdsProvider
      publisherToken='<your-publisher-token>'
      messages={messages}
      userId='user-1234'
      conversationId='conv-5678'
      enabledPlacementCodes={['inlineAd']}
      character={{
        id: 'character-1234',
        name: 'John Doe',
        avatarUrl: 'https://example.com/avatar.png',
        greeting: 'Hello, how can I help you today?'
      }}
      regulatory={{
        gdpr: 1,
        // ... other regulatory properties
      }}
      onEvent={({ name, code, payload }) => {
        // process events
      }}
    >
      <TheRestOfYourApplication />
    </AdsProvider>
  )
}
```

### 3. Show your first ad

An ad slot is a designated area in your UI where an ad can be rendered. In most cases, it appears below a chat message. During onboarding, you’ll receive a unique `code` for each ad slot you plan to use.

Copy the markup `<InlineAd />` and place it in your application where it should be rendered. Don't forget to assign `messageId` as a unique identifier. For example, if you have a `MessageList` component, you can show an ad after each message like this (every message will have a unique ad displayed because of `messageId`).

```jsx theme={null}
function MessageList({ messages }: { messages: Message[] }) {
  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          <Message message={m} />
          <InlineAd code='<your-code>' messageId={m.id} />
        </div>
      ))}
    </div>
  )
}
```

## API documentation

### `AdsProvider` properties

**publisherToken** `string` *required*

Your unique publisher token.

**messages** `array` *required*

List of messages between the assistant and the user.

**Properties**

**id** `string` *required*

Unique ID of the message.

**role** `string` *required*

Role of the message (`user` or `assistant`).

**content** `string` *required*

Message text.

**createdAt** `Date` *required*

Timestamp when the message was created.

**userId** `string` *required*

Unique identifier that remains the same for the user’s lifetime (used for retargeting and rewarded ads).

**userEmail** `string`

Email of the user.

**conversationId** `string` *required*

Unique ID of the conversation.

**enabledPlacementCodes** `array` *required*

Placement codes enabled for the conversation. Example: `['inlineAd']`.

**character** `object`

Character object used in this conversation.

**Properties**

**id** `string` *required*

Unique ID of the character.

**name** `string` *required*

Name of the character.

**avatarUrl** `string` *required*

URL of the character’s avatar.

**isNsfw** `boolean`

Indicates whether the character is NSFW.

**greeting** `string`

The character’s greeting.

**persona** `string`

Description of the character’s personality.

**tags** `array`

Tags describing the character.

**regulatory** `object`

Regulatory object used in this conversation.

**Properties**

**gdpr** `integer`

Indicates whether the request is subject to GDPR regulations. (0 = No, 1 = Yes, null = Unknown)

**gdprConsent** `string`

The IAB Transparency and Consent Framework (TCF) consent string.

**coppa** `integer`

Indicates whether the request is subject to COPPA. (0 = No, 1 = Yes, null = Unknown)

**gpp** `string`

Global Privacy Platform (GPP) consent string.

**gppSid** `array`

IDs of the GPP sections that apply to this transaction.

**usPrivacy** `string`

Signals regarding consumer privacy under US privacy regulations (e.g., CCPA, LSPA).

**variantId** `string`

Publisher-provided identifier for the user cohort (for A/B testing).

**onEvent** `function`

Callback triggered when an event occurs. See [Supported events](#supported-events) for more details.

**isDisabled** `boolean`

Flag indicating if the ads are disabled.

Note: This does not disable the display of old ads; that behavior is controlled by `staleAdsHandling`.

**staleAdsHandling** `string`

Determines how stale ads (ads not linked to the latest message) are handled.

* `preserve` - keep displaying the last anchored ad until it's replaced by a new ad
* `hide` (default) - hide the ad when it becomes stale

### `InlineAd` properties

**code** `string` *required*

Placement code provided during onboarding.

**messageId** `string` *required*

Unique ID of the message.

**theme** `string`

Theme of the ad, e.g. `light` or `dark`.

**wrapper** `function`

Wrapper function to wrap the ad content.

### Supported Events

#### `ad.clicked`

The user has clicked the ad.

**Payload**

**id** `string`

Ad ID.

**content** `string`

Generated ad content.

**messageId** `string`

Message ID.

**url** `string`

Click URL.

**format** `string`

Ad format.

#### `ad.viewed`

The user has viewed the ad.

**Payload**

**id** `string`

Ad ID.

**content** `string`

Generated ad content.

**messageId** `string`

Message ID.

**format** `string`

Ad format.

**revenue** `number`

The revenue of the ad (eCPM in USD).

#### `ad.filled`

Ad is available.

**Payload**

**revenue** `number`

The revenue of the ad (eCPM in USD).

#### `ad.no-fill`

Ad is not available.

**Payload**

**skipCode** `string`

The code indicating the reason why the ad was skipped.

#### `ad.render-started`

Triggered before the first token is received.

**Payload**

**id** `string`

Ad ID.

#### `ad.render-completed`

Triggered after the last token is received.

**Payload**

**id** `string`

Ad ID.

#### `ad.error`

Triggered when an error occurs.

**Payload**

**message** `string`

Error message.

**errCode** `string`

Error code.

#### `video.started`

Triggered when the video playback starts.

**Payload**

**id** `string`

Ad ID.

#### `video.completed`

Triggered when the video playback finishes.

**Payload**

**id** `string`

Ad ID.

## Guides

### Controlling when ads load

You can fine-tune ad frequency by controlling when new `messages` are passed into `AdsProvider`. This allows you to adjust the ratio of ads to messages dynamically.

### Handling no-fill events

You can notify when the ad is not available by using the `onEvent` callback.

```tsx theme={null}
<AdsProvider
  // ...
  onEvent={({ name, payload }) => {
    if (name === 'ad.no-fill') {
      console.log('Ad is not available');
    }
  }}
/>
```

## Links

* [NPM Package](https://www.npmjs.com/package/@kontextso/sdk-react)
* [React Demo Project](https://github.com/kontextso/sdk-react-demo/tree/v3)


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