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

# React Native & Expo

Integrate OnsideKit into a React Native or Expo app with the @onside-io/react-native-onsidekit package — an Expo module over the native iOS SDK.

The **`@onside-io/react-native-onsidekit`** package lets you use OnsideKit from JavaScript/TypeScript in a React Native app that ships to iOS. It is built on the [Expo Modules API](https://docs.expo.dev/modules/overview/) and mirrors the native API one to one: the same objects and calls as `Onside` in Swift, with no logic of its own. Products, payments and transactions are native-backed objects, so the [Core Concepts](https://docs.onside.io/sdk/core-concepts/payment-queue.md) and [Error Reference](https://docs.onside.io/sdk/reference/errors.md) pages apply as is.

* **Package:** [`@onside-io/react-native-onsidekit`](https://www.npmjs.com/package/@onside-io/react-native-onsidekit) on npm
* **Requires:** Expo SDK 58+, React Native 0.88+, Xcode 27+, iOS 17.4+
* **Works with:** Expo prebuild / development builds and bare React Native projects
* **Platforms:** iOS only — Android is not supported

{% hint style="info" %}
The package contains native code, so it does not run in **Expo Go**. Use a [development build](https://docs.expo.dev/develop/development-builds/introduction/) or a bare React Native project.
{% endhint %}

The package version always matches the native OnsideKit version it bundles: `@onside-io/react-native-onsidekit@3.0.1` contains OnsideKit 3.0.1. The `OnsideKit.xcframework` ships inside the npm package, so `pod install` needs no extra sources or network access, and your lockfile pins the exact SDK build. The framework includes its device dSYM, so Xcode adds it to your archive and crash reporters symbolicate OnsideKit frames automatically.

## 1. Install the package

```bash
npm install @onside-io/react-native-onsidekit
```

## 2. Configure the iOS project

{% tabs %}
{% tab title="Expo (prebuild)" %}
Add the config plugin to `app.json` (or `app.config.js`):

```json
{
  "expo": {
    "ios": {
      "deploymentTarget": "17.4"
    },
    "plugins": [
      [
        "@onside-io/react-native-onsidekit",
        {
          "callbackScheme": "myapp-onside",
          "applePayMerchantId": "merchant.com.yourcompany.app",
          "storeKitConfigurationPath": "./TestProducts.storekit"
        }
      ]
    ]
  }
}
```

| Option                      | Required | What the plugin does                                                                                                                                                                                                  |
| --------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `callbackScheme`            | Yes      | Registers the scheme in `CFBundleURLTypes` and adds `onside` to `LSApplicationQueriesSchemes`. Prebuild fails if it's missing or empty.                                                                               |
| `applePayMerchantId`        | No       | A merchant ID or an array of IDs, added to the `com.apple.developer.in-app-payments` entitlement. See [Apple Pay](https://docs.onside.io/sdk/purchasing/apple-pay.md).                                                |
| `storeKitConfigurationPath` | No       | Path (relative to the project root) to a `.storekit` file. The file is copied into the iOS project and added to the app bundle for [local testing](https://docs.onside.io/sdk/advanced-and-tooling/local-testing.md). |

The plugin also raises the iOS deployment target to **17.4** if it is lower.

Then generate the native project:

```bash
npx expo prebuild --platform ios
```

{% hint style="warning" %}
The plugin only writes the native project configuration. You still pass the same scheme to `Onside.setCallbackScheme(...)` at runtime and the merchant ID to `Onside.setApplePayMerchantIdentifier(...)` — see the next step.
{% endhint %}
{% endtab %}

{% tab title="Bare React Native" %}

1. Install Expo modules support with [`npx install-expo-modules`](https://docs.expo.dev/bare/installing-expo-modules/). The package depends on `expo`.
2. Set the iOS deployment target to **17.4** or later (`platform :ios, '17.4'` in the `Podfile` and in the Xcode target).
3. Run `cd ios && pod install`.
4. In `Info.plist`, add `onside` to `LSApplicationQueriesSchemes` and your callback scheme to `CFBundleURLTypes` — see [Initializing the SDK](https://docs.onside.io/sdk/getting-started/initialization.md).
5. Make sure incoming URLs reach React Native `Linking`, so you can forward them to `Onside.handle(url)` — see the next step. The React Native 0.88 app template already does this; if you replaced its `AppDelegate` or `SceneDelegate`, forward `scene(_:openURLContexts:)` to `RCTLinkingManager`.
6. For Apple Pay, add the merchant ID to the **Apple Pay** capability of your target — see [Apple Pay](https://docs.onside.io/sdk/purchasing/apple-pay.md).
   {% endtab %}
   {% endtabs %}

## 3. Initialize and forward callback URLs

Initialize the SDK once at startup, before any other `Onside` call, then set the callback scheme and forward every incoming URL to `Onside.handle(url)`. The package does not intercept URLs on its own — forward both the URL the app was launched with and URLs received while it runs:

```ts
import { Linking } from 'react-native';
import { Onside } from '@onside-io/react-native-onsidekit';

export async function setUpOnside() {
  await Onside.initialize();
  await Onside.setCallbackScheme('myapp-onside');
  await Onside.setApplePayMerchantIdentifier('merchant.com.yourcompany.app'); // full build only

  const initialUrl = await Linking.getInitialURL();
  if (initialUrl) {
    await Onside.handle(initialUrl);
  }
  Linking.addEventListener('url', ({ url }) => {
    void Onside.handle(url);
  });
}
```

`Onside.handle(url)` resolves to `false` for URLs that are not OnsideKit callbacks, so you can route those yourself. Calling any `Onside` API before `initialize()` is undefined behavior.

`initialize` takes the same options as the native call — see [Initializing the SDK](https://docs.onside.io/sdk/getting-started/initialization.md):

```ts
await Onside.initialize({
  storeKitConfigurationName: 'TestProducts', // local testing only; omit in production
  disableSSLPinning: false,                  // debugging aid only
});
```

## 4. Observe the payment queue

Register the transaction listener early — at startup, before the first purchase — so transactions left unfinished in a previous session are delivered too. Keep a long-lived reference to the queue object (for example, in a module-level variable): the native observer is removed when the JS object is garbage-collected.

```ts
import { Onside, OnsidePaymentTransaction } from '@onside-io/react-native-onsidekit';

const queue = Onside.defaultPaymentQueue();

queue.addListener('updatedTransactions', async (transactions: OnsidePaymentTransaction[]) => {
  for (const transaction of transactions) {
    switch (transaction.transactionState) {
      case 'purchased':
      case 'restored':
        await deliverContent(transaction); // validate on your backend, grant content
        await queue.finishTransaction(transaction);
        break;
      case 'failed':
        console.warn('Purchase failed:', transaction.error);
        await queue.finishTransaction(transaction);
        break;
      default:
        break; // 'purchasing' — wait for the next update
    }
  }
});
```

See [The Payment Queue & Transactions](https://docs.onside.io/sdk/core-concepts/payment-queue.md) for the transaction lifecycle and why every purchased, restored, or failed transaction must be finished.

## 5. Fetch products

`makeProductsRequest` returns a request object that reports through events. Keep a reference to it until it finishes:

```ts
import { Onside, OnsideProductsResponse } from '@onside-io/react-native-onsidekit';

function fetchProducts(ids: string[]): Promise<OnsideProductsResponse> {
  const request = Onside.makeProductsRequest(ids);
  return new Promise((resolve, reject) => {
    request.addListener('didReceive', resolve);
    request.addListener('didFail', (error) => reject(new Error(error)));
    void request.start();
  });
}

const response = await fetchProducts(['coins.100', 'premium.monthly']);
response.products.forEach((p) => console.log(p.productIdentifier, p.price.value, p.price.currencyCode));
```

`invalidProductIdentifiers` and `unsupportedProductIdentifiers` list the identifiers that were not returned. See [Fetching Products](https://docs.onside.io/sdk/products-and-subscriptions/fetching-products.md).

## 6. Make a purchase

```ts
import { Onside, OnsidePayment, OnsideProduct } from '@onside-io/react-native-onsidekit';

async function buy(product: OnsideProduct) {
  const payment = new OnsidePayment(product);
  payment.appAccountToken = currentUserId; // optional
  try {
    await Onside.defaultPaymentQueue().add(payment);
  } catch (error: any) {
    // Pre-flight failure, e.g. 'loginDiscarded' — nothing was enqueued.
    console.warn("Couldn't start the purchase:", error.code);
  }
}
```

`add` resolves once the payment is accepted into the queue — not when the purchase completes. The result arrives through `updatedTransactions`. If the user is not logged in, the login flow is presented automatically. See [Making a Purchase](https://docs.onside.io/sdk/purchasing/making-a-purchase.md).

## Other features

**Restore purchases** — restored transactions arrive through `updatedTransactions`; the end of the restore is reported by queue events:

```ts
queue.addListener('restoreCompletedTransactionsFinished', () => { /* done */ });
queue.addListener('restoreCompletedTransactionsFailed', (error) => { /* e.g. 'connectionError' */ });
await queue.restoreCompletedTransactions(); // rejects with e.g. 'loginDiscarded'
```

**Login & account** — `await Onside.requestLogin()`, `await Onside.logout()`, `await Onside.presentPaymentMethodsManager()`. See [Authentication](https://docs.onside.io/sdk/core-concepts/authentication.md) and [Managing Payment Methods](https://docs.onside.io/sdk/purchasing/payment-methods.md).

**Delegate options** — the native [`OnsideDelegate`](https://docs.onside.io/sdk/customization/delegate.md) is configured with plain values:

```ts
await Onside.setDelegate({
  loginMethod: 'local',                       // 'auto' (default) | 'local'
  defaultCountryCodeAssumption: 'DE',         // pre-login region hint
  windowLevelOverride: null,                  // UIWindow.Level raw value for all SDK screens
  shouldOverrideHostSupportedInterfaceOrientations: true, // default
});
```

**Payment queue delegate** — approve or veto purchases; handlers may be async. A missing handler, or one that throws, counts as `true`:

```ts
await queue.setDelegate({
  shouldContinue: async (transaction, storefront) => storefront.countryCode !== 'XX',
  shouldContinueAfterLogin: async (transaction) => true,
});
```

See [Handling Storefront & Price Changes](https://docs.onside.io/sdk/purchasing/storefront-price-changes.md).

**External login** — return your app's account token, or `null` to fall back to the regular login. See [External Login](https://docs.onside.io/sdk/core-concepts/external-login.md):

```ts
await Onside.setExternalLoginDelegate({
  externalAccountToken: async () => (await getSession())?.userId ?? null,
});
```

**Appearance** — `await Onside.appearance().setThemeMode('dark')` (`'auto' | 'light' | 'dark'`, or `null` to reset). See [Appearance & Theming](https://docs.onside.io/sdk/customization/appearance.md).

**Attribution & events** — `await Onside.getAttributionMetadata()` resolves to `{ referer: string | null }`; `await Onside.track(event, parameters)` sends an analytics event. `OnsidePredefinedEvent` and `OnsidePredefinedEventParameter` hold the predefined names. See [Attribution](https://docs.onside.io/sdk/attribution-and-analytics/attribution.md) and [Event tracking](https://docs.onside.io/sdk/attribution-and-analytics/building-funnels-with-event-tracking.md).

**Signed in-app purchase history** — `await Onside.makeSignedInAppsHistoryRequest()` resolves to a request object with the same `start()` / `didReceive` / `didFail` / `didFinish` shape as the products request; `didReceive` delivers `{ dataBase64, string }`. See [Signed In-App Purchase History](https://docs.onside.io/sdk/purchase-validation/signed-in-apps-history.md).

**Installation id & source** — publishers that emit the current value and every change:

```ts
const subscription = Onside.installationId.subscribe((id) => console.log('installationId', id));
// later:
subscription.remove();
```

`Onside.installationSource` emits `'appStore' | 'onside' | 'unknown'` (or `null`). See [Debugging & installationId](https://docs.onside.io/sdk/advanced-and-tooling/debugging.md).

**Local testing** — pass `storeKitConfigurationName` to `initialize`, and `await Onside.resetLocalTestingState()` to clear local purchase history. See [Local Testing](https://docs.onside.io/sdk/advanced-and-tooling/local-testing.md).

## Errors

Native errors reach JavaScript as string codes that match the native enum cases (`.loginDiscarded` → `'loginDiscarded'`). A code the package version doesn't know maps to `'unknown'`.

* **Rejected promises** — `add`, `restoreCompletedTransactions`, `requestLogin`, `presentPaymentMethodsManager`, `getAttributionMetadata` and `makeSignedInAppsHistoryRequest` reject with an error whose `code` property holds the code.
* **Request events** — `didFail` on products and signed-history requests, and the queue's `restoreCompletedTransactionsFailed`, receive the code as their argument.
* **Failed transactions** — `transaction.error` holds the code.

| Where                                | Type                                   | Codes                                                                                                                                  |
| ------------------------------------ | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `requestLogin`                       | `OnsideLoginErrorCode`                 | `loginDiscarded`                                                                                                                       |
| `queue.add`                          | `OnsideAddPaymentErrorCode`            | `loginDiscarded`, `rejectedAfterLogin`, `notSupportedForExternalLogin`, `applePayRequired`, `internalError`                            |
| `queue.restoreCompletedTransactions` | `OnsideRestoreRequestErrorCode`        | `loginDiscarded`, `internalError`                                                                                                      |
| `restoreCompletedTransactionsFailed` | `OnsideTransactionsRestoreErrorCode`   | `cancelled`, `connectionError`, `appNotRegistered`, `serviceUnavailable`, `internalError`                                              |
| `transaction.error`                  | `OnsidePaymentTransactionErrorCode`    | `cancelled`, `presentationFailed`, `internalError`                                                                                     |
| `presentPaymentMethodsManager`       | `OnsidePaymentMethodsManagerErrorCode` | `loginDiscarded`, `notSupportedInLocalTesting`, `notSupportedForExternalLogin`, `presentationFailed`                                   |
| Products `didFail`                   | `OnsideProductsRequestErrorCode`       | `cancelled`, `connectionError`, `appNotRegistered`, `invalidProductIdentifier`, `serviceUnavailable`, `internalError`                  |
| `getAttributionMetadata`             | `OnsideAttributionMetadataErrorCode`   | `connectionError`, `appNotRegistered`, `serviceUnavailable`, `internalError`                                                           |
| Signed history                       | `OnsideSignedInAppsHistoryErrorCode`   | `notLoggedIn`, `notSupportedInLocalTesting`, `cancelled`, `connectionError`, `appNotRegistered`, `serviceUnavailable`, `internalError` |

Every type also includes `unknown`. For what each code means, see the [Error Reference](https://docs.onside.io/sdk/reference/errors.md).

## Object lifetime

Products, responses, payments, transactions, requests and the payment queue are native-backed shared objects. A native object lives while its JS object is reachable:

* Keep the **payment queue** in a long-lived variable — when it is collected, its transaction observer and delegate are removed.
* Keep **requests** referenced until `didFinish` or `didFail`.
* Remove listeners you no longer need with `subscription.remove()` or `removeAllListeners(eventName)`.

See [Threading & Object Lifetime](https://docs.onside.io/sdk/core-concepts/threading-and-retention.md) for the native rules.

***

## API Reference

### `Onside`

<table><thead><tr><th width="430">Member</th><th>Description</th></tr></thead><tbody><tr><td><code>initialize(options?: { disableSSLPinning?: boolean; storeKitConfigurationName?: string | null }): Promise&#x3C;void></code></td><td>Initialize the SDK. Call once, before anything else.</td></tr><tr><td><code>isInitialized(): Promise&#x3C;boolean></code></td><td>Whether <code>initialize</code> has been called.</td></tr><tr><td><code>setCallbackScheme(scheme: string | null)</code> / <code>getCallbackScheme()</code></td><td>The URL scheme the Onside app returns to.</td></tr><tr><td><code>setApplePayMerchantIdentifier(id: string | null)</code> / <code>getApplePayMerchantIdentifier()</code></td><td>Apple Pay merchant ID.</td></tr><tr><td><code>handle(url: string): Promise&#x3C;boolean></code></td><td>Forward an incoming URL; <code>false</code> if it isn't an OnsideKit callback.</td></tr><tr><td><code>setDelegate(delegate: OnsideDelegate | null)</code></td><td>Login method, region hint, window level, orientation override.</td></tr><tr><td><code>setExternalLoginDelegate(delegate: OnsideExternalLoginDelegate | null)</code></td><td>Supply an external account token.</td></tr><tr><td><code>appearance().setThemeMode(mode: 'auto' | 'light' | 'dark' | null)</code></td><td>Global theme.</td></tr><tr><td><code>requestLogin(): Promise&#x3C;void></code></td><td>Present the login flow.</td></tr><tr><td><code>logout(): Promise&#x3C;void></code></td><td>End the current session.</td></tr><tr><td><code>presentPaymentMethodsManager(): Promise&#x3C;void></code></td><td>Show the saved-cards manager.</td></tr><tr><td><code>makeProductsRequest(ids: string[]): OnsideProductsRequest</code></td><td>Create a products request.</td></tr><tr><td><code>makeSignedInAppsHistoryRequest(): Promise&#x3C;OnsideSignedInAppsHistoryRequest></code></td><td>Create a signed purchase-history request.</td></tr><tr><td><code>defaultPaymentQueue(): OnsidePaymentQueue</code></td><td>The shared payment queue.</td></tr><tr><td><code>getAttributionMetadata(): Promise&#x3C;OnsideAttributionMetadata></code></td><td>Attribution metadata.</td></tr><tr><td><code>track(event: string, parameters: Record&#x3C;string, OnsideEventParameterValue>): Promise&#x3C;void></code></td><td>Send an analytics event.</td></tr><tr><td><code>installationId</code>, <code>installationSource</code></td><td>Publishers: <code>subscribe(listener)</code> returns a subscription with <code>remove()</code>.</td></tr><tr><td><code>resetLocalTestingState(): Promise&#x3C;void></code></td><td>Reset local-testing purchase history.</td></tr></tbody></table>

### `OnsidePaymentQueue`

<table><thead><tr><th width="430">Member</th><th>Description</th></tr></thead><tbody><tr><td><code>add(payment: OnsidePayment): Promise&#x3C;void></code></td><td>Start a purchase. Resolves when the payment is enqueued.</td></tr><tr><td><code>finishTransaction(transaction): Promise&#x3C;void></code></td><td>Finish a purchased, restored or failed transaction.</td></tr><tr><td><code>restoreCompletedTransactions(): Promise&#x3C;void></code></td><td>Restore non-consumables and subscriptions.</td></tr><tr><td><code>getTransactions(): Promise&#x3C;OnsidePaymentTransaction[]></code></td><td>Unfinished transactions in the queue.</td></tr><tr><td><code>getStorefront(): Promise&#x3C;OnsideStorefront | null></code></td><td>The current storefront.</td></tr><tr><td><code>setDelegate(delegate: OnsidePaymentQueueDelegate | null)</code></td><td><code>shouldContinue</code> / <code>shouldContinueAfterLogin</code> handlers.</td></tr><tr><td>Events</td><td><code>updatedTransactions</code>, <code>removedTransactions</code>, <code>restoreCompletedTransactionsFinished</code>, <code>restoreCompletedTransactionsFailed</code>, <code>didChangeStorefront</code>.</td></tr></tbody></table>

### Types

* **`OnsideProduct`** — `productIdentifier`, `localizedTitle`, `localizedDescription`, `iconUrl`, `price`, `subscriptionGroupIdentifier` (the localized group name, not a stable identifier), `subscriptionPeriod`. See [Models](https://docs.onside.io/sdk/reference/models.md).
* **`OnsidePayment`** — `new OnsidePayment(product)`; `product`, `appAccountToken`.
* **`OnsidePaymentTransaction`** — `id`, `transactionIdentifier`, `originalTransactionIdentifier`, `payment`, `transactionState` (`'purchasing' | 'purchased' | 'restored' | 'failed' | 'unknown'`), `storefront`, `error`, `isSame(other)`.
* **`OnsideStorefront`** — `id`, `countryCode`.
* **`OnsidePrice`** — `value`, `currencyCode`; **`OnsidePeriod`** — `unit` (`'day' | 'week' | 'month' | 'year' | 'unknown'`), `numberOfUnits`.

All types are exported from the package with full TypeScript definitions.

## Common issues

* **`Cannot find native module 'OnsideKit'`** — you are running in Expo Go, or the native project wasn't rebuilt after installing the package. Run `npx expo prebuild` (or `pod install`) and rebuild the app.
* **Prebuild fails with `` `callbackScheme` must be configured ``** — add the `callbackScheme` option to the config plugin.
* **The app crashes at launch with "UIScene life cycle is required"** — apps built with the iOS 27 SDK must use the scene-based life cycle. Use Expo SDK 58 or later, whose app template already adopts it.
* **Login or payment never returns to the app** — the scheme in `setCallbackScheme` doesn't match the one in `Info.plist`, or incoming URLs aren't forwarded to `Onside.handle(url)`.
* **Transactions from a previous session never arrive** — the `updatedTransactions` listener was added too late, or the queue object was garbage-collected. Register it at startup and keep a reference.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.onside.io/sdk/integrations/react-native.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
