# React Native SDK

Source: https://kirora.io/docs/sdks/react-native

Track signed-in customer activity in your React Native app and send push notifications on iOS and Android.

Use the React Native SDK to see what customers do in your app and reach them with push, on iOS and Android from one TypeScript API. Track events and visits for segments and journeys, register devices for push, and report opens and clicks without extra code. Kirora's native [iOS](https://kirora.io/docs/sdks/ios) and [Android](https://kirora.io/docs/sdks/android) SDKs do the work underneath: they keep events on the device while it's offline, handle sessions and consent, and show the notifications.

## Before you start

- **React Native 0.71 or later.** It's tested with React Native 0.88, and works on the New Architecture through React Native's interop layer.
- **Android 7.0 (API 24) or later**, compiled with `compileSdkVersion` 35 or later. **iOS 13 or later.**
- **A server you control** that can sign a token for the signed-in user. Every Kirora server library does it in one call.
- **For push:** an iOS push app, an Android push app, or both in Kirora. See [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push), and [Get your Apple and Firebase keys](https://kirora.io/docs/guides/getting-started/get-push-keys) if you haven't used either before.

Using Expo? Follow the [Expo guide](https://kirora.io/docs/sdks/expo) first: its config plugin does the native setup for you.

## How it works

The SDK runs on your users' phones, so it never holds an API key. It uses two things instead:

- **A client key** (`kirora_pk_…`): public, safe to ship in the app. It says which workspace the events belong to.
- **A user token**: signed by your server for the user who is signed in, so nobody can send events as someone else. The SDK asks your server for one at sign-in and when one expires.

> [!WARNING]
> Never put an API key or the SDK token secret in your app's code, its bundle or its logs. Both stay on your server.

## 1. Create your keys

In the dashboard, open **Developer → SDK**. An owner, admin or developer chooses **Set up the SDK**, which creates both keys. The **Secret key** is your token secret, shown only once: put it in your server's environment as `KIRORA_SDK_TOKEN_SECRET`. The **Public key** is your client key, and goes in your app.

## 2. Add a token route to your server

Add a route that signs a token for the user of the current session. Take the user's id from your own session, never from the app's request:

```ts
// Express, with the Node.js library
import { createUserToken } from '@kirora/node';

app.get('/kirora-token', requireSignedIn, (request, response) => {
  response.set('Cache-Control', 'no-store');
  response.type('text/plain').send(createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, String(request.user.id)));
});
```

Return `401` when nobody is signed in. The [Go](https://kirora.io/docs/sdks/go#sign-tokens-for-the-web-sdk), [.NET](https://kirora.io/docs/sdks/dotnet#sign-tokens-for-the-web-sdk), [PHP](https://kirora.io/docs/sdks/php#sign-tokens-for-the-web-sdk) and [Laravel](https://kirora.io/docs/sdks/laravel#sign-tokens-for-the-web-sdk) libraries sign the same token. In any other language, sign an HS256 JWT with the token secret, with `sub` set to your id for the user (their contact's `externalId`) and `exp` no more than 24 hours after `iat`.

## 3. Install the SDK

```sh
npm install @kirora/react-native
cd ios && pod install
```

Then rebuild the app with `npx react-native run-ios` or `run-android`: a Metro reload can't add native code. Autolinking adds the native module, so don't register it again by hand.

On Android, the SDK brings Firebase Messaging and the notification permission into your app, even if you don't use push yet.

## 4. Start the SDK

Create one client when your app starts, outside any component:

```ts
// src/kirora.ts
import { Kirora } from '@kirora/react-native';

export const kirora = new Kirora({
  clientKey: 'kirora_pk_…', // public: safe in the app
  fetchUserToken: () => api.fetchKiroraToken(), // the token text from your route in step 2
});
```

`fetchUserToken` is your app's signed-in request to the route from step 2. It returns the response body, the token itself, as a string. Throw when it fails, so the SDK keeps the events and tries again later.

Keep this one client for the life of the app. Creating another replaces the first, so never create one per screen or render.

## 5. Sign users in and out

```ts
import { kirora } from './kirora';

// Each time the app starts with a signed-in user, and right after they sign in.
await kirora.identify();

// Before your own sign-out.
await kirora.logout();
```

Nothing is sent before sign-in: events tracked earlier wait on the device and go as the user who signs in next. `logout()` tries for up to five seconds to send what's waiting and stop this device's pushes for the user, then forgets the rest. Offline, stopping pushes is retried while the app runs, for up to 24 hours.

`identify()` throws a `KiroraError` when it can't get or use a token. If the token fails later, in the background, the SDK calls `onAuthenticationFailed` with `'fetch_failed'` or `'refused'`. Use it to sign the user out, or call `identify()` again once your session is fixed.

## 6. Track what they do

```ts
kirora.track('Order Completed', { order_id: 'A-1042', total: 46.5, currency: 'USD' });
kirora.trackScreenView('Checkout');
```

`track()` returns at once and never throws: events go in [batches](#delivery-and-storage). Properties take strings, numbers, booleans, `null`, arrays and plain objects; dates are sent as ISO 8601 strings. Name events as the [naming guide](https://kirora.io/docs/sdks/web#naming-events) describes, so journeys and segments can match them.

## 7. Check it works

Sign in on a device or emulator, track an event, then call `await kirora.flush()` to send it now. Open the contact in **Contacts** in Kirora: the event is on their activity. While you build, set `logLevel: 'debug'` to see each event and batch in the native logs.

If `kirora.isAvailable` is `false`, the native module isn't in your build: every method does nothing. Rebuild the app.

## Ask for tracking consent

Where the law asks for consent before tracking, start the SDK with `requireTrackingConsent: true` and pass on the user's answer:

```ts
kirora.setTrackingConsent(true);  // they agreed
kirora.setTrackingConsent(false); // they refused, or withdrew
```

Nothing is tracked or kept until the user agrees. The answer is remembered on the device, and `false` stops tracking. Tracking consent covers events, screens and visits only: push permission and push consent are separate, below.

## Send push notifications

### Turn push on

1. **In Kirora**, add a push app for each platform. See [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push).
2. **Set up each platform**, below.
3. **In your app**, add `push: true` to the client's options. If the workspace has several push apps for a platform, choose one with `push: { pushAppId: '…' }`.
4. **Ask for permission** at a moment the user understands, after they've signed in:

```ts
const permission = await kirora.requestPushPermission(); // 'granted', 'denied', 'unanswered' or 'unsupported'

if (permission === 'granted' && userOptedInToMarketing) {
  await kirora.setPushConsent(true); // their consent to marketing push
}
```

The device is registered at `identify()` and when permission is granted. Permission is enough for a transactional push, such as an order update. Campaign and journey push also need the user's marketing consent, which `setPushConsent()` records. `userOptedInToMarketing` stands for their answer to your own opt-in, such as a checkbox: allowing notifications alone isn't marketing consent. It throws if Kirora didn't record it, so only show the choice as saved once it resolves.

### Android

1. Add your app to Firebase and put its `google-services.json` in `android/app/`. Apply the Google Services Gradle plugin in `android/build.gradle` and `android/app/build.gradle`, as in the [Android SDK](https://kirora.io/docs/sdks/android#turn-push-on). New to Firebase? See [Get your Apple and Firebase keys](https://kirora.io/docs/guides/getting-started/get-push-keys).
2. In Kirora, upload a Firebase service account file to the Android push app.
3. Add a white-on-transparent notification icon to your app's drawables and name it in the options:

```ts
push: {
  smallIcon: 'ic_notification',
  accentColor: '#FF5500',
  defaultChannelId: 'kirora_default',
  defaultChannelName: 'Notifications',
}
```

On Android 13 and later, `requestPushPermission()` shows the system prompt. The SDK's own Firebase messaging service shows Kirora's pushes and ignores other messages. To receive those too, register a fallback handler in native code, or, if your app has its own `FirebaseMessagingService`, forward Kirora's messages and token changes to the SDK; the [Android SDK](https://kirora.io/docs/sdks/android#send-push-notifications) shows both. A token from a JavaScript messaging library can be passed with `kirora.onNewPushToken(token)`.

### iOS

1. In Xcode, add the **Push Notifications** capability to your app target.
2. In Kirora, upload your APNs key (`.p8`) to the iOS push app, with its key ID, team ID and your app's bundle ID.
3. For images, buttons and delivery reports, add a notification service extension. Without it, a push still arrives and taps are still reported, but it shows plainly:
   1. In Xcode, choose **File → New → Target → Notification Service Extension**.
   2. In `ios/Podfile`, add the extension's pod, then run `pod install`:

      ```ruby
      target 'NotificationService' do
        pod 'KiroraNotificationService', :path => File.join(File.dirname(`node --print "require.resolve('@kirora/react-native/package.json')"`), 'ios', 'vendor', 'kirora-ios')
      end
      ```

   3. Replace the generated `NotificationService.swift` with:

      ```swift
      import KiroraNotificationService

      final class NotificationService: KiroraNotificationServiceExtension {}
      ```

The SDK receives the APNs token and taps on its own, with no code of yours. If your iOS push app sends through Firebase, install and configure Firebase's iOS SDK too: `push: true` doesn't add it.

### Handle taps and links

A tap opens the app and is reported as an open, or a click when it has a link. To route a push's link in your app, add `handleDeepLink` to the client's options:

```ts
handleDeepLink: (url) => {
  if (!url.startsWith('myapp://orders/')) return false;
  router.navigate(url);
  return true; // your app handled it
},
```

Return `false`, or don't answer within 1.5 seconds, and the SDK opens the link itself. A tap that launched the app is held while your app starts. On iOS, claim your universal links here, or they may open in the browser.

To act on a tap or a push in your own code:

```ts
const offClick = kirora.onNotificationClicked((data) => {
  // the push's data, as strings; the SDK has already reported the tap and opened its link
});
const offReceived = kirora.onNotificationReceived((data) => {
  // Android only: a push arrived
});

// When the screen that listens goes away:
offClick();
offReceived();
```

Don't open the link again in `onNotificationClicked`. To decide whether a push shows while the app is open, add `onForegroundNotification: (data) => boolean` to the push options; it must answer within about 1.5 seconds.

### Test a push

Use a real device for iOS: the simulator can't receive remote pushes from Kirora. On iOS, register your test device to the right push app: **Sandbox** for a build run from Xcode or `npx expo run:ios`, **Production** for every EAS build, TestFlight, ad hoc and App Store builds. See [Sandbox or Production](https://kirora.io/docs/guides/getting-started/get-push-keys#sandbox-or-production). Sign in, allow notifications, then send yourself a test from the push step's **Send test**. To check delivery and tap reports, send a campaign to a segment with just you in it: test sends aren't counted.

## Visits and app events

- **Visits:** a visit starts with a `Session Started` event, and every event in it carries the same `context.sessionId`. Visits are on by default; `trackSessions: false` turns them off.
- **App events:** `trackAppLifecycle: true` records `Application Installed`, `Application Updated`, `Application Opened` and `Application Backgrounded`. It's off by default.
- **Screens:** call `trackScreenView()` from the screens you care about, for example from your navigation container's state change. Screens aren't tracked automatically.
- **Context:** the native SDKs add the app version, the OS, the screen and the device's language and time zone to each event, with a random id for this install. Never an advertising id.

To remove a field, or drop an event, before it's stored, use `beforeSend`. It sees the events your app tracks, not the SDK's own:

```ts
beforeSend: (event) => {
  if (event.name === 'Sensitive Action') return null; // drop it
  const properties = { ...event.properties };
  delete properties.email;
  return { ...event, properties };
},
```

It must answer at once: a promise drops the event.

## Options

| Option | Default | What it does |
| --- | --- | --- |
| `clientKey` | Required | The workspace's public key (`kirora_pk_…`). |
| `fetchUserToken` | None | Asks your server for a user token. Times out after 30 seconds. |
| `push` | Off | `true`, or options: `pushAppId`, and on Android `smallIcon`, `accentColor`, `defaultChannelId`, `defaultChannelName`; `onForegroundNotification` on both. |
| `requireTrackingConsent` | `false` | Track and keep nothing until `setTrackingConsent(true)`. |
| `trackSessions` | `true` | Record `Session Started` and the visit on every event. |
| `trackAppLifecycle` | `false` | Record install, update, open and background events. |
| `handleDeepLink` | None | Routes a push's link. Return `true` when your app handled it. |
| `onAuthenticationFailed` | None | Called when the user's token fails in the background. |
| `beforeSend` | None | Edits or drops each event your app tracks before it's stored. |
| `logLevel` | `'error'` | `'none'`, `'error'` or `'debug'`. |
| `apiUrl` | `https://api.kirora.io` | For tests against a mock server. |

## Methods

| Method | Does |
| --- | --- |
| `identify(token?)` | Signs the user in, with a token from `fetchUserToken` unless given one; registers for push if allowed; sends waiting events. |
| `logout()` | Tries for up to five seconds to send what's waiting and stop this device's pushes, then forgets the user. |
| `track(name, properties?)` | Records an event. Returns at once. |
| `trackScreenView(name)` | Records `Screen Viewed`. |
| `setTrackingConsent(granted)` | Records the user's tracking answer. |
| `requestPushPermission()` | Shows the system prompt when needed and registers the device. |
| `getPushStatus()` | `'enabled'`, `'disabled'`, `'denied'`, `'unanswered'` or `'unsupported'`. Never prompts. |
| `setPushEnabled(enabled)` | Turns push on or off for this device, for every user. Never prompts. |
| `setPushConsent(granted)` | Records the signed-in user's consent to marketing push. |
| `onNotificationClicked(listener)` | Hears taps on Kirora pushes. Returns a function that stops listening. |
| `onNotificationReceived(listener)` | Hears Kirora pushes as they arrive, on Android. |
| `onNewPushToken(token)` | Passes an Android token from another messaging library. |
| `flush()` | Sends waiting events now. Rarely needed. |
| `getState()` | What the SDK knows now, for debugging: signed in, device id, queued events. |
| `destroy()` | Stops the client. Waiting events stay for the next one. |

Errors are `KiroraApiError` (with `status`, `code`, `retryAfterMs` and `retryable`), `UserTokenError` when `fetchUserToken` fails, or `KiroraError`.

## Delivery and storage

- **Batches:** events go when 20 are waiting, otherwise every 30 seconds, and when the app goes to the background. A batch holds up to 100.
- **Retries:** when the device is offline or Kirora is busy, the SDK retries with growing gaps, never sooner than Kirora's `Retry-After`. Each event keeps its idempotency key, so a retry is recorded once.
- **On the device:** up to 1,000 events wait in the app's storage. Beyond that, the oldest are dropped. Tokens are kept in memory only.
- **Plan limit:** past your plan's tracked events for the month, Kirora refuses further events and the SDK drops them. Sign-in and push still work.

## Test your code

In Jest, without native code, use the SDK's mock. It records calls with `jest.fn()`:

```js
jest.mock('@kirora/react-native', () => require('@kirora/react-native/jest'));
```

## Troubleshooting

| Symptom | Check |
| --- | --- |
| `kirora.isAvailable` is `false` | The native module isn't in your build. Run `pod install` and rebuild the app; in Expo, use a development build. |
| Events stay on the device | The user is signed in with `identify()`, tracking consent is given, and your token route returns a token. |
| `401` or a token error | The token is signed with this workspace's secret, names the signed-in user and hasn't expired. |
| No Android pushes | `google-services.json` in `android/app/`, and the service account uploaded to the Android push app. |
| White square for the Android icon | Use a white-on-transparent drawable for `smallIcon`. |
| No iOS image or buttons | The notification service extension and its `KiroraNotificationService` pod. |
| Links open twice | Route links in `handleDeepLink` only, not again in `onNotificationClicked`. |
| No delivery or tap reports | Send a campaign, not a test: test sends aren't counted. |

## Next steps

- [Expo](https://kirora.io/docs/sdks/expo) — the config plugin that does the native setup on every prebuild.
- [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push) — add the push apps the SDK registers with.
- [Create a push notification](https://kirora.io/docs/guides/messaging/push/create-a-push-notification) — write one, with an image and buttons.
- [Source on GitHub](https://github.com/kiroratech/kirora-react-native) — the full reference, changelog and issues.