> For the complete documentation index, see [llms.txt](https://docs.amply.tools/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.amply.tools/reference/sdk-react-native.md).

# React Native SDK

Public API surface for `@amplytools/react-native-amply-sdk`. All functions are exported by name from the package root and are also available on the default export.

## At a glance

| Group           | Function                                                                                                                                                                  |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Initialization  | `initialize(config)`, `isInitialized()`                                                                                                                                   |
| Event tracking  | `track(payload)`                                                                                                                                                          |
| User attributes | `setUserId(userId)`, `setCustomProperty(key, value)`, `setCustomProperties(properties)`, `getCustomProperty(key)`, `removeCustomProperty(key)`, `clearCustomProperties()` |
| Deeplinks       | `addDeepLinkListener(listener)`                                                                                                                                           |
| System events   | `addSystemEventListener(listener)`, `addSystemEventsListener(listener)`, `systemEvents.addListener(listener)`, `useAmplySystemEvents(options)`                            |
| Data inspection | `getRecentEvents(limit)`, `getDataSetSnapshot(type)`                                                                                                                      |
| Logging         | `setLogLevel(level)`, `getLogLevel()`                                                                                                                                     |
| Utilities       | `formatSystemEventLabel(event, options)`, `removeAllListeners()`                                                                                                          |

## Initialization

### `initialize(config: AmplyInitializationConfig): Promise<void>`

Configure the SDK and start the first session. Call once at app startup before any other SDK call.

| Name     | Type                        | Required | Description            |
| -------- | --------------------------- | -------- | ---------------------- |
| `config` | `AmplyInitializationConfig` | yes      | See the Types section. |

Returns `Promise<void>` that resolves when native init completes. If `config.debug` or `config.logLevel` is set, a console log listener is registered automatically.

### `isInitialized(): boolean`

Synchronously check whether `initialize` has finished. Takes no parameters. Returns `boolean`. Useful for guarding calls in hot-reload environments.

## Event tracking

### `track(payload: TrackEventPayload): Promise<void>`

Record a custom event.

| Name      | Type                | Required | Description              |
| --------- | ------------------- | -------- | ------------------------ |
| `payload` | `TrackEventPayload` | yes      | `{ name, properties? }`. |

Returns `Promise<void>` resolved after the event is handed to the native queue. Events are persisted locally and flushed by the SDK.

## Gating

Gate a user-facing step on a campaign's outcome — for example, a rewarded ad before an export. See [Gating actions](/developer-guide/gating-actions.md) for the full flow.

### `trackGated(event: string, properties?: Record<string, CustomPropertyValue>): Promise<GateDecision>`

Track an event and wait for any gating campaign on it to resolve, then resolve with the decision. If no gate applies, resolves to `{ outcome: 'proceed', reason: 'failOpen' }` immediately. **Never rejects.**

| Name         | Type                                  | Required | Description                     |
| ------------ | ------------------------------------- | -------- | ------------------------------- |
| `event`      | `string`                              | yes      | Event name a campaign may gate. |
| `properties` | `Record<string, CustomPropertyValue>` | no       | Event properties.               |

### `registerGate(baseUrl: string, presenter: GatePresenter, options?: GateOptions): Promise<() => void>`

Register the single gate presenter once at startup. Resolves to an **unregister** function. The SDK calls the presenter when a gated campaign needs to show UI.

| Name        | Type            | Required | Description                                                                                                   |
| ----------- | --------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `baseUrl`   | `string`        | yes      | Base URL the gate resolves against.                                                                           |
| `presenter` | `GatePresenter` | yes      | `(params, info, resolution) => void` — shows the gated UI.                                                    |
| `options`   | `GateOptions`   | no       | `{ onAbort?: 'cancel' \| 'proceed'; timeoutMs?: number }`. Defaults: `onAbort: 'cancel'`, `timeoutMs: 60000`. |

### `GateDecision`

A plain object, one of:

| Shape                                                       | Meaning                                                                                                                                       |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `{ outcome: 'proceed', reason: 'completed' \| 'failOpen' }` | Do the next step. `completed` = value-exchange satisfied (reward earned); `failOpen` = nothing to wait on / couldn't resolve — do not reward. |
| `{ outcome: 'cancelled' }`                                  | User deliberately dismissed a `cancel`-policy gate. Suppress the next step.                                                                   |

Branch on `decision.outcome === 'proceed'`.

### Resolution (presenter callback)

The third argument the SDK passes to your `presenter` reports the outcome exactly once:

* `resolution.completed()` — value-exchange satisfied → the gate proceeds.
* `resolution.dismissed()` — user backed out → honors the `onAbort` option.
* `resolution.unavailable()` — couldn't run (no fill / error) → fail-open.

## User attributes

### `setUserId(userId: string | null): void`

Associate subsequent events with a user identifier. Pass `null` to clear.

| Name     | Type             | Required | Description                                   |
| -------- | ---------------- | -------- | --------------------------------------------- |
| `userId` | `string \| null` | yes      | Stable user identifier, or `null` to log out. |

Returns `void`. Survives across sessions until changed.

### `setCustomProperty(key: string, value: CustomPropertyValue): void`

Set one custom property.

| Name    | Type                  | Required | Description                                                   |
| ------- | --------------------- | -------- | ------------------------------------------------------------- |
| `key`   | `string`              | yes      | Property key (max 32 characters).                             |
| `value` | `CustomPropertyValue` | yes      | `string`, `number`, or `boolean`. Strings max 255 characters. |

Returns `void`. Implemented as a `setCustomProperties` call with a single entry.

### `setCustomProperties(properties: Record<string, CustomPropertyValue>): void`

Set multiple custom properties in one call.

| Name         | Type                                  | Required | Description               |
| ------------ | ------------------------------------- | -------- | ------------------------- |
| `properties` | `Record<string, CustomPropertyValue>` | yes      | Keys to supported values. |

Returns `void`.

### `getCustomProperty(key: string): Promise<CustomPropertyValue | null>`

Read the current value of a custom property.

| Name  | Type     | Required | Description   |
| ----- | -------- | -------- | ------------- |
| `key` | `string` | yes      | Property key. |

Returns `Promise<CustomPropertyValue | null>` — the stored value or `null` if unset.

### `removeCustomProperty(key: string): void`

Delete a single custom property.

| Name  | Type     | Required | Description             |
| ----- | -------- | -------- | ----------------------- |
| `key` | `string` | yes      | Property key to remove. |

Returns `void`.

### `clearCustomProperties(): void`

Remove every custom property on the current user. Takes no parameters. Returns `void`.

## Deeplinks

### `addDeepLinkListener(listener: (event: DeepLinkEvent) => void): Promise<() => void>`

Register a handler for campaign deep link URLs. Registers the native listener on the first call and reuses it for subsequent subscribers.

| Name       | Type                             | Required | Description                      |
| ---------- | -------------------------------- | -------- | -------------------------------- |
| `listener` | `(event: DeepLinkEvent) => void` | yes      | Called for each deep link event. |

Returns `Promise<() => void>` — an unsubscribe function. Invoke it (for example in a `useEffect` cleanup) to stop receiving events.

## System events

For the full list of system-event names and their payloads (`SessionStarted`, `CustomPropertyChanged`, `CampaignResolved`, …), see [Events](/reference/events.md). The methods below subscribe to them.

### `addSystemEventListener(listener: (event: EventRecord) => void): Promise<() => void>`

Register a handler for SDK lifecycle events. `DebugLog` events are filtered out and handled by the console output listener.

| Name       | Type                           | Required | Description                   |
| ---------- | ------------------------------ | -------- | ----------------------------- |
| `listener` | `(event: EventRecord) => void` | yes      | Called for each system event. |

Returns `Promise<() => void>` — an unsubscribe function.

### `addSystemEventsListener(listener: (event: EventRecord) => void): Promise<() => void>`

Alias for `addSystemEventListener`. Same parameters, same return.

### `systemEvents.addListener(listener: (event: EventRecord) => void): Promise<() => void>`

Namespaced alias for `addSystemEventListener`. Same parameters, same return.

### `useAmplySystemEvents(options?: UseAmplySystemEventsOptions): UseAmplySystemEventsResult`

React hook that subscribes to system events and returns the accumulated list.

| Name                 | Type                           | Required | Description                                                                       |
| -------------------- | ------------------------------ | -------- | --------------------------------------------------------------------------------- |
| `options.maxEntries` | `number`                       | no       | Maximum entries kept in state. Defaults to 50.                                    |
| `options.dedupe`     | `boolean`                      | no       | If `true`, drops events with the same `name`+`timestamp` key. Defaults to `true`. |
| `options.onEvent`    | `(event: EventRecord) => void` | no       | Side-effect callback invoked for every non-deduped event.                         |

Returns `{ events: EventRecord[]; reset: () => void }`. `reset()` clears the buffered events and the dedupe cache. The subscription is torn down on unmount.

## Data inspection

### `getRecentEvents(limit: number): Promise<EventRecord[]>`

Fetch the most recent events tracked in the current install. Intended for in-app debug tools.

| Name    | Type     | Required | Description                         |
| ------- | -------- | -------- | ----------------------------------- |
| `limit` | `number` | yes      | Maximum number of events to return. |

Returns `Promise<EventRecord[]>` newest-first.

### `getDataSetSnapshot(type: DataSetType): Promise<DataSetSnapshot>`

Return a snapshot of one dataset the SDK uses for targeting.

| Name   | Type          | Required | Description                  |
| ------ | ------------- | -------- | ---------------------------- |
| `type` | `DataSetType` | yes      | Dataset selector. See Types. |

Returns `Promise<DataSetSnapshot>` — a JSON object whose shape depends on the selector.

## Logging

### `setLogLevel(level: LogLevel): void`

Set the SDK log level at runtime. If `level !== 'none'`, a console log listener is registered automatically.

| Name    | Type       | Required | Description                                            |
| ------- | ---------- | -------- | ------------------------------------------------------ |
| `level` | `LogLevel` | yes      | `'none'`, `'error'`, `'warn'`, `'info'`, or `'debug'`. |

Returns `void`.

### `getLogLevel(): LogLevel`

Return the current log level. Takes no parameters. Returns `LogLevel`.

## Utilities

### `formatSystemEventLabel(event: EventRecord, options?: FormatOptions): string`

Format an `EventRecord` into a short human-readable label. Used by debug panels.

| Name              | Type          | Required | Description                                                                                  |
| ----------------- | ------------- | -------- | -------------------------------------------------------------------------------------------- |
| `event`           | `EventRecord` | yes      | The event to label.                                                                          |
| `options.verbose` | `boolean`     | no       | When `true`, includes detailed campaign info for `ConfigFetchFinished`. Defaults to `false`. |

Returns `string`. Produces a short readable label for each recognized system event name; unknown names return `"System event <name>"`. For the full list of system event names and their properties, see [Events](/reference/events.md).

### `removeAllListeners(): void`

Invoke every unsubscribe function tracked for deep link listeners. Takes no parameters. Returns `void`. Useful during a full SDK teardown (tests, hot reload).

## Types

### `AmplyInitializationConfig`

```ts
type AmplyInitializationConfig = {
  appId: string;
  apiKeyPublic: string;
  apiKeySecret?: string | null;
  configBaseUrl?: string | null;
  backendBaseUrl?: string | null;
  /** @deprecated older spelling of backendBaseUrl */
  endpoint?: string | null;
  defaultConfig?: string | null;
  debug?: boolean | null;
  logLevel?: LogLevel | null;
};
```

| Field            | Required | Description                                                                                                                                               |
| ---------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appId`          | yes      | Application identifier from the Amply dashboard.                                                                                                          |
| `apiKeyPublic`   | yes      | Public API key.                                                                                                                                           |
| `apiKeySecret`   | no       | Secret API key.                                                                                                                                           |
| `configBaseUrl`  | no       | Base URL for campaign config. Needed together with `backendBaseUrl` to point the app at a non-production stack — the two are served from different hosts. |
| `backendBaseUrl` | no       | Base URL for session and event delivery.                                                                                                                  |
| `endpoint`       | no       | Deprecated spelling of `backendBaseUrl`, kept for existing callers. Never covered the config host. Ignored when `backendBaseUrl` is set.                  |
| `defaultConfig`  | no       | JSON string used as the fallback config until the remote config loads.                                                                                    |
| `debug`          | no       | Shortcut for `logLevel: 'debug'`.                                                                                                                         |
| `logLevel`       | no       | Explicit log level. Takes precedence over `debug`.                                                                                                        |

### `TrackEventPayload`

```ts
type TrackEventPayload = {
  name: string;
  properties?: JsonMap | null;
};
```

`JsonMap = { [key: string]: unknown }`.

### `EventRecord`

```ts
type EventRecord = {
  id?: string | null;
  name: string;
  type: EventType;         // 'custom' | 'system'
  timestamp: number;       // UTC epoch milliseconds
  properties: JsonMap;
};
```

### `DeepLinkEvent`

```ts
type DeepLinkEvent = {
  url: string;
  info: JsonMap;
  consumed: boolean;       // true if a prior listener handled the URL
};
```

### `DataSetType`

Discriminated union:

```ts
type DataSetType =
  | { kind: '@device' }
  | { kind: '@user' }
  | { kind: '@session' }
  | { kind: '@triggeredEvent'; data: TriggeredEventData }
  | { kind: '@events'; data: EventsDataSetEvent[] };
```

`@custom` (a snapshot of all custom properties) is available on iOS and Android but is **not** exposed in the React Native union. To inspect custom properties in RN, read them back individually with `getCustomProperty(key)`.

Supporting types:

```ts
type TriggeredEventCountStrategy = 'global' | 'session';

type TriggeredEventParam = {
  name: string;
  value: unknown;
};

type TriggeredEventData = {
  countStrategy: TriggeredEventCountStrategy;
  params: TriggeredEventParam[];
  eventName?: string | null;
};

type EventsDataSetEvent = {
  name: string;
  type: EventType;         // 'custom' | 'system'
  params: TriggeredEventParam[];
};
```

### `CustomPropertyValue`

```ts
type CustomPropertyValue = string | number | boolean;
```

Narrower than the native SDKs, which also accept `Long`, `Float`, `Double`, and `DateTimeValue`.

### `LogLevel`

```ts
type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
```

`'none'` silences all output. `'debug'` includes everything.

### System event names

Well-known values on `EventRecord.name` when `type === 'system'`. See [Events](/reference/events.md) for the canonical list with full property details and observability notes.

## Related

* [iOS SDK reference](/reference/sdk-ios.md) — Swift surface for native iOS apps.
* [Android SDK reference](/reference/sdk-android.md) — Kotlin surface for native Android apps.
