React Native Multi-Instance Support

Overview

Starting from CleverTap React Native SDK v4.4.0, Multi-instance support lets one app talk to two or more CleverTap accounts simultaneously.

  • Every CleverTap account has an account ID and an account token.
  • The SDK object that communicates with a single account is called an instance.
  • In JavaScript, you work with a handle, a small object with the same methods as CleverTap, but every call and every listener on it goes to one account only.
  • The top-level CleverTap object is the handle for your default account: the account configured in AndroidManifest.xml / Info.plist. It works exactly as before.
const CleverTap = require('clevertap-react-native');

// Default account (AndroidManifest.xml / Info.plist) — unchanged
CleverTap.recordEvent('App Opened');

// A second account, created from JavaScript
const insurance = await CleverTap.createInstance({
    accountId: 'INSURANCE-ACCOUNT-ID',
    accountToken: 'INSURANCE-TOKEN',
    region: 'eu1'
});
insurance.recordEvent('Policy Viewed', { plan: 'gold' });

// Listen to ONLY the insurance account's events
insurance.addListener(CleverTap.CleverTapProfileDidInitialize, (event) => {
    console.log('Insurance profile ready', event);
});
CallWhich account receives it
CleverTap.recordEvent('App Opened')Default account only
insurance.recordEvent('Policy Viewed', ...)Insurance account only
insurance.addListener(...)Fires for the insurance account's events only. The default account's CleverTapProfileDidInitialize never reaches it.

Prerequisites

  • CleverTap React Native SDK v4.4.0 or above.

The React Native SDK bundles CleverTap Android SDK v8.4.1 and CleverTap iOS SDK v7.8.2. No separate install is needed.

Choosing the right approach

Not every app needs multi-instance support. If your app uses one CleverTap account, nothing changes, keep using the top-level CleverTap object as before. Multi-instance is for apps that need to send data to two or more accounts simultaneously: for example, a super-app where different product lines (insurance, loans, travel) each have their own CleverTap account, or a white-label platform that runs several brands under one binary.

If your app switches entirely from one account to another, a brand switch, a tenant change at login, setInstanceWithAccountId is still the simpler choice. Handles are for when both accounts need to be active at the same time.

Your appWhat to do
One CleverTap account (most apps)Nothing. Keep using CleverTap as before. Read Upgrading from an older SDK version once.
Two or more accounts used at the same timeUse handles. This guide.
The whole app switches from account A to account B (for example, a brand switch)setInstanceWithAccountId still works. See Upgrading from setInstanceWithAccountId.

Types of Accounts

There are three ways an account can exist. Refer to the following table for more information:

WayWho creates itWhenHow you get it in JavaScript
Default accountThe native SDK, from AndroidManifest.xml / Info.plistApp startCleverTap (the top-level object)
Launch config (native code)Your Application / AppDelegateApp start, before any screen is shownCleverTap.getInstance(accountId)
createInstance (JavaScript)Your JavaScriptWhen your JavaScript bundle runs (~2 seconds into a cold start)await CleverTap.createInstance(config)

Which one for my extra account?

  • The account sends push notifications → use a launch config. On Android, push for an extra account is shown only when that account is a launch-config account. On both platforms, the tap that opens the app reaches the account.
  • The account shows in-apps, Native Display units, or variables on the first screen → use a launch config, so the account sends its App Launched event and downloads its content at app start.
  • The credentials are only known at runtime (fetched from your server) → use createInstance.
  • Anything else → either works. createInstance needs no native code.

Create Additional Instances

Use CleverTap.createInstance(config) to create an account from JavaScript. It returns a Promise that resolves with the account's handle.

let insurance;
try {
    insurance = await CleverTap.createInstance({
        accountId: 'INSURANCE-ACCOUNT-ID',
        accountToken: 'INSURANCE-TOKEN',
        region: 'eu1',
        logLevel: 'debug',
        identityKeys: ['Email', 'Identity'],
        encryptionLevel: 'medium'
    });
} catch (error) {
    console.log(error.code, error.message);
    // e.g. EINVALID  createInstance: accountId and accountToken must be non-empty strings
}
🚧

Note

Call createInstance on every app start, before any other call for that account. The native SDK persists the account between runs, but createInstance is what applies your config for the current run.

Config reference

KeyTypeRequiredNotes
accountIdstringYesCleverTap account ID
accountTokenstringYesCleverTap account token
regionstringData center region, e.g. 'eu1', 'in1', 'us1', 'sg1'
proxyDomainstringCustom proxy domain for events. iOS cannot combine with region; region is applied and proxy settings are ignored with a warning. Android applies both.
spikyProxyDomainstringCustom proxy domain for push impression events. iOS: requires proxyDomain; otherwise ignored with a warning.
handshakeDomainstringCustom domain for the SDK's first handshake request
identityKeysstring[]Profile keys that identify a user, e.g. ['Email', 'Identity']. Only for JavaScript-created accounts. The default account reads CLEVERTAP_IDENTIFIER (Android) / CleverTapIdentifiers (iOS).
logLevel'off', 'info', 'debug', 'verbose'Native log level for this account only. 'verbose' maps to 'debug' on iOS. Exact strings only — 'Debug' is rejected.
analyticsOnlybooleanAnalytics only; no in-app or engagement rendering
enablePersonalizationbooleanAllow local reads of profile and event properties
disableAppLaunchedEventbooleanDo not send the automatic App Launched event
encryptionLevel'none', 'medium', 'high'Encryption of data stored on the device. Creation time only. See Encryption.
encryptionInTransitbooleanEncrypt the SDK's network traffic
useCustomCleverTapIdbooleanYou supply the CleverTap ID. Must be given together with cleverTapId.
cleverTapIdstringYour own ID for this user/device. Must be given together with useCustomCleverTapId: true.
androidobject{ useGoogleAdId?: boolean, backgroundSync?: boolean, pushProviders?: [...] }. Ignored on iOS.
iosobject{ disableIDFV?: boolean, enableFileProtection?: boolean }. Ignored on Android.

Keep the following in mind when you build the config:

  • android.pushProviders entries need all four parts, the same four as the manifest CLEVERTAP_PROVIDER_1 key: { type, prefKey, className, messagingSDKClassName }. A missing part rejects the whole call.
  • A null value means "not set".
  • A value of the wrong type (for example logLevel: 3 or analyticsOnly: 'yes') rejects with EINVALID.

What happens when you call it twice

SituationResult
First call for this account in this app runThe account is created with your config. The native SDK saves the config.
Second call for the same account in the same app runResolves immediately with the same handle. The new config is silently ignored.
Next app launch with a changed configThe new config is applied.

Errors

Refer to the following table for errors.

error.codeWhenExample error.message
EINVALIDThe config is wrong. Nothing was created.createInstance: accountId and accountToken must be non-empty strings
EINVALIDcreateInstance: logLevel must be one of off, info, debug, verbose
EINVALIDcreateInstance: cleverTapId and useCustomCleverTapId: true must be given together (or both left out)
ECREATEThe native SDK could not create the account.createInstance failed for accountId INSURANCE-ACCOUNT-ID

Create Accounts at App Launch (Native Launch Configs)

Accounts created from JavaScript exist only once your bundle runs (~2 seconds after a cold start). For accounts that need to receive push notifications or show content on the first screen, use launch configs instead. The SDK creates these accounts at process start, alongside the default account.

Android

If your Application class extends CleverTapApplication, override launchConfigs():

import android.app.Application;
import com.clevertap.android.sdk.CleverTapInstanceConfig;
import com.clevertap.react.CleverTapApplication;
import com.clevertap.react.CleverTapLaunchConfig;
import com.facebook.react.ReactApplication;
import java.util.Collections;
import java.util.List;

public class MainApplication extends CleverTapApplication implements ReactApplication {

    // ... your existing ReactApplication members (reactNativeHost, reactHost)

    @Override
    public List<CleverTapLaunchConfig> launchConfigs() {
        CleverTapInstanceConfig insurance = CleverTapInstanceConfig.createInstance(
                this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1");
        return Collections.singletonList(new CleverTapLaunchConfig(insurance));
    }
}
import android.app.Application
import com.clevertap.android.sdk.CleverTapInstanceConfig
import com.clevertap.react.CleverTapApplication
import com.clevertap.react.CleverTapLaunchConfig
import com.facebook.react.ReactApplication

class MainApplication : CleverTapApplication(), ReactApplication {

    // ... your existing ReactApplication members (reactNativeHost, reactHost)

    override fun launchConfigs(): List<CleverTapLaunchConfig> {
        val insurance = CleverTapInstanceConfig.createInstance(
            this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1"
        )
        return listOf(CleverTapLaunchConfig(insurance))
    }
}

If your Application class does not extend CleverTapApplication, pass the list as the second argument of CleverTapRnAPI.initReactNativeIntegration:

import android.app.Application;
import com.clevertap.android.sdk.ActivityLifecycleCallback;
import com.clevertap.android.sdk.CleverTapInstanceConfig;
import com.clevertap.react.CleverTapLaunchConfig;
import com.clevertap.react.CleverTapRnAPI;
import com.facebook.react.ReactApplication;
import java.util.Collections;

public class MainApplication extends Application implements ReactApplication {

    // ... your existing ReactApplication members (reactNativeHost, reactHost)

    @Override
    public void onCreate() {
        super.onCreate();
        ActivityLifecycleCallback.register(this);

        CleverTapInstanceConfig insurance = CleverTapInstanceConfig.createInstance(
                this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1");
        CleverTapRnAPI.initReactNativeIntegration(this,
                Collections.singletonList(new CleverTapLaunchConfig(insurance)));
    }
}
import android.app.Application
import com.clevertap.android.sdk.ActivityLifecycleCallback
import com.clevertap.android.sdk.CleverTapInstanceConfig
import com.clevertap.react.CleverTapLaunchConfig
import com.clevertap.react.CleverTapRnAPI
import com.facebook.react.ReactApplication

class MainApplication : Application(), ReactApplication {

    // ... your existing ReactApplication members (reactNativeHost, reactHost)

    override fun onCreate() {
        super.onCreate()
        ActivityLifecycleCallback.register(this)

        val insurance = CleverTapInstanceConfig.createInstance(
            this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1"
        )
        CleverTapRnAPI.initReactNativeIntegration(this,
            listOf(CleverTapLaunchConfig(insurance)))
    }
}

iOS

Replace the one-argument applicationDidLaunchWithOptions: call with the two-argument version:

#import <CleverTap-iOS-SDK/CleverTap.h>
#import <CleverTap-iOS-SDK/CleverTapInstanceConfig.h>
#import <clevertap-react-native/CleverTapReactManager.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [CleverTap autoIntegrate];

    CleverTapInstanceConfig *insurance = [[CleverTapInstanceConfig alloc]
        initWithAccountId:@"INSURANCE-ACCOUNT-ID"
             accountToken:@"INSURANCE-TOKEN"
            accountRegion:@"eu1"];

    [[CleverTapReactManager sharedInstance]
        applicationDidLaunchWithOptions:launchOptions
                          launchConfigs:@[[[CleverTapReactLaunchConfig alloc] initWithConfig:insurance]]];

    return YES;
}
import CleverTapSDK
import CleverTapReact

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    CleverTap.autoIntegrate()

    let insuranceConfig = CleverTapInstanceConfig(
        accountId: "INSURANCE-ACCOUNT-ID",
        accountToken: "INSURANCE-TOKEN",
        accountRegion: "eu1"
    )
    let launchConfig = CleverTapReactLaunchConfig(config: insuranceConfig)
    CleverTapReactManager.sharedInstance()?.applicationDidLaunch(
        options: launchOptions,
        launchConfigs: [launchConfig]
    )

    return true
}

JavaScript side

Launch-config accounts already exist when your JavaScript runs. Use getInstance — do not call createInstance for them.

const insurance = CleverTap.getInstance('INSURANCE-ACCOUNT-ID');
insurance.addListener(CleverTap.CleverTapPushNotificationClicked, (event) => {
    // Fires even when this push tap cold-started the app
});

Custom CleverTap ID at Launch

If you supply your own CleverTap ID for an account, pass it with the launch config. It is used only when the account is created for the first time.

CleverTapInstanceConfig insurance = CleverTapInstanceConfig.createInstance(
        this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1");
insurance.setEnableCustomCleverTapId(true);
new CleverTapLaunchConfig(insurance, "CUST-88231");
val insurance = CleverTapInstanceConfig.createInstance(
    this, "INSURANCE-ACCOUNT-ID", "INSURANCE-TOKEN", "eu1"
)
insurance.setEnableCustomCleverTapId(true)
CleverTapLaunchConfig(insurance, "CUST-88231")
insurance.useCustomCleverTapId = YES;
[[CleverTapReactLaunchConfig alloc] initWithConfig:insurance cleverTapID:@"CUST-88231"];
insuranceConfig.useCustomCleverTapId = true
CleverTapReactLaunchConfig(config: insuranceConfig, cleverTapID: "CUST-88231")
📘

Note

If you pass a custom ID but omit the flag, the SDK logs a warning and generates its own ID. A bad launch config is logged and skipped; other accounts are still created.

Get a Handle

Use CleverTap.getInstance(accountId) to get a handle to an account that already exists — either a launch-config account or one you created with createInstance earlier in this app run.

const insurance = CleverTap.getInstance('INSURANCE-ACCOUNT-ID');
insurance.recordEvent('Policy Viewed');
  • Synchronous. Always returns a handle, never null.
  • Returns the same handle every time: getInstance('X') === getInstance('X').
  • If the account does not exist, every call on the handle logs one native warning and does nothing. Promise methods reject; callback methods return an error. The app never crashes.
  • getInstance('') or a non-string logs a console.error and returns the default account's handle.

If you use TypeScript, import the types alongside the SDK:

import * as CleverTap from 'clevertap-react-native';
import type { CleverTapInstance, CleverTapInstanceConfig } from 'clevertap-react-native';

const config: CleverTapInstanceConfig = {
  accountId: 'INSURANCE-ACCOUNT-ID',
  accountToken: 'INSURANCE-TOKEN',
};
const insurance: CleverTapInstance = await CleverTap.createInstance(config);

Track Events

Track events on a handle exactly as you would on the top-level CleverTap object. Each call goes only to that handle's account.

// Default account
CleverTap.recordEvent('App Opened');

// Insurance account
const insurance = CleverTap.getInstance('INSURANCE-ACCOUNT-ID');
insurance.recordEvent('Policy Viewed', { plan: 'gold' });

A handle exposes every event-tracking method: recordEvent, recordChargedEvent, recordScreenView, and so on.

Update Profiles

Profile methods work per handle. Each account maintains its own user profile.

const insurance = CleverTap.getInstance('INSURANCE-ACCOUNT-ID');
insurance.onUserLogin({ Identity: 'jane-001', Email: '[email protected]' });
insurance.profileSet({ Plan: 'gold' });
insurance.getCleverTapID((err, id) => console.log('insurance CleverTap ID', id));

Listen to Events

Every event is delivered to the handle of the account it belongs to. The event-name constants are the same CleverTap.* values you already use.

// Default account's events
const subA = CleverTap.addListener(
    CleverTap.CleverTapInAppNotificationDismissed,
    (e) => console.log('default', e)
);

// Insurance account's events
const subB = insurance.addListener(
    CleverTap.CleverTapInAppNotificationDismissed,
    (e) => console.log('insurance', e)
);

subA.remove(); // detaches only this handler
subB.remove();
Event sourceCleverTap.addListener handlerinsurance.addListener handler
In-app of the default account dismissedYes, firesNo
In-app of the insurance account dismissedNoYes, fires
  • addListener returns a subscription. Call subscription.remove() to detach that specific handler.
  • addOneTimeListener(eventName, handler) fires once for the first matching event of that account, then detaches itself.
  • handle.removeListener(eventName) removes only the handlers added on that handle for that event.
  • Events fired before your JavaScript adds a listener (for example, a push tap that cold-started the app) are held briefly per account and delivered when the listener is added. This covers launch-config accounts and the default account.

Custom templates per account

Register the template definitions once natively, as today. Each account then presents its own templates, so present and close events arrive on the handle, and argument reads and dismissal must use the same handle.

insurance.addListener(CleverTap.CleverTapCustomTemplatePresent, async (templateName) => {
    const text = await insurance.customTemplateGetStringArg(templateName, 'Text');
    await insurance.customTemplateSetPresented(templateName);
    await insurance.customTemplateSetDismissed(templateName);
});
insurance.syncCustomTemplates();

Push for Additional Accounts

The device has one FCM / APNs token, but each account needs it to send push notifications to the device. Pass the token to every account that should be able to push.

CleverTap.setFCMPushToken(token);    // default account
insurance.setFCMPushToken(token);    // insurance account
🚧

Note

An account that sends push notifications must be a launch-config account, not a createInstance account. Only launch-config accounts receive the push that opened the app and are ready before your JavaScript bundle runs. See Create Accounts at App Launch.

Set Offline and Encryption

Set Offline

Pause and resume an account's event tracking and network traffic independently.

insurance.setOffline(true);   // pause the insurance account
insurance.setOffline(false);  // resume

Encryption

Set the encryption level for an account at creation time using the encryptionLevel config key.

LevelValueWhat is encrypted
None'none'Nothing
Medium'medium'PII fields only (email, phone, and so on)
High'high'All data stored on the device
const insurance = await CleverTap.createInstance({
    accountId: 'INSURANCE-ACCOUNT-ID',
    accountToken: 'INSURANCE-TOKEN',
    encryptionLevel: 'high'
});

For the default account, set encryption level via CLEVERTAP_ENCRYPTION_LEVEL in AndroidManifest.xml or CleverTapEncryptionLevel in Info.plist.

Upgrading from setInstanceWithAccountId

setInstanceWithAccountId and getInstance both let you address another account, but they work differently.

CleverTap.setInstanceWithAccountId('B')CleverTap.getInstance('B')
What it doesSwaps the account behind the top-level CleverTap object. All subsequent CleverTap.* calls go to account B.Returns a separate handle for B. CleverTap keeps pointing at the default account.
Use whenThe whole app moves to another account and you do not want to update every call site.You want two accounts at the same time, or need to address B from one place without changing what CleverTap means elsewhere.
Handles from getInstance / createInstanceNot affected by the swap. Each stays pinned to its own account.
StatusSupported, not deprecated.New in v4.4.0.
// Before v4.4.0 — only way to reach account B:
CleverTap.setInstanceWithAccountId('B');
CleverTap.recordEvent('Purchase');          // goes to B
CleverTap.setInstanceWithAccountId('A');    // had to swap back to use A

// From v4.4.0 — no swapping needed:
CleverTap.recordEvent('Purchase');                    // default account
CleverTap.getInstance('B').recordEvent('Purchase');   // B, at the same time
📘

Note

From v4.4.0, after setInstanceWithAccountId('B'), CleverTap.addListener handlers receive only B's events. In earlier versions they received events from both the old and the new account mixed together.

Upgrading from an older SDK version

Nothing changes for an app that uses one account and calls everything through the CleverTap object. Three behaviours did change. Check whether any applies to you.

ChangeBefore v4.4.0From v4.4.0Who is affected
CleverTap.removeListener(eventName)Removed every listener for that event name in the whole app, including listeners other libraries added on React Native's raw event emitter.Removes only the handlers added through CleverTap.addListener.Apps that relied on it to clear listeners added elsewhere. Remove those where they were added.
Listeners after setInstanceWithAccountId('B')CleverTap.addListener handlers received the old and the new account's events, mixed.Handlers receive only B's events.Apps that swap accounts and expected both streams. Use getInstance('A').addListener(...) for the other account.
Direct NativeModules.CleverTapReact.* callsWorked by accident.Break: every native method has a new trailing account argument. Old-architecture Android throws got N arguments, expected N+1, in release builds too.Any code that bypassed the CleverTap object. Call CleverTap.* instead.

Also new, and harmless for existing code:

  • CleverTap.addListener now returns a subscription object ({ remove }). It returned nothing before.
  • On iOS, callback methods now return an error when the account does not exist. Before, most of them never called back.

Rules and Warnings

Refer to the following table for the rules you must follow.

RuleWhat goes wrong if you skip it
The top-level CleverTap object is the manifest / plist account. If your app has no manifest / plist account, use handles for everything.CleverTap.recordEvent(...) logs CleverTap default instance is not available — call ignored and does nothing.
createInstance(config), or a launch config, must be the first thing that touches an account, on every app run.getInstance('B') before createInstance may restore the account with its config from the previous launch (for example, an outdated region).
For launch-config accounts, use getInstance only. Never pass a config from JavaScript for them.A second config in the same run is silently ignored; a difference between the two hides until it causes incorrect data.
createInstance called twice in the same run returns the existing account and ignores the new config. Config changes take effect on the next launch.The new config appears to have applied but has not.
identityKeys and encryptionLevel for the default account come from the manifest / plist only. For JavaScript-created accounts they come from createInstance only.The other path is silently ignored by the native SDK.
cleverTapId and useCustomCleverTapId: true must be given together.createInstance rejects with EINVALID.
OS-level methods (registerForPush, getInitialUrl, createNotification, notification channel methods) belong on CleverTap, not on a handle.On a handle they log a console.warn and do nothing.
setDebugLevel is global. For per-account logging, use the logLevel config key at creation.A per-account expectation that cannot be met.
Never call NativeModules.CleverTapReact.* directly. Always call through the CleverTap object or a handle.Old-architecture Android throws got N arguments, expected N+1 on every call, including in release builds.
Accounts that send push, or that need in-apps or display units on the first screen, should be launch-config accounts.A createInstance-only account misses the push that opened the app and gets its launch-time content only on its next App Launched.

Refer to the following table for warnings and their meanings.

MessageWhereMeaningFix
CleverTap instance not found for accountId: X — call ignored.NativeYou called a method on getInstance('X'), but no account X exists in this app run.Call createInstance for X first, or list it as a launch config. Check the ID for typos.
CleverTap default instance is not available — call ignored.NativeYou called a top-level CleverTap.* method, but the app has no manifest / plist account.Add the default account, or use handles for everything.
[CleverTap] <method> is not supported on account handles; call it on the top-level CleverTap objectJavaScriptYou called an OS-level method on a handle.Call it on CleverTap.
[CleverTap] getInstance called with an invalid accountId; returning the DEFAULT account handle.JavaScript (console.error)getInstance received an empty string, undefined, or a non-string.Pass the correct account ID string.
createInstance: iOS cannot combine region with proxyDomain/spikyProxyDomain; region applied, proxy settings ignorediOSConfig has both region and a proxy domain.Pass only one on iOS.
createInstance: spikyProxyDomain requires proxyDomain; ignorediOSspikyProxyDomain without proxyDomain.Pass both.
Promise rejected with EINVALIDJavaScriptThe createInstance config is wrong. The message names the field.Fix the config. See Errors.
Promise rejected with ECREATEJavaScriptThe native SDK could not create the account.Check the native log for the SDK's own error.
Callback error CleverTap not initialized (Android) / CleverTap is not initialized (iOS)Callback methodsThe addressed account does not exist.Call createInstance first, or list it as a launch config.

FAQs

Do I need to change anything if my app uses only one CleverTap account?
No. Keep using the top-level CleverTap object as before. Read Upgrading from an older SDK version once to confirm none of the three behaviour changes apply to your app.

Can I create more than two accounts?
Yes. Each call to createInstance (or each entry in your launch configs) creates one account. There is no documented limit, but each active account adds network and memory overhead.

What happens if I call getInstance before createInstance?
You get a handle, but every call on it logs one native warning and does nothing. The app never crashes. Create the account first.

Can I use createInstance and a launch config for the same account?
No. Use one or the other. If the account is a launch config, use getInstance in JavaScript. Passing a config via createInstance in the same run is silently ignored, and a difference between the two configs hides until it causes incorrect data.

What is a launch-config account?
An account listed in your Application / AppDelegate so it is created at process start, before any screen is shown. Required for accounts that send push notifications or display content on the first screen. See Create Accounts at App Launch.

Additional Resources


Did this page help you?
Suggest Edit
CleverTap Ask AI Widget (CSP-Safe)