Skip to main content

React Native SDK+ Integration Guide

This page explains how to implement the Rokt Ecommerce React Native SDK+. The SDK+ passes user and transaction data to Rokt on configured screens so Rokt can render relevant experiences, such as offers on confirmation screens.

tip

Work with your Rokt account manager to first implement the SDK+ in a development environment so you can thoroughly test before going live.

1. Add the Rokt SDK+ to Your React Native AppDirect link to 1. Add the Rokt SDK+ to Your React Native App

Add the React Native SDK+ as a dependency to your application:

npm install react-native-mparticle --save

Import the package into your React Native app code and get an instance of mParticle:

import MParticle from 'react-native-mparticle';

After installing the React Native plugin, continue integrating the Rokt SDK+ into your mobile app by following the platform-specific setup steps below. Be sure to include the key and secret provided by your Rokt account manager where required.

1.1. Add the Rokt SDK to your iOS appDirect link to 1.1. Add the Rokt SDK to your iOS app

The NPM install step above will automatically include the React framework and the core iOS framework in your project. The Rokt Kit needs to be added as a pod dependency in the ios/Podfile. However depending on your app and its other dependencies you must integrate it in 1 of 2 ways:

Using CocoaPods, include the Rokt SDK in your application:

CocoaPodsDirect link to CocoaPods

To integrate the Rokt Kit using CocoaPods, specify it in your Podfile with:

ios/Podfile
pod 'mParticle-Rokt','~> 9.0'
pod 'RoktPaymentExtension', '~> 1.0'
  1. Static Libraries are the React Native default, but because the Rokt iOS SDK contains Swift code you need to add an exception for it in the form of a pre-install command in the Podfile.

    pre_install do |installer|
    installer.pod_targets.each do |pod|
    if pod.name == 'mParticle-Apple-SDK' || pod.name == 'mParticle-Rokt' || pod.name == 'Rokt-Widget'
    def pod.build_type;
    Pod::BuildType.new(:linkage => :dynamic, :packaging => :framework)
    end
    end
    end
    end

    Then run the following command

    bundle exec pod install
  2. Frameworks are the default for Swift development and while it isn’t preferred by React Native it is supported. Additionally you can define whether the frameworks are built statically or dynamically.

Update your Podfile to be ready to use dynamically linked frameworks by commenting out the following line(if flipper is there)

# :flipper_configuration => flipper_config,

Then run either of the following commands

USE_FRAMEWORKS=static bundle exec pod install

or

USE_FRAMEWORKS=dynamic bundle exec pod install

1.2. Initialize the Rokt SDKDirect link to 1.2. Initialize the Rokt SDK

To initialize the SDK, insert the following initialization snippet in your AppDelegate file. Replace your-key and your-secret with the key and secret provided by your Rokt team.

caution
  • Make sure to replace your-key and your-secret with the key and secret provided by your dedicated Rokt team.
  • Call registerPaymentExtension after MParticle.sharedInstance().start(with:) and before selectPlacements.
AppDelegate initialization
import mParticle_Apple_SDK
import RoktPaymentExtension

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development
MParticle.sharedInstance().start(with: options)

// Register after MParticle.sharedInstance().start(), before selectPlacements
if let paymentExt = RoktPaymentExtension(
applePayMerchantId: "merchant.com.yourapp.rokt"
) {
MParticle.sharedInstance().rokt.registerPaymentExtension(paymentExt)
}
return true
}

Further setupDirect link to Further setup

For further help, see the full iOS SDK Integration Guide.


2. Initialize the Rokt SDK+Direct link to 2. Initialize the Rokt SDK+

The platform-specific initialization code lives in the native files set up in §1 above. After completing that setup, import MParticle in your React Native app and initialize any JavaScript-layer configuration. The native SDK+ must be initialized before any other SDK+ API calls are made.

When inserting the initialization snippet into your app, you will see customizable fields for:

  1. Entering your Rokt key and secret.

    Set your-key and your-secret inside the native credentials call to the key and secret values provided by your Rokt account manager.

  2. Setting your data environment.

    Set environment to Development while testing to route data to the Development environment, and Production to send live customer activity to Production.

  3. Identifying your user and setting attributes.

    Pass the user's raw, un-hashed email at initialization. For hashed emails and other identifiers, see Supported User Identifiers. Once identified, set additional user attributes — see User Attributes for the recommended list.

    Set user attributes in the identity callback
    MParticle.Identity.identify(request, (error, userId) => {
    if (!error) {
    const user = new MParticle.User(userId);
    user.setUserAttribute('example attribute key', 'example attribute value');
    }
    });
    note

    Always pass an identifyRequest during initialization. If you don't have the user's email at initialization, you can identify the user later via 3. Identify the User. See Error Handling for how to handle identity errors — without error handling you may see data consistency issues at scale.

3. Identify the UserDirect link to 3. Identify the User

Call MParticle.Identity.identify with a fresh identifyRequest any time the user provides their email address after the SDK+ has initialized (for example, when they log in, create an account, or make a purchase). This ensures event data is attributed to the correct user.

Supported User IdentifiersDirect link to Supported User Identifiers

Show supported user identifiers
FieldTypeDescription
emailstringPass the customer's raw, unhashed email address.
mobilestringPass the customer's phone number in E.164 format.
customeridstringPass your internal customer/account identifier. Send on every screen for logged-in users.
otherstringPass a SHA-256-hashed email. Only use when the raw email cannot be provided — do not pass both email and other. (Android path only.)
other2stringPass a SHA-256-hashed mobile number. Only use when the raw mobile number cannot be provided — do not pass both mobile and other2. (Android path only.)
emailSha256stringPass a SHA-256-hashed email. Only use when the raw email cannot be provided — do not pass both email and emailSha256. (iOS path only.)
mobileSha256stringPass a SHA-256-hashed mobile number. Only use when the raw mobile number cannot be provided — do not pass both mobile and mobileSha256. (iOS path only.)

To identify the user:

  1. Create an IdentityRequest object to contain the user's identifiers. You should integrate the user's raw, unhashed email address into the email field.

  2. To set additional user attributes, use the identity callback. If the identifyRequest succeeds, any user attributes you set inside the callback are assigned to the identified user.

  3. After creating the identifyRequest and the callback, send them to Rokt using the MParticle.Identity.identify method.

    For example, to identify a user named Jane Smith with the email address j.smith@example.com, mobile number +13125551515, and customer ID cust_10482, you would use:

    Identify Jane Smith
    // 1. Create the identifyRequest object
    const request = new MParticle.IdentityRequest();
    // Preferred: pass the customer's raw, unhashed email.
    // If you can only provide a SHA-256-hashed email, remove .email and use other instead — do not pass both.
    request.email = 'j.smith@example.com';
    request.other = 'SHA-256 hashed email'; // only if raw email unavailable
    // If you can only provide a SHA-256-hashed mobile number, use other2 instead of mobile — do not pass both.
    // (Called 'other2' on Android and 'mobileSha256' on iOS; both use this same field.)
    request.other2 = 'SHA-256 hashed mobile number'; // only if raw mobile unavailable
    request.mobile = '+13125551515';
    request.customerId = 'cust_10482';

    // 2. User attributes are set using the identity callback
    // 3. Call the identify method, including the identifyRequest and callback
    MParticle.Identity.identify(request, (error, userId) => {
    if (error) {
    console.debug(error);
    } else {
    const user = new MParticle.User(userId);
    user.setUserAttribute('firstname', 'Jane');
    user.setUserAttribute('lastname', 'Smith');
    }
    });

4. Set User AttributesDirect link to 4. Set User Attributes

Set user attributes progressively as the user navigates your app, not just at checkout. The more attributes you set, the better Rokt can resolve the customer and deliver relevant offers.

Set user attributes
import MParticle from 'react-native-mparticle';

// Retrieve the current user. This will only succeed if you have identified the user during SDK+ initialization or by calling the identify method.
MParticle.Identity.getCurrentUser((currentUser) => {
if (currentUser) {
// Once you have the current user, you can set user attributes with:
currentUser.setUserAttribute('custom-attribute-name', 'custom-attribute-value');
// Note: all user attributes (including list attributes and tags) must have distinct names.

// Rokt recommends setting as many of the following user attributes as possible:
currentUser.setUserAttribute('firstname', 'John');
currentUser.setUserAttribute('lastname', 'Doe');
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser.setUserAttribute('mobile', '3125551515');
currentUser.setUserAttribute('age', '33');
currentUser.setUserAttribute('gender', 'M');
currentUser.setUserAttribute('billingcity', 'Brooklyn');
currentUser.setUserAttribute('billingstate', 'NY');
currentUser.setUserAttribute('billingzipcode', '123456');
currentUser.setUserAttribute('dob', 'yyyymmdd');
currentUser.setUserAttribute('title', 'Mr');
currentUser.setUserAttribute('language', 'en');
currentUser.setUserAttribute('predictedltv', '136.23');

// You can create a user attribute to contain a list of values
currentUser.setUserAttributeArray('favorite-genres', ['documentary', 'comedy', 'romance', 'drama']);

// To remove a user attribute, call removeUserAttribute and pass in the attribute name.
currentUser.removeUserAttribute('attribute-to-remove');
}
});

User AttributesDirect link to User Attributes

Set as many of the following as you can collect:

Show all user attributes
FieldTypeDescription
firstnamestringCustomer's first name. Used for personalization.
lastnamestringCustomer's last name. Used for personalization.
mobilestringPhone number formatted as 1112345678 or +1 (222) 345-6789. Used for identity resolution and relevance.
ageintegerCustomer's age. Alternate to dob. Used for eligibility and relevance.
dobstringDate of birth, yyyymmdd. Alternate to age. Used for eligibility and relevance.
genderstringCustomer's gender. For example, M, F, Male, or Female. Used for relevance.
titlestringHonorific. For example, Mr, Mrs, Ms. Used for personalization.
languagestringISO 639-1 language code associated with the purchase. Used for relevance.
billingcitystringBilling city. Used for relevance.
billingstatestringBilling state / province / region. Used for relevance and eligibility.
billingzipcodestringFull ZIP or postcode (US preference is ZIP+4). Used for identity resolution and relevance.
billingaddress1stringBilling street address line 1. Used for identity resolution and relevance.
billingaddress2stringBilling street address line 2. Used for identity resolution.
countrystringISO 3166-1 alpha-2 country code (e.g. US, GB, AU). Used for eligibility and relevance.
birthyearintegerCustomer's birth year (e.g. 1990). Used for eligibility and relevance.
newcustomerbooleanWhether this is a first-time buyer. Used for relevance.
customertypestringWhether the user is authenticated (guest / logged_in). Used for relevance.
loyaltytierstringPartner loyalty program tier. Used for relevance and eligibility.
loyaltyidstringLoyalty program member ID. Used for identity resolution.
predictedltvdecimalPredicted total lifetime value, typically from a partner ML model. Used for relevance.
subscriptionstatusstringSubscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility.
customersegmentstringPartner internal segmentation (e.g. vip, at_risk, new, reactivated). Used for relevance.
acquisitionchannelstringChannel through which the customer was acquired. Used for relevance.

All user attributes (including list attributes) must have distinct names.

5. Track Funnel EventsDirect link to 5. Track Funnel Events

Track screen views, account lifecycle events, commerce events, and custom events so Rokt can maintain identity continuity and understand where each customer is in their journey.

Screen ViewsDirect link to Screen Views

Call MParticle.logScreenEvent() with the name of the screen (e.g. "homepage", "product detail page"). Include any additional custom attributes in the info object.

Log a screen view
import MParticle from 'react-native-mparticle';

MParticle.logScreenEvent('homepage', {
'custom-attribute': 'custom-value',
});

Account Lifecycle EventsDirect link to Account Lifecycle Events

Log account lifecycle events when the user signs up, logs in, or logs out so Rokt can maintain identity continuity across sessions and devices. Signup and login events accept a method attribute describing how the user signed up or logged in.

Supported lifecycle event typesDirect link to Supported lifecycle event types

Show lifecycle event types
Lifecycle Event TypeWhen to triggerSupported method values
sign_upNew account createdemail, social, guest
loginUser logs inemail, social, sso
logoutUser logs outNot applicable.

Example lifecycle eventsDirect link to Example lifecycle events

Signup, login, logout
import MParticle from 'react-native-mparticle';

// Signup event
const signupEvent = new MParticle.Event()
.setName('sign_up')
.setType(MParticle.EventType.Other)
.setInfo({ method: 'email' });
MParticle.logMPEvent(signupEvent);

// Login event
const loginEvent = new MParticle.Event()
.setName('login')
.setType(MParticle.EventType.Other)
.setInfo({ method: 'email' });
MParticle.logMPEvent(loginEvent);

// Logout event
const logoutEvent = new MParticle.Event()
.setName('logout')
.setType(MParticle.EventType.Other);
MParticle.logMPEvent(logoutEvent);

Commerce EventsDirect link to Commerce Events

Commerce events carry product-level details for the user's journey. Trigger a separate commerce event for each product action the customer takes.

Investing in full commerce event coverage is one of the highest-leverage things you can do during your integration. Each event tells Rokt something different about where the customer is in their journey: a product view signals exploration, an add-to-cart signals consideration, a checkout start signals purchase intent, and a completed purchase confirms conversion. With a richer signal, Rokt can personalize offers more effectively, measure placement performance accurately, and attribute conversions to the right touchpoints. Doing this work during your initial integration also avoids a retrofit later. The signal compounds over time: each event Rokt receives adds context used to sharpen personalization, improve attribution accuracy, and better resolve and segment your customer base on future visits.

Commerce events are logged with MParticle.CommerceEvent.createProductActionEvent, using a product action type that identifies the customer action (viewing a product, adding to cart, starting checkout, completing a purchase, etc.). The sections below list the supported action types and walk through assembling the event.

Product action typesDirect link to Product action types

Show all product action types
Customer actionProduct action type
Product detail page viewedMParticle.ProductActionType.ViewDetail
Product clickedMParticle.ProductActionType.Click
Item added to cartMParticle.ProductActionType.AddToCart
Item removed from cartMParticle.ProductActionType.RemoveFromCart
Item added to wishlistMParticle.ProductActionType.AddToWishlist
Item removed from wishlistMParticle.ProductActionType.RemoveFromWishlist
Checkout flow initiatedMParticle.ProductActionType.Checkout
Checkout option selectedMParticle.ProductActionType.CheckoutOption
Order confirmedMParticle.ProductActionType.Purchase
Order refundedMParticle.ProductActionType.Refund

Tracking a commerce event requires three steps:

1. Define the productDirect link to 1. Define the product

Create a MParticle.Product with the product's name, SKU, price, and quantity. Set additional fields using the product object's properties.

Define a product
import MParticle from 'react-native-mparticle';

const product = new MParticle.Product('Double Room - Econ Rate', 'econ-1', 100.00, 4);

// Add optional custom attributes to the product
product.customAttributes = {
'ocean-view': 'true',
'balcony': 'false',
};

2. Summarize the transactionDirect link to 2. Summarize the transaction

Create a MParticle.TransactionAttributes object for Purchase, Checkout, and CheckoutOption events. Include shipping and coupon code when applicable — order-level coupons belong here, not on individual products.

Summarize the transaction
import MParticle from 'react-native-mparticle';

const transactionAttributes = new MParticle.TransactionAttributes('ORDER-12345')
.setRevenue(149.99)
.setTax(12.50)
.setShipping(5.99)
.setCouponCode('SUMMER20');

3. Log the commerce eventDirect link to 3. Log the commerce event

Create a CommerceEvent with a product action type from the table above, attach the transactionAttributes, and log it.

Log a Purchase commerce event
import MParticle from 'react-native-mparticle';

const commerceEvent = MParticle.CommerceEvent.createProductActionEvent(
MParticle.ProductActionType.Purchase,
[product],
transactionAttributes,
);

// Optional: add custom attributes to the commerce event
commerceEvent.customAttributes = { 'sale': 'true' };
MParticle.logCommerceEvent(commerceEvent);

The same structure applies to every product action type — swap MParticle.ProductActionType.Purchase for the action that matches the customer behavior you're logging. See the Product action types table for the full list.

Custom EventsDirect link to Custom Events

Track custom events using MParticle.Event, passing an event name, event type, and optional custom attributes.

Supported custom event typesDirect link to Supported custom event types

Show custom event types
TypeUse for
MParticle.EventType.NavigationUser navigation flows and screen transitions within your app.
MParticle.EventType.LocationLocation-based interactions and movements.
MParticle.EventType.SearchSearch queries and search-related actions.
MParticle.EventType.TransactionFinancial transactions and purchase-related activity.
MParticle.EventType.UserContentUser-generated content like reviews, comments, or posts.
MParticle.EventType.UserPreferenceUser settings, preferences, and customization choices.
MParticle.EventType.SocialSocial media interactions and sharing activities.
MParticle.EventType.OtherAnything that doesn't fit the categories above.

Example custom eventDirect link to Example custom event

Log a custom event
import MParticle from 'react-native-mparticle';

const event = new MParticle.Event()
.setName('Video Watched')
.setType(MParticle.EventType.Navigation)
.setInfo({ category: 'Destination Intro', title: 'Paris' });
MParticle.logMPEvent(event);

6. Show a PlacementDirect link to 6. Show a Placement

Call selectPlacements on every payment and confirmation screen you want Rokt to render content on. Include one of the following page identifiers to specify the screen type and whether it's for testing or production:

  • stg.rokt.conf: A confirmation screen in a staging (or testing) environment.
  • prod.rokt.conf: A confirmation screen in a production environment.
  • stg.rokt.payments: A payments screen in a staging (or testing) environment.
  • prod.rokt.payments: A payments screen in a production environment.

Placement AttributesDirect link to Placement Attributes

Pass these attributes in the attributes map of selectPlacements. Always supply the most recent value — attributes passed here override any earlier setUserAttribute calls.

Show all placement attributes
FieldTypeDescription
emailstringCustomer email (unhashed). Used for identity resolution.
firstnamestringCustomer first name. Used for personalization.
lastnamestringCustomer last name. Used for personalization.
mobilestringCustomer mobile number in E.164 format. Used for identity resolution.
confirmationrefstringOrder / confirmation reference number. Used for relevance and deduplication.
currencystringTransaction currency (ISO 4217, e.g. USD, GBP, AUD). Used for relevance.
countrystringISO 3166-1 alpha-2 country code. Used for eligibility and relevance.
languagestringCustomer's preferred language (ISO 639-1). Used for relevance.
totalpricedecimalTotal cart value including tax and shipping. Used for relevance.
amountstringCart subtotal before tax and shipping. Distinct from totalprice. Used for relevance.
couponCodestringPromo code applied to the order, if any. Used for relevance.
newcustomerbooleanWhether this is a first-time buyer. Used for relevance.
customertypestringguest or logged_in. Used for relevance.
valuedecimalCustomer's cumulative purchase value (e.g. "2340.00"). Used for relevance.
subscriptionstatusstringSubscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility.
customersegmentstringPartner internal segmentation (e.g. vip, at_risk, new, reactivated). Used for relevance.
paymenttypestringPayment method selected (credit_card, paypal, apple_pay, etc.). Used for Pay+ eligibility.
paymentServiceProviderstringPayment services offered on the page (apple_pay, paypal, card). Used for Pay+ eligibility.
ccbinstringCredit card BIN (first 6 digits). Used for relevance.
billingnamestringBilling name. Used for identity resolution.
billingaddress1stringBilling street address. Used for identity resolution and relevance.
billingaddress2stringBilling apartment / unit. Used for identity resolution.
billingcitystringBilling city. Used for relevance.
billingstatestringBilling state or province. Used for relevance.
billingzipcodestringBilling ZIP / postcode. Used for identity resolution and relevance.
shippingmethodstringShipping method selected (standard, express, next_day). Used for relevance.
shippingnamestringShipping name. Used for relevance.
shippingaddress1stringShipping street address. Used for relevance.
shippingcitystringShipping city. Used for relevance.
shippingstatestringShipping state or province. Used for relevance.
shippingzipcodestringShipping ZIP or postcode. Used for relevance.
shippingcountrystringShipping country (ISO 3166-1 alpha-2). Used for relevance.
cartItemsstringJSON-serialized array of cart items. Used for relevance.
adsExperiencestringPass "shoppable" when deliberately targeting a Shoppable Ads experience. Used for iOS only.

Overlay PlacementsDirect link to Overlay Placements

Overlay placements render on top of your confirmation screen in a Rokt-managed container, requiring no changes to your app's existing layout.

To insert an overlay placement, call selectPlacements once the confirmation screen loads:

Overlay placement
import MParticle from 'react-native-mparticle';

const attributes = {
// Identity
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'mobile': '+13125551515',

// Transaction
'confirmationref': '54321',
'currency': 'USD',
'country': 'US',
'language': 'en',
'totalprice': '149.99',
'couponCode': 'SUMMER20',

// Customer context
'newcustomer': 'false',
'customertype': 'logged_in',
'value': '2340.00',
'subscriptionstatus': 'active',
'customersegment': 'vip',

// Payment (include paymenttype and paymentServiceProvider for Pay+)
'paymenttype': 'credit_card',
'paymentServiceProvider': 'card',
'ccbin': '411112',

// Billing address
'billingaddress1': '123 Main St',
'billingcity': 'Brooklyn',
'billingstate': 'NY',
'billingzipcode': '11201',

// Shipping
'shippingmethod': 'express',
'shippingaddress1': '175 Varick St',
'shippingcity': 'New York',
'shippingstate': 'NY',
'shippingzipcode': '10014',
'shippingcountry': 'US',
};

const roktConfig = MParticle.Rokt.createRoktConfig('light');

MParticle.Rokt.selectPlacements(
'RoktExperience', // identifier
attributes, // attributes map
{}, // placeholders (empty for overlay)
roktConfig, // configuration
);

Embedded PlacementsDirect link to Embedded Placements

Embedded placements render inline at a fixed position in your app that you control (for example, above the payment options on a cart screen). Both Thanks and Pay+ use embedded placements, but Pay+ must use embedded placements.

Add a RoktLayoutView to your screen at the position where you want the placement to render:

Embedded placement
import React, { ComponentRef } from 'react';
import { findNodeHandle } from 'react-native';
import MParticle, { RoktLayoutView } from 'react-native-mparticle';

const placeholder1 = React.createRef<ComponentRef<typeof RoktLayoutView>>();

const showRoktLayout = () => {
const placeholders = {
RoktEmbedded1: findNodeHandle(placeholder1.current),
};

const attributes = {
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'billingzipcode': '90210',
'confirmationref': '54321',
};

MParticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
placeholders,
);
};

// Integrate the RoktLayoutView in the view hierarchy
<RoktLayoutView ref={placeholder1} placeholderName="RoktEmbedded1" />
Pay+

For Pay+ placements, include paymenttype and paymentServiceProvider in the selectPlacements call on each screen. paymentServiceProvider communicates what payment methods are available on the payment screen; paymenttype communicates what method the user paid with.

Interstitial PlacementsDirect link to Interstitial Placements

Interstitial placements are rendered between the payment and confirmation screens, allowing customers to purchase additional products. Interstitial placements are used by Shoppable Ads.

note

Interstitial placements are supported on iOS only in the React Native SDK+. The Android path of this SDK+ does not support interstitial placements. The code below must only be invoked on the iOS path of your app.

To enable interstitial placements on iOS, first ensure the iOS-specific setup is complete:

  1. Follow the iOS SDK+ Integration Guide to configure Apple Pay and register RoktPaymentExtension in your AppDelegate.
  2. In your React Native AppDelegate (Swift or Objective-C), register the payment extension after MParticle.sharedInstance().start().

Then call selectPlacements from your React Native JavaScript layer with the confirmation-screen identifier. On iOS, the Rokt SDK+ will render the interstitial experience when an eligible offer is available.

Interstitial placement (iOS only)
import { Platform } from 'react-native';
import MParticle from 'react-native-mparticle';

// Interstitial placements are iOS only — do not invoke on Android
if (Platform.OS === 'ios') {
const attributes = {
// Identity
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'mobile': '+13125551515',

// Transaction
'confirmationref': '54321',
'currency': 'USD',
'country': 'US',
'language': 'en',
'totalprice': '149.99',
'amount': '137.50',

// Customer context
'newcustomer': 'false',
'customertype': 'logged_in',
'value': '2340.00',

// Payment
'paymenttype': 'credit_card',
'paymentServiceProvider': 'card',
'ccbin': '411112',

// Billing address
'billingaddress1': '123 Main St',
'billingcity': 'Brooklyn',
'billingstate': 'NY',
'billingzipcode': '11201',

// Shipping (required for Shoppable Ads order fulfillment)
'shippingaddress1': '175 Varick St',
'shippingcity': 'New York',
'shippingstate': 'NY',
'shippingzipcode': '10014',
'shippingcountry': 'US',
};

MParticle.Rokt.selectPlacements(
'prod.rokt.conf', // use 'stg.rokt.conf' in test environments
attributes,
{}, // no embedded placeholders for interstitial
);
}

Subscribe to the CartItemInstantPurchase and related Shoppable Ads events via the Events API to handle purchase flows initiated from the interstitial experience.

Optional FunctionsDirect link to Optional Functions

FunctionPurpose
MParticle.Rokt.close()Auto-close overlay placements.

Additional ConfigurationDirect link to Additional Configuration

Pass optional parameters such as RoktConfig to customize the placement UI (e.g. dark/light mode, caching).

selectPlacements with RoktConfig
import MParticle from 'react-native-mparticle';

const roktConfig = MParticle.Rokt.createRoktConfig(
'light',
MParticle.Rokt.createCacheConfig(1200, { 'email': 'j.smith@example.com', 'orderNumber': '123' }),
);

MParticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
{},
roktConfig,
);
note

If you want to update the identifier RoktExperience or embedded identifier RoktEmbedded1 with a different value, contact your Rokt account manager to ensure Rokt placements are configured consistently.

Events APIDirect link to Events API

The SDK+ provides placement lifecycle events through the NativeEventEmitter mechanism.

Subscribe to placement events
import { NativeEventEmitter } from 'react-native';
import MParticle from 'react-native-mparticle';

const eventManagerEmitter = new NativeEventEmitter(MParticle.RoktEventManager);

eventManagerEmitter.addListener('RoktEvents', data => {
console.log(`event received ${JSON.stringify(data)}`);
});

Standard eventsDirect link to Standard events

Show all standard events
EventDescriptionParams
ShowLoadingIndicatorTriggered before the SDK+ calls the Rokt backend.
HideLoadingIndicatorTriggered when the SDK+ receives a success or failure from the Rokt backend.
PlacementInteractiveTriggered when a placement has been rendered and is interactable.placementId: String
PlacementReadyTriggered when a placement is ready to display but has not rendered content yet.placementId: String
OfferEngagementTriggered when the user engages with the offer.placementId: String
PositiveEngagementTriggered when the user positively engages with the offer.placementId: String
FirstPositiveEngagementTriggered when the user positively engages with the offer for the first time.placementId: String
OpenUrlTriggered when the user presses a URL that is configured to be sent to the partner app.placementId: String, url: String
PlacementClosedTriggered when a placement is closed by the user.placementId: String
PlacementCompletedTriggered when the offer progression reaches the end and no more offers are available to display. Also triggered when cache is hit but the retrieved placement will not be displayed as it has previously been dismissed.placementId: String
PlacementFailureTriggered when a placement could not be displayed due to some failure or when no placements are available to show.placementId: String (optional)
CartItemInstantPurchaseTriggered when the catalog item purchase is initiated by the user (iOS only).placementId: String, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String, totalPrice: number, quantity: number, unitPrice: number

7. AppendixDirect link to 7. Appendix

Appendix A: App ConfigurationDirect link to Appendix A: App Configuration

Applications can pass configuration settings through RoktConfig so the SDK+ uses your app's custom configuration instead of system defaults.

ColorMode objectDirect link to ColorMode object

ValueDescription
lightApplication is in Light Mode
darkApplication is in Dark Mode
systemApplication defaults to System Color Mode

EdgeToEdgeDisplay (Android only)Direct link to EdgeToEdgeDisplay (Android only)

This boolean controls whether the Rokt SDK+ renders in edge-to-edge display mode on Android (default true). Set to false if your app does not support edge-to-edge display.

EdgeToEdgeDisplay
import com.mparticle.rokt.RoktConfig

val roktConfig = RoktConfig.Builder()
.edgeToEdgeDisplay(true)
.build()

CacheConfig objectDirect link to CacheConfig object

ParameterDescription
cacheDurationOptional duration in seconds for which the Rokt SDK+ should cache the experience. Maximum allowed value is 90 minutes; default is 90 minutes if not provided or invalid.
cacheAttributesOptional attributes to be used as cache key. If null, all attributes sent in selectPlacements will be used as the cache key.
RoktConfig with ColorMode and CacheConfig
import MParticle from 'react-native-mparticle';

// Cache the experience for 1200 seconds, using email and orderNumber as the cache key.
const roktConfig = MParticle.Rokt.createRoktConfig(
'light',
MParticle.Rokt.createCacheConfig(
1200,
{ 'email': 'j.smith@example.com', 'orderNumber': '123' }
),
);

MParticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
{},
roktConfig,
);

Appendix B: RoktLayoutView ComponentDirect link to Appendix B: RoktLayoutView Component

For embedded placements, the React Native SDK+ provides the RoktLayoutView component for a declarative approach to integrating Rokt placements in your app's view hierarchy. RoktLayoutView supports embedded placement types without the need to manually manage node handles.

Embedded placement with RoktLayoutView
import React, { ComponentRef } from 'react';
import { findNodeHandle, View } from 'react-native';
import MParticle, { RoktLayoutView } from 'react-native-mparticle';

const MyConfirmationScreen = () => {
const placeholder1 = React.createRef<ComponentRef<typeof RoktLayoutView>>();

const handleSelectPlacements = () => {
const placeholders = {
RoktEmbedded1: findNodeHandle(placeholder1.current),
};

const attributes = {
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'billingzipcode': '90210',
'confirmationref': '54321',
};

MParticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
placeholders,
);
};

return (
<View>
{/* Your confirmation screen content */}
<RoktLayoutView ref={placeholder1} placeholderName="RoktEmbedded1" />
</View>
);
};

ParametersDirect link to Parameters

ParameterTypeDescription
refRefReact ref used to get the native node handle for the placeholder map.
placeholderNamestringThe embedded view identifier (e.g. "RoktEmbedded1"), must match the key in the placeholders map passed to selectPlacements.

Appendix C: Error HandlingDirect link to Appendix C: Error Handling

The IDSync API is intended to be central to your app's state and is designed to be fast and highly-available. Similar to how your app may prevent users from logging in, logging out, or modifying their state without an internet connection — treat these APIs as gating operations to maintain a consistent user state. The SDK+ will not retry API calls automatically, but provides callback APIs so you can do so according to your business logic.

If you do not implement error handling, you may see data consistency issues at scale.

IDSync error handling
import MParticle from 'react-native-mparticle';

const request = new MParticle.IdentityRequest();
request.email = 'j.smith@example.com';

MParticle.Identity.identify(request, (error, userId) => {
if (error) {
// Inspect error.code to determine the cause:
// - Network errors: retry the request
// - Throttle errors (429): retry with backoff
console.debug('Identity error:', error);
} else {
// Proceed with the identified user
const user = new MParticle.User(userId);
user.setUserAttribute('first_name', 'Jane');
}
});

iOS error codesDirect link to iOS error codes

On iOS, the native MPIdentityErrorResponseCode enum defines the following client-side codes. Inspect error.code in the native onIdentifyComplete callback to determine the cause:

MPIdentityErrorResponseCodeDescription
MPIdentityErrorResponseCodeRequestInProgressAn IDSync HTTP request was not performed because one is already in progress.
MPIdentityErrorResponseCodeClientSideTimeoutThe IDSync HTTP request failed due to a TCP connection timeout.
MPIdentityErrorResponseCodeClientNoConnectionThe IDSync HTTP request failed due to lack of network coverage.
MPIdentityErrorResponseCodeSSLErrorThe IDSync HTTP request failed due to an SSL configuration issue.
MPIdentityErrorResponseCodeOptOutThe IDSync HTTP request was not performed because the SDK+ is disabled due to opt-out.
MPIdentityErrorResponseCodeUnknownThe IDSync HTTP request failed due to an unknown error.

For HTTP status codes (400, 401, 429, 5xx), see Appendix C of the iOS guide.

Android error codesDirect link to Android error codes

On Android, the IDSync API always returns the HTTP status code and body of the underlying HTTP response. For client-side failures (device offline, timeout, invalid request), the SDK+ returns IdentityApi.UNKNOWN_ERROR. For throttling (HTTP 429), it returns IdentityApi.THROTTLE_ERROR. Handle both in your failure listener:

Android IDSync error handling (Kotlin)
MParticle.getInstance()?.Identity()?.identify(identifyRequest)
?.addFailureListener { identityHttpResponse ->
if (identityHttpResponse?.httpCode == IdentityApi.UNKNOWN_ERROR) {
// Device is likely offline — retry the request
} else if (identityHttpResponse?.httpCode == IdentityApi.THROTTLE_ERROR) {
// Throttled (429) — retry with backoff
}
}

Appendix D: Passing Session ID from Web to NativeDirect link to Appendix D: Passing Session ID from Web to Native

When a user journey spans both web and native platforms, you can maintain a consistent Rokt session by passing the session ID from the Web SDK+ to the mParticle React Native SDK+. This is useful for hybrid flows where users complete an action in a WebView (such as a payment page) and return to the native app for confirmation.

Getting the session ID from Web SDK+Direct link to Getting the session ID from Web SDK+

After calling selectPlacements, the session ID is available on the selection context:

Retrieve sessionId from the selection context
const selection = await launcher.selectPlacements({
identifier: "checkout",
attributes: {
email: "user@example.com",
// ... other attributes
}
});

const sessionId = await selection.context.sessionId;

Pass the session ID to your native app using a deep link:

Deep-link to native app
const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}`;
window.location.href = deepLink;

Setting the session IDDirect link to Setting the session ID

Extract the session ID from the deep link in your native platform code and pass it to the mParticle SDK+ before calling selectPlacements. Handle this in your native AppDelegate (iOS) or Activity (Android) before the React Native layer loads:

Set sessionId from deep link (React Native)
import { Linking } from 'react-native';
import MParticle from 'react-native-mparticle';

// Listen for incoming deep links
Linking.addEventListener('url', ({ url }) => {
const sessionId = new URL(url).searchParams.get('sessionId');
if (sessionId) {
// Pass sessionId to the native SDK+ via the platform-specific setSessionId API
// on iOS: MParticle.sharedInstance().rokt.setSessionId(sessionId: sessionId)
// on Android: MParticle.getInstance()?.Rokt()?.setSessionId(sessionId)
}
});

NotesDirect link to Notes

  • Call setSessionId before selectPlacements to ensure the session is used.
  • Empty strings are ignored and will not update the session.
  • Always URL-encode the session ID when passing as a query parameter.

8. Test Your IntegrationDirect link to 8. Test Your Integration

To confirm the SDK+ initializes and events log correctly:

  1. Enable verbose SDK+ logging before initialization so you can see what's being sent.
  2. Build and run your app with the environment set to Development.
  3. Trigger selectPlacements on the screen where the placement should render and confirm the placement loads.
  4. Verify events appear in your mParticle workspace's Live Stream, and confirm the identifyRequest call succeeds.
Enable verbose SDK+ logging
// For iOS verbose logging, add to your Swift AppDelegate:
// MParticle.sharedInstance().logLevel = .verbose

// For Android verbose logging, add to your Application class before MParticle.start():
// MParticle.setLogLevel(MParticle.LogLevel.VERBOSE)

TroubleshootingDirect link to Troubleshooting

If the placement doesn't render or events don't appear, check the native console (Xcode for iOS, Logcat for Android) for Rokt SDK+ errors. Common issues:

Initialization errorsDirect link to Initialization errors

  • Confirm the key and secret in your native initialization match the values from your Rokt account manager.
  • Confirm the native SDK+ start call runs before any selectPlacements or event logging calls.
  • For iOS Shoppable Ads, confirm RoktPaymentExtension is registered after start() and before selectPlacements.

Identity errorsDirect link to Identity errors

If the identity callback fires with an error, see Error Handling for error codes and retry guidance. Without error handling you may see data consistency issues at scale.

Placement not renderingDirect link to Placement not rendering

  • Confirm the placement identifier (e.g. RoktExperience) matches what your Rokt account manager configured.
  • For embedded placements, confirm the embedded view identifier (e.g. RoktEmbedded1) matches the placeholderName on the RoktLayoutView component.
  • Check that the attributes map contains at least email, firstname, lastname, billingzipcode, and confirmationref.
  • For interstitial placements, confirm Platform.OS === 'ios' before calling selectPlacements — interstitial placements are not supported on Android.
Was this article helpful?