Skip to content

About

No description, website, or topics provided.

Resources

Security policy

Stars

2 stars

Watchers

20 watching

Forks

Repository files navigation

@rokt/react-native-sdk

Overview

This repository contains the React Native SDK Rokt.Widget, a Sample Application RoktSampleApp, and an Expo Test Application ExpoTestApp.

The React Native SDK enables you to integrate Rokt into your React Native mobile apps to drive more value from—and for—your customers. The SDK is built to be lightweight, secure, and simple to integrate and maintain, resulting in minimal lift for your engineering team.

For detailed information about each component, please refer to:

Integration Guide

Installation

npm install @rokt/react-native-sdk --save

Android Configuration

The Rokt SDK is available from Maven Central and will be resolved automatically via React Native autolinking. No manual repository or package configuration is required.

iOS Configuration

Bare React Native

The Rokt iOS SDK comes from Swift Package Manager. React Native and this package still install with CocoaPods, and pod install links the Rokt iOS SDK into your app target as a Swift package. No Podfile change is needed:

cd ios && pod install

Swift Package Manager

CocoaPods stops accepting new versions of pods on 2 December 2026 (announcement), and the Rokt iOS SDK is published as a Swift package. Swift Package Manager mode is iOS only; Android is unchanged.

Podfile settings. All are optional. Set them at the top of the Podfile, before the first target block:

$RNRoktSPMVersion = '5.5.5'                    # exact Rokt iOS SDK version; defaults to the version this release was tested with
$RNRoktSPMPackages = ['RoktPaymentExtension']  # optional Rokt packages, at the same version

What pod install changes. It adds the rokt-sdk-ios Swift package, product Rokt-Widget, to each iOS app, App Clip and app extension target that uses this package, pinned to an exact version, plus any packages in $RNRoktSPMPackages. It unlinks the optional Rokt packages the Podfile does not list, including one added by hand, prints each change, and changes nothing when run again. Commit the .xcodeproj change and the Package.resolved file Xcode creates.

Linkage. Static libraries (the React Native default), use_frameworks! :linkage => :static and use_frameworks! :linkage => :dynamic all work. This package's own pod is always built as a static framework, so it never links a second copy of the SDK.

One copy only. Take every Rokt SDK from Swift Package Manager or every one from CocoaPods, never both. An app that has both builds without a warning and misbehaves at runtime, so pod install stops if a pod would add a second copy, and Debug builds show an error on launch if one is loaded.

Troubleshooting
  • [Rokt] This package takes the Rokt iOS SDK from Swift Package Manager, but these pods would add a second copy: remove those pods from the Podfile, and their names from any pre_install dynamic-framework hook. Put RoktPaymentExtension in $RNRoktSPMPackages instead. If another pod depends on them, remove it too, or use CocoaPods (below).
  • [Rokt] $RNRoktSPMPackages: unknown package: use a name from the list in the error.
  • [Rokt] ... already links Rokt-Widget from ...: the app target links the SDK from another package. Remove it from the target in Xcode, then run pod install again.
  • [Rokt] Swift Package Manager mode is on, but the Rokt-Widget Swift package is not linked into the app target (a build error): run pod install again, and keep the package in the app target.
  • [Rokt] The Rokt SDK is loaded more than once (Debug builds): the app links the SDK from both CocoaPods and Swift Package Manager. Remove one of them.
  • These checks run from hooks on CocoaPods' own install steps, tested with CocoaPods 1.16.2. If a later CocoaPods version breaks them, use CocoaPods mode and report it in this repository's issues.

CocoaPods (deprecated)

To keep taking the Rokt iOS SDK from CocoaPods, set this at the top of the Podfile, remove the rokt-sdk-ios package from your app target if it is there, and add the pre_install block before the target block. The Rokt iOS SDK (5.x) ships as source-based Swift pods that need dynamic framework linking:

$RNRoktDisableSPM = true

pre_install do |installer|
  installer.pod_targets.each do |pod|
    if ['Rokt-Widget', 'RoktContracts', 'RoktUXHelper', 'DcuiSchema'].include?(pod.name)
      def pod.build_type;
        Pod::BuildType.new(:linkage => :dynamic, :packaging => :framework)
      end
    end
  end
end

New versions of the Rokt iOS SDK may not be published to CocoaPods after 2 December 2026.

Experimental: React Native Swift Package Manager mode

React Native 0.87 can build an app with Swift Package Manager instead of CocoaPods (npx react-native spm add). This package's support for that mode is experimental and not for production use; it was tested with React Native 0.87.1. In that mode this package is the Swift package RoktReactNativeSdk, which brings the Rokt iOS SDK (rokt-sdk-ios) with it. RoktPaymentExtension is not included: if you use it, add https://github.com/ROKT/rokt-payment-extension-ios to the app target yourself, at the same version as the rokt-sdk-ios package resolves to. The Podfile settings above do not apply in this mode.

Expo

This package cannot be used with "Expo Go" because it requires custom native code. Use a custom development client instead.

  1. Install the required packages:

    npm install @rokt/react-native-sdk expo-dev-client
  2. Add the config plugin to your app.json or app.config.js:

    {
      "expo": {
        "plugins": ["@rokt/react-native-sdk"]
      }
    }

    The config plugin writes the Rokt settings into the generated iOS Podfile. pod install, which expo prebuild runs, then links the Rokt iOS SDK into the app as a Swift package (Swift Package Manager).

    Plugin options, all optional:

    {
      "expo": {
        "plugins": [
          [
            "@rokt/react-native-sdk",
            {
              "iosSdkVersion": "5.5.5",
              "iosSpmPackages": ["RoktPaymentExtension"]
            }
          ]
        ]
      }
    }
    • iosSdkVersion: the exact Rokt iOS SDK version. Defaults to the version this package's release was tested with, which can change when you upgrade the package.
    • iosSpmPackages: optional Rokt packages, such as RoktPaymentExtension.
    • iosDependencyManager: "spm" (the default), or "cocoapods" to take the SDK from CocoaPods instead, which is deprecated. iosSdkVersion and iosSpmPackages apply only to "spm".

    Run npx expo prebuild --clean after changing an option.

  3. Generate the native projects and build:

    npx expo prebuild --clean
    npx expo run:ios   # or npx expo run:android

Usage

Import

import { Rokt, RoktEmbeddedView } from "@rokt/react-native-sdk";

Initialize

Rokt.initialize("YOUR_ROKT_TAG_ID", "1.0");

Select Placements (Overlay)

const attributes = {
  email: "j.smith@example.com",
  firstname: "Jenny",
  lastname: "Smith",
  mobile: "(323) 867-5309",
  postcode: "90210",
  country: "US",
};

Rokt.selectPlacements("RoktExperience", attributes);

Select Placements (Embedded)

// Mount the named placeholder in your screen:
<RoktEmbeddedView placeholderName="RoktEmbedded1" />;

// Select by name, including from the effect that renders the view:
Rokt.selectPlacements("RoktEmbeddedExperience", attributes, ["RoktEmbedded1"]);

Named placeholders wait up to two seconds for their native views to mount. After that deadline, selection proceeds with available views and logs unresolved names. A newer selection with the same identifier replaces a pending selection. Omit placeholders, or pass [], for overlay-only requests.

Placeholders are names only. The earlier { name: findNodeHandle(ref.current) } map is no longer accepted: TypeScript reports it, and at runtime the SDK logs an error and selects the placement without embedded views (MIGRATING). For stacked screens, the newest attached view with a matching name is selected. Use distinct names across simultaneously mounted independent React Native hosts.

Placement attributes accept strings, numbers, and booleans. Numbers and booleans are converted to strings consistently on both platforms; null and unsupported values are omitted. Font and cache attribute maps still require strings.

Select Placements with Config

import { RoktConfigBuilder, CacheConfig } from "@rokt/react-native-sdk";

const config = new RoktConfigBuilder()
  .withColorMode("dark")
  .withCacheConfig(new CacheConfig(5400)) // 90 minutes
  .build();

Rokt.selectPlacements("RoktExperience", attributes, placeholders, config);

Shoppable Ads

Shoppable Ads enables partners to present contextual upsell offers to customers after a purchase. Shoppable Ads use a full-screen overlay — no embedded placeholders are needed.

Rokt.selectShoppableAds("ConfirmationPage", {
  email: "j.smith@example.com",
  confirmationref: "ORD-123",
  amount: "52.25",
  currency: "USD",
});

Note: Shoppable Ads is currently supported on iOS only. On Android, selectShoppableAds is a no-op.

Payment Extension (iOS)

Shoppable Ads requires a payment extension registered in your native iOS AppDelegate. This is done in native Swift — it cannot be called from JavaScript. The extension (RoktPaymentExtension) is Stripe-backed and presents Apple Pay, card, and Afterpay/Clearpay:

// AppDelegate.swift
import Rokt_Widget
import RoktPaymentExtension

// After SDK initialization:
if let paymentExt = RoktPaymentExtension(
    applePayMerchantId: "merchant.com.yourapp"
) {
    Rokt.registerPaymentExtension(paymentExt, config: [
        "stripeKey": "YOUR_STRIPE_PUBLISHABLE_KEY"
    ])
}

Add RoktPaymentExtension to $RNRoktSPMPackages in your Podfile (Swift Package Manager), or to the iosSpmPackages option of the Expo config plugin. With CocoaPods, add the RoktPaymentExtension pod. If it is not yet available in your SDK version, contact your Rokt account team.

Purchase Finalized (Shoppable Ads only)

purchaseFinalized is not a generic order-confirmation or checkout hook. It exists solely to close the loop on a Rokt in-placement instant purchase — an item the user buys directly inside a Shoppable Ads placement.

Call it only in response to a CartItemInstantPurchase event, after you have processed that item's payment. Pass the placementId and catalogItemId from the event (the placementId is the Rokt placement/layout id, not your order id), and true/false for whether your payment processing succeeded:

eventEmitter.addListener("RoktEvents", (event) => {
  if (event.event === "CartItemInstantPurchase") {
    // ...process payment for event.catalogItemId...
    const success = true; // or false if your payment step failed
    Rokt.purchaseFinalized(event.placementId, event.catalogItemId, success);
  }
});

Do not call purchaseFinalized on your own order-confirmation page after a normal checkout. The native SDK no-ops unless a Rokt instant purchase is currently open.

Event Handling

Listen for SDK events via NativeEventEmitter:

import { NativeEventEmitter } from "react-native";
import { RoktEventManager } from "@rokt/react-native-sdk";

const eventEmitter = new NativeEventEmitter(RoktEventManager ?? undefined);

const subscription = eventEmitter.addListener("RoktEvents", (event) => {
  switch (event.event) {
    case "InitComplete":
      console.log("SDK initialized:", event.status);
      break;
    case "PlacementReady":
      console.log("Placement ready:", event.placementId);
      break;
    case "PlacementClosed":
      console.log("Placement closed");
      break;
    case "CartItemInstantPurchase":
      console.log("Purchase:", event.catalogItemId, event.totalPrice);
      break;
  }
});

// Clean up
subscription.remove();

Environment Configuration

Rokt.setEnvironmentToStage(); // For testing
Rokt.setEnvironmentToProd(); // For production (default)

Custom Base URL (CNAME)

Route all Rokt SDK requests through your own first-party domain. Must be called before Rokt.initialize(...). Supported on iOS and Android.

Rokt.setCustomBaseURL("https://rokt.example.com");
Rokt.initialize("YOUR_ROKT_TAG_ID", "1.0");

Only the scheme, host, and port of the URL are used. Non-HTTPS URLs and URLs with a missing/empty host are rejected with a warning.

Built-in PayPal redirect callback

Built-in PayPal device-pay authenticates in a web view and returns to the host app via a custom URL scheme. This is iOS only — on Android the SDK self-registers its own redirect activity (scoped to your app's package name) via manifest merging, so none of the steps below are needed there.

  1. Register a URL scheme in your iOS app.

    • Bare React Native: add an entry under CFBundleURLTypes in ios/<App>/Info.plist.
    • Expo: set expo.scheme in app.json (e.g. "scheme": "myapp") and run expo prebuild.
  2. Tell the SDK the scheme:

    Rokt.setPaymentCallbackURLScheme("myapp");
  3. Forward incoming deep links to the SDK using React Native's Linking:

    import { useEffect } from "react";
    import { Linking, Platform } from "react-native";
    
    useEffect(() => {
      if (Platform.OS !== "ios") return;
      // Cold start: the app was launched by the callback URL itself.
      Linking.getInitialURL().then((url) => {
        if (url) Rokt.handleURLCallback(url);
      });
      // Warm return: the app was already running.
      const sub = Linking.addEventListener("url", ({ url }) => {
        Rokt.handleURLCallback(url);
      });
      return () => sub.remove();
    }, []);

API Reference

Method Description
Rokt.initialize(tagId, appVersion, fontFilesMap?) Initialize the SDK
Rokt.selectPlacements(identifier, attributes, placeholders?, config?) Display overlay or embedded placements
Rokt.selectShoppableAds(identifier, attributes, config?) Display shoppable ads (iOS only)
Rokt.purchaseFinalized(placementId, catalogItemId, success) Close the loop on a Rokt in-placement instant purchase (Shoppable Ads) — call from the CartItemInstantPurchase event handler, not on normal checkout
Rokt.setEnvironmentToStage() Set staging environment
Rokt.setEnvironmentToProd() Set production environment
Rokt.setSessionId(sessionId) Set a custom session ID
Rokt.getSessionId() Get the current session ID
Rokt.setCustomBaseURL(url) Route SDK requests through a CNAME
Rokt.setPaymentCallbackURLScheme(scheme) Register URL scheme for built-in PayPal redirects
Rokt.handleURLCallback(url) Forward deep-link URL to the SDK

Minimum Requirements

Platform Version
iOS 15.0
Android API 21
React Native 0.71.0+

Development

Local Development

  1. Make code changes in Rokt.Widget/
  2. Build the package: cd Rokt.Widget && npm run build
  3. Test using the sample apps:
    • cd RoktSampleApp && npm install && npm run ios
    • cd RoktSampleApp && npm install && npm run android

Publishing

The SDK is published to NPM automatically via GitHub Actions when the VERSION file is updated on main or on a maintenance/<major>.x branch. See RELEASING.md.

License

Copyright 2020 Rokt Pte Ltd

Licensed under the Rokt Software Development Kit (SDK) Terms of Use Version 2.0 (the "License"); You may not use this file except in compliance with the License. You may obtain a copy of the License at https://rokt.com/sdk-license-2-0/

About

No description, website, or topics provided.

Resources

Security policy

Stars

2 stars

Watchers

20 watching

Forks

Releases

Packages

Used by

Contributors

Languages