Skip to content

Initial SDK setup

This reference article covers how to install the Braze SDK for React Native. Installing the Braze React Native SDK provides basic analytics functionality and lets you integrate in-app messages and Content Cards for both iOS and Android with just one codebase.

Prerequisites and compatibility

To set up this SDK, React Native v0.71 or later is required. For the full list of supported versions, see our React Native SDK GitHub repository.

React Native New Architecture Support

Using Braze with the New Architecture

The Braze React Native SDK is compatible with any apps using the React Native New Architecture starting from SDK version 2.0.1+.

As of SDK version 6.0.0, Braze has been upgraded internally to a React Native Turbo Module, which can still be used with either the New Architecture or the legacy bridge architecture. Because the Turbo Module is backwards compatible, no migration steps are required other than the breaking changes mentioned in the Changelog and requiring React Native v0.70+.

Step 1: Integrate the Braze library

1
npm install @braze/react-native-sdk
1
yarn add @braze/react-native-sdk

Step 2: Complete native setup

Step 2.1: Install the Braze Expo plugin

Ensure that your version of the Braze React Native SDK is at least 1.37.0. Then, install the Braze Expo plugin.

1
expo install @braze/expo-plugin

Step 2.2: Add the plugin to your app.json

In your app.json, add the Braze Expo Plugin. You can provide the following configuration options:

Method Type Description
androidApiKey string Required. The API key for your Android application, located in your Braze dashboard under Manage Settings.
iosApiKey string Required. The API key for your iOS application, located in your Braze dashboard under Manage Settings.
baseUrl string Required. The SDK endpoint for your application, located in your Braze dashboard under Manage Settings.
enableBrazeIosPush boolean iOS only. Whether to use Braze to handle push notifications on iOS. Introduced in React Native SDK v1.38.0 and Expo Plugin v0.4.0.
enableFirebaseCloudMessaging boolean Android only. Whether to use Firebase Cloud Messaging for push notifications. Introduced in React Native SDK v1.38.0 and Expo Plugin v0.4.0.
firebaseCloudMessagingSenderId string Android only. Your Firebase Cloud Messaging sender ID. Introduced in React Native SDK v1.38.0 and Expo Plugin v0.4.0.
sessionTimeout integer The Braze session timeout for your application in seconds.
enableSdkAuthentication boolean Whether to enable the SDK Authentication feature.
logLevel integer The log level for your application. The default log level is 8 and will minimally log info. To enable verbose logging for debugging, use log level 0.
minimumTriggerIntervalInSeconds integer The minimum time interval in seconds between triggers. Defaults to 30 seconds.
enableAutomaticLocationCollection boolean Whether automatic location collection is enabled (if the user permits).
enableGeofence boolean Whether geofences are enabled.
enableAutomaticGeofenceRequests boolean Whether geofence requests should be made automatically.
dismissModalOnOutsideTap boolean iOS only. Whether a modal in-app message will be dismissed when the user clicks outside of the in-app message.
androidHandlePushDeepLinksAutomatically boolean Android only. Whether the Braze SDK should automatically handle push deep links.
androidPushNotificationHtmlRenderingEnabled boolean Android only. Sets whether the text content in a push notification should be interpreted and rendered as HTML using android.text.Html.fromHtml.
androidNotificationAccentColor string Android only. Sets the Android notification accent color.
androidNotificationLargeIcon string Android only. Sets the Android notification large icon.
androidNotificationSmallIcon string Android only. Sets the Android notification small icon.
iosRequestPushPermissionsAutomatically boolean iOS only. Whether the user should automatically be prompted for push permissions on app launch.
enableBrazeIosRichPush boolean iOS only. Whether to enable rich push features for iOS.
enableBrazeIosPushStories boolean iOS only. Whether to enable Braze push stories for iOS.
iosPushStoryAppGroup string iOS only. The app group used for iOS push stories.

Example configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
  "expo": {
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          "androidApiKey": "YOUR-ANDROID-API-KEY",
          "iosApiKey": "YOUR-IOS-API-KEY",
          "baseUrl": "YOUR-SDK-ENDPOINT",
          "sessionTimeout": 60,
          "enableGeofence": false,
          "enableBrazeIosPush": false,
          "enableFirebaseCloudMessaging": false,
          "firebaseCloudMessagingSenderId": "YOUR-FCM-SENDER-ID",
          "androidHandlePushDeepLinksAutomatically": true,
          "enableSdkAuthentication": false,
          "logLevel": 0,
          "minimumTriggerIntervalInSeconds": 0,
          "enableAutomaticLocationCollection": false,
          "enableAutomaticGeofenceRequests": false,
          "dismissModalOnOutsideTap": true,
          "androidPushNotificationHtmlRenderingEnabled": true,
          "androidNotificationAccentColor": "#ff3344",
          "androidNotificationLargeIcon": "@drawable/custom_app_large_icon",
          "androidNotificationSmallIcon": "@drawable/custom_app_small_icon",
          "iosRequestPushPermissionsAutomatically": false,
          "enableBrazeIosPushStories": true,
          "iosPushStoryAppGroup": "group.com.example.myapp.PushStories"
        }
      ],
    ]
  }
}

Step 2.3: Build and run your application

Prebuilding your application will generate the native files necessary for the Braze SDK to work.

1
expo prebuild

Run your application as specified in the Expo docs. Note that making any changes to the configuration options will require you to prebuild and run the application again.

Step 2.1: Add our repository

In your top-level project build.gradle, add the following under buildscript > dependencies:

1
2
3
4
5
6
7
buildscript {
    dependencies {
        ...
        // Choose your Kotlin version
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10")
    }
}

This will add Kotlin to your project.

Step 2.2: Configure the Braze SDK

To connect to Braze servers, create a braze.xml file in your project’s res/values folder. Paste the following code and replace the API key and endpoint with your values:

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOU_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>

Add the required permissions to your AndroidManifest.xml file:

1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 2.3: Implement user session tracking

The calls to openSession() and closeSession() are handled automatically. Add the following code to the onCreate() method of your MainApplication class:

1
2
3
4
5
6
7
8
import com.braze.BrazeActivityLifecycleCallbackListener;

@Override
public void onCreate() {
    super.onCreate();
    ...
    registerActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
}
1
2
3
4
5
6
7
import com.braze.BrazeActivityLifecycleCallbackListener

override fun onCreate() {
    super.onCreate()
    ...
    registerActivityLifecycleCallbacks(BrazeActivityLifecycleCallbackListener())
}

Step 2.4: Handle intent updates

If your MainActivity has android:launchMode set to singleTask, add the following code to your MainActivity class:

1
2
3
4
5
@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}
1
2
3
4
override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    setIntent(intent)
}

Step 2.1: (Optional) Configure Podfile for dynamic XCFrameworks

To import certain Braze libraries, such as BrazeUI, into an Objective-C++ file, you will need to use the #import syntax. Starting in version 7.4.0 of the Braze Swift SDK, binaries have an optional distribution channel as dynamic XCFrameworks, which are compatible with this syntax.

If you’d like to use this distribution channel, manually override the CocoaPods source locations in your Podfile. Reference the sample below and replace {your-version} with the relevant version you wish to import:

1
2
3
pod 'BrazeKit', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeKit.podspec'
pod 'BrazeUI', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeUI.podspec'
pod 'BrazeLocation', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeLocation.podspec'

Step 2.2: Install pods

Since React Native automatically links the libraries to the native platform, you can install the SDK with the help of CocoaPods.

From the root folder of the project:

1
2
3
4
5
# To install using the React Native New Architecture
cd ios && RCT_NEW_ARCH_ENABLED=1 pod install

# To install using the React Native legacy architecture
cd ios && pod install

Step 2.3: Configure the Braze SDK

Import the Braze SDK at the top of the AppDelegate.swift file:

1
import BrazeKit

In the application(_:didFinishLaunchingWithOptions:) method, replace the API key and endpoint with your app’s values. Then, create the Braze instance using the configuration, and create a static property on the AppDelegate for easy access:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
    // Setup Braze
    let configuration = Braze.Configuration(
        apiKey: "{BRAZE_API_KEY}",
        endpoint: "{BRAZE_ENDPOINT}")
    // Enable logging and customize the configuration here.
    configuration.logger.level = .info
    let braze = BrazeReactBridge.perform(
      #selector(BrazeReactBridge.initBraze(_:)),
      with: configuration
    ).takeUnretainedValue() as! Braze

    AppDelegate.braze = braze

    /* Other configuration */

    return true
}

// MARK: - AppDelegate.braze

static var braze: Braze? = nil

Import the Braze SDK at the top of the AppDelegate.m file:

1
2
#import <BrazeKit/BrazeKit-Swift.h>
#import "BrazeReactBridge.h"

In the application:didFinishLaunchingWithOptions: method, replace the API key and endpoint with your app’s values. Then, create the Braze instance using the configuration, and create a static property on the AppDelegate for easy access:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Setup Braze
  BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{BRAZE_API_KEY}"
                                                                    endpoint:@"{BRAZE_ENDPOINT}"];
  // Enable logging and customize the configuration here.
  configuration.logger.level = BRZLoggerLevelInfo;
  Braze *braze = [BrazeReactBridge initBraze:configuration];
  AppDelegate.braze = braze;

  /* Other configuration */

  return YES;
}

#pragma mark - AppDelegate.braze

static Braze *_braze = nil;

+ (Braze *)braze {
  return _braze;
}

+ (void)setBraze:(Braze *)braze {
  _braze = braze;
}

Step 3: Usage

Once installed, you can import the library in your React Native code:

1
import Braze from "@braze/react-native-sdk";

Reference our sample project for more details.

Test your basic integration

At this point, you can verify that the SDK is integrated by checking session statistics in the dashboard. If you run your application on either platform, you should see a new session in dashboard (in the Overview section).

You can start a session for a particular user by calling the following code in your app.

1
Braze.changeUser("userId");

For example, you can assign the user ID at the startup of the app:

1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useEffect } from "react";
import Braze from "@braze/react-native-sdk";

const App = () => {
  useEffect(() => {
    Braze.changeUser("some-user-id");
  }, []);

  return (
    <div>
      ...
    </div>
  )

You can then search for the user with some-user-id in the dashboard under User Search. There, you can verify that session and device data have been logged.

HOW HELPFUL WAS THIS PAGE?
New Stuff!