Blue Triangle Help Center
Auto Light Dark
Auto Light Dark

Blue Triangle SDK for React Installation Guide

Introduction

The Blue Triangle SDK for React enables application owners to track their users’ experience so they can focus on user experience issues that impact their business outcomes.

PLEASE read through the mandatory instrumentation instructions to ensure that 

  • Mobile native views are reported for views and performance

  • User sessions are properly stitched between mobile native views and webviews

  • Network details are reported (detailed backend interaction, errors etc.)

  • Checkout events are reported

Release Notes

Version

Date

Notes

0.2.1

May 30, 2025

No-code support for integrated Clarity (session playback) experience. The SDK will automatically detect the presence of Clarity, request a playback URL, which would show in the performance details page. To read more about Blue Triangle's Clarity integration, please visit here.

Supported SDK Metrics

  • Performance & Network Timings

    • Main Timers

    • Network Timers

    • Custom Timers

  • Errors & Crashes

  • Application Not Responding (ANR)

  • HTTP Response Codes

  • App Crashes

  • Device Stats & Session Attributes

    • OS/OS Version

    • App Version

    • Device Type

    • Geographical/Country

    • CPU Usage

    • Memory Warnings

    • Memory/Out of Memory

    • Hot/Cold Launch

    • Custom variables

    • Network Type – Coming soon

    • Device Model- Coming soon

Instrumenting Your App with the Blue Triangle SDK

SDK Default Values

Feature

Required (For installation), 
Recommended, 
Optional

Configuration property name

Default Value

Notes

Site ID

Required (Set paraemeter)

siteID

This will ensure data from the SDK is sent to the correct account in Blue Triangle

Native View Tracking

Required (Add Code)

enableScreenTracking

TRUE

This will enable automatic mobile view tracking. 

Webview Capture

Required (Add Code)

BTTWebViewTracker.onLoadResource(view, url)

TRUE

This will enable session stitching

Network Capture

Required (Add Code, change setting for debugging)

networkSampleRate

0.05 (5%) 
Min = 0.0 (Disabled) 
Max = 1.0 (100%)

This sample rate defines the percentage of user sessions for which network calls will be captured. A value of 0.05 = 5%, 0.0 = no tracking, and 1.0 means that all  network requests will be captured for any user sessions. It is recommended to set to 1.0 (100%) when installing or debugging the SDK.

Campaign Configuration Parameters

Recommended

abTestID

These fields can be used to identify and segment users for optimized analytics contextualization. They can be set in advance and changed in real time.

campaignMedium

campaignName

campaignSource

dataCenter

trafficSegmentName

Offline Caching

Optional, changes to default values are not recommended

cacheMemoryLimit

30 Mb 
Min = 0Mb 
Max = 100MB

The amount of memory the cache uses (in bytes) to store Blue Triangle data when the device is offline

cacheExpiryDuration

48 Hours 
Min = 0 Hours 
Max = 120 Hours

The amount of time (in milliseconds) the data is kept in the cache before it expires

Memory Warning

Optional, changes to default values are not recommended

enableMemoryWarning

TRUE

This will enable memory warnings

Performance Monitoring CPU and Memory

Optional, changes to default values are not recommended

isPerformanceMonitorEnabled

TRUE

This will enable or disable CPU and Memory performance metrics

performanceMonitorSampleRate

1000ms

Set the sampling interval for performance monitoring in milliseconds

ANR Detection

Optional, changes to default values are not recommended

ANRMonitoring

TRUE

This will enable ANR tracking

ANRWarningTimeInterval

5 seconds 
Min = 3s 
Max = 10s

Use this configuration property to configure the interval duration that qualifies as an ANR state 

Track Crashes

Optional, changes to default values are not recommended

enableTrackingNetworkState

TRUE

Set this property to TRUE to enable crash tracking

Network State Capture

Optional, changes to default values are not recommended

enableTrackingNetworkState

TRUE

Network interfaces include wifi, ethernet, cellulat, etc. This enables the network state, (associated with all Timers, Errors and Network Requests captured by the SDK)

Application Hot/Cold Launch Time

Optional, changes to default values are not recommended

enableLaunchTime

TRUE

Report on the application hot/cold launch time

Mandatory Installation Steps

SDK Installation

To add the package, run the following command:

npm install @bluetriangle/react-native-btt-sdk

For iOS, run the following command to install the native dependencies

cd ios && pod install

SDK Configuration

Add the following code snippet in your index.js/jsx/ts/tsx file:

import {BTTConfiguration, BTTOptions} from '@bluetriangle/react-native-btt-sdk';

//Add the code snippet to configure sdk
const bttOptions = new BTTOptions()

BTTConfiguration.configure(<site ID>, bttOptions)

Replace <Site ID> with your project ID from Blue Triangle.

Site ID Configuration

In order to use Blue Triangle, the Site ID needs to be configured in the SDK. 

Find your site ID by:

  • Login to https://portal.bluetriangletech.com 

  • Click on "Settings" icon

  • Open the Sites page under the Settings Modal. (Logged in user needs to have access to Sites page)

  • Get the value for Site ID from the "Tag Prefix" column for the desired "Site Name"

Native View Performance Tracking

Native view tracking automatically tracks screen views in your app. 

Automated Screen Tracking for React Navigation

If you are using React Navigation library to perform screen navigation in your app, then all screens can be tracked by BTTSdk automatically by just adding two lines of code in the NavigationContainer, as shown in below example.:

import React from 'react';
import { BTTNavigationContainerTracker } from '@bluetriangle/react-native-btt-sdk';
import NavigationContainer, { useNavigationContainerRef } from '@react-navigation/native';
function App() {
  const navigationRef = useNavigationContainerRef();
  return (
    <NavigationContainer
      ref = { navigationRef }
      onReady = {() => {
        BTTNavigationContainerTracker.onContainerStateChange(navigationRef)
      }}
      onStateChange={async () => {
        BTTNavigationContainerTracker.onContainerStateChange(navigationRef)
      }}
    >
      {/* ... */}
    </NavigationContainer>
  );
}

BTTNavigationContainerTracker has a single method for screen tracking which is called in onReady and onStateChange. These two lines of code can track all of the happening in the navigation container.

This solution is based on the React Navigation reference for screen tracking analytics.

With the above setup, all screens can be tracked except when the app is put in the background. In that case, we don't get onStateChange callback. Hence, to overcome this, we need to add another listener to track when the app is put in the background and when it comes back to the foreground. To do that, add the following code snippet in your app component:

AppState.addEventListener('change', state => {
  if (state === 'active') {
  // do this
  BTTNavigationContainerTracker.onContainerStateChange(navigationRef)
  }
  else if (state === 'background') {
  // do that
  BTTNavigationContainerTracker.applicationDidEnterBackground(navigationRef)
  }
});

Manual Screen Tracking

If you are using any other way to perform screen navigation in your app or you want to track only a certain set of screens in your app, you can use manual tracking.

To use a manual tracker, you need to first import the BTTScreenTracker object from '@bluetriangle/react-native-btt-sdk'. Create a timer object with the pageName.

The BTTScreenTracker object has the following functions:

  • manualTracker.startTracking():

  • manualTracker.stopTracking():

You need to call the function startTracking when the component that you want to track is rendered for the first time, and you need to call stopTracking when the component is about to disappear. You can refer to the following code snippet.

import React, { useEffect } from 'react';
import { BTTScreenTracker } from '@bluetriangle/react-native-btt-sdk';

function YourComponent({ }) {
var manualTracker:BTTScreenTracker

useEffect(() => {
  const unsubscribeFocus = navigation.addListener('focus', () =>{
  
    if(manualTracker == undefined){
    manualTracker = new BTTScreenTracker("PageName")
    }
    manualTracker.startTracking()
  });
  const unsubscribeBlur = navigation.addListener('blur', () =>{
    manualTracker.stopTracking()
});

return () => {
  unsubscribeFocus()
  unsubscribeBlur()
  };
}, []);

return (
  {/* ... */}
  );
}

Native View/Webview Tracking/Session Stitching

Websites shown in webview that are tracked by BlueTriangle can be tracked in the same session as the react app. To achieve this, follow the steps below to configure the WebView:

import { BTTWebViewTracker } from '@bluetriangle/react-native-btt-sdk'

const MyWebView = ({navigation, route}) => {
  return (
    <WebView
      domStorageEnabled={true}
      javaScriptEnabled={true}
      injectedJavaScriptBeforeContentLoaded={BTTWebViewTracker.injectSession()} >
    </WebView>
  );
};

export default MyWebView;

If you are already using injectedJavaScriptBeforeContentLoaded to inject any of your scripts. Append your script to BTTWebViewTracker.injectSession() like below.

import { BTTWebViewTracker } from '@bluetriangle/react-native-btt-sdk'

const MyWebView = ({navigation, route}) => {
  return (
    <WebView
      domStorageEnabled={true}
      javaScriptEnabled={true}
      injectedJavaScriptBeforeContentLoaded={BTTWebViewTracker.injectSession() + "YOUR SCRIPT"}>
    
    </WebView>
  );
};

export default MyWebView;

Network Capture  

BlueTriangle SDK allows capturing of network state data. Network state refers to the availability of any network interfaces on the device. Network interfaces include wifi, ethernet, cellular, etc. Once Network state capturing is enabled, the Network state is associated with all Timers, Errors and Network Requests captured by the SDK.

Permission on Android
In Android, Network state capturing requires android.permission.ACCESS_NETWORK_STATE permission. So, include the permission into your AndroidManifest.xml file as follows:

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

Note:

  • If Network state capture is enabled and ACCESS_NETWORK_STATE permission is not granted, then the SDK won't track network state as it won't be able to.

  • This feature is only available on API Level 21 and above.

To disable Network state capture, use the trackNetworkState property on the BTTOptions object as follows:

const bttOptions = new BTTOptions()
bttOptions.trackNetworkState = false

Network Capture Sample Rate

Network Sample rate defines the percentage of user sessions for which network calls will be captured. A value of 0.025 means that 2.5% of your users' sessions' network requests will be tracked. A value of 0.0 means that no network requests will be captured for any user sessions, and a value of 1.0 will track all network requests for all user sessions. Whether network requests will be tracked is determined on application start, and will either be set to on or off for the entirety of the user session.

You can configure the sample rate by setting the networkSampleRate property in the configuration object as shown below:

const bttOptions = new BTTOptions()
bttOptions.networkSampleRate = 0.05


To disable network capture, set 0.0 to 'bttOptions.networkSampleRate' during configuration.

It is recommended to have 100% sample rate while developing/debugging. By setting 'bttOptions.networkSampleRate' to 1.0 during configuration.

Checkout Event Data

Checkout Event Data Upon a customer checkout, it is possible to configure the following data parameters for the event.

Brand Value

import { BTTTimer, PurchaseConfirmation } from '@bluetriangle/react-native-btt-sdk';
const timer = new BTTTimer("Confirmation")
timer.startTimer()
const purchaseConfirmation = new PurchaseConfirmation.Builder()
.setBrandValue(100.0)
.build()
timer.stopTimer(purchaseConfirmation)


Cart Value, Cart Count, Cart Count Checkout, Order Number, Order Time

import { BTTTimer, PurchaseConfirmation } from '@bluetriangle/react-native-btt-sdk';
const timer = new BTTTimer("Confirmation")
timer.startTimer()
const purchaseConfirmation = new PurchaseConfirmation.Builder()
.setCartValue(99.0)
.setCartCount(2)
.setCartCountCheckout(2)
.setOrderNumber("ORD-123345")
.build() 
timer.stopTimer(purchaseConfirmation)

Blue Triangle Campaign Configuration Fields- coming soon

The following fields can be used to identify and segment users for optimized analytics contextualization. They can be configured in the SDK and modified in the app in real time, and they show in the Blue Triangle portal as parameters for reporting.

abTestID="MY_AB_TEST_ID"

Capture a variable that allows us to understand a live AB test of two variants in the app.

campaignMedium="MY_CAMPAIGN_MEDIUM"

Understand the general reason the journey started (email, paid search, organic search, etc)

campaignName="MY_CAMPAIGN_NAME"

Understand the campaign name that started the journey. 

campaignSource="MY_CAMPAIGN_SOURCE"

Understanding the type of marketing campaign. 

dataCenter="MY_DATA_CENTER"

Understand if you have multiple data centers that serve your customers you can group data by them.

trafficSegmentName="MY_SEGMENT_NAME"

This can be used to segment environment type.  For instance, we can use this to understand if you have beta vs prod but both are live versions of the app.

 

Tracker.instance?.setSessionAbTestIdentifier("MY_AB_TEST_ID")
Tracker.instance?.setSessionCampaignMedium("MY_CAMPAIGN_MEDIUM")
Tracker.instance?.setSessionCampaignName("MY_CAMPAIGN_NAME")
Tracker.instance?.setSessionCampaignSource("MY_CAMPAIGN_SOURCE")
Tracker.instance?.setSessionDataCenter("MY_DATA_CENTER")
Tracker.instance?.setSessionTrafficSegmentName("MY_SEGMENT_NAME")

 

Custom Timers 

While mobile Views are automatically tracked upon installation, Custom Timers can also be configured if needed. 

Using Custom Timer: To use a custom timer, you need to first import the BTTTimer object from @bluetriangle/react-native-btt-sdk. Create timer object with pageName.

The BTTTimer object has the following functions:

  • timer.startTimer():

  • timer.stopTimer():

import { BTTTimer } from '@bluetriangle/react-native-btt-sdk';

const timer = new BTTTimer(pageName)
timer.startTimer()
timer.stopTimer()

Add Cart Value: You can add cart value to the BTTTimer object using the PurchaseConfirmation object as follows:

import { BTTTimer, PurchaseConfirmation } from '@bluetriangle/react-native-btt-sdk';

const timer = new BTTTimer(pageName)
timer.startTimer()

const purchaseConfirmation = new PurchaseConfirmation.Builder()
.setCartValue(99.99)
.build()
timer.stopTimer(purchaseConfirmation)

Custom Variables 

It is a developer-defined property introduced into the BTT SDK payload that developers can include to collect and track extra information specific to their application needs.

To introduce a custom variable, the developer first needs to create it on the BlueTriangle portal by following the instructions on the Custom Variables Page.

To use a custom variable, you need to first import the BTTCustomVariable object from @bluetriangle/react-native-btt-sdk.

Then the developer needs to usea  custom variable function as below:

import {
BTTCustomVariable,
} from '@bluetriangle/react-native-btt-sdk';

//In order to set custom variable using the below function:
BTTCustomVariable.setCustomVariable('CV1','value')

const customVariables = {
'CV1': 'Value1',
'CV2': 'Value1',
};
BTTCustomVariable.setCustomVariables(customVariables)

// In order to get the custom variable value, call the following with the variable name
const customVariable = BTTCustomVariable.getCustomVariable('CV1')

const customVariables = BTTCustomVariable.getCustomVariables()

// In order to clear the custom variable value, call the following with the variable name
BTTCustomVariable.clearCustomVariable('CV1')

BTTCustomVariable.clearAllCustomVariables()

where <VARIABLE NAME> is the variable name of the custom variable that the user added to the portal while creating the custom variable e.g. CV1, CV2, etc, and is whatever the developer wants to set in these fields.

Once the value is set, it will be sent with each page view until it is cleared by calling any of the above clear methods.

To view one of the values on the portal, navigate to the path 'Menu > Native App Monitoring > Native App Performance Detail' or go to the Session Lookup Page. Then, search by session ID and see the Performance Measurement Details for the specific page. For more details, click here.

Optional Configuration Steps

ANR Detection

The ANR Detector automatically identifies blocks in the main thread over a specified period of time and reports them as Application Not Responding (ANR) incidents.

You can also configure the ANR Interval (sec) by setting trackAnrIntervalSec property in BTTOption.

By default, the ANR interval is set to 5 seconds.

To disable ANR detection, set the trackAnr property to false from BTTOptions at the time of configuration.

Memory Warning 

The SDK automatically tracks and reports memory warnings based on the memory usage of the app. Depending on the platform, the definition of memory warning differs. They are explained below:

Android
Memory warning is an error that is reported when the code uses up more than 80% of the app's available memory (heap capacity).

Currently, Memory Warning is only captured for memory used by the native modules. Memory used in React code is not considered in the memory warning.

iOS
Track iOS reported a low memory warning. iOS reported memory warnings can be tracked by btt.

How to disable
To disable memory warning, set the memoryWarning property to false from BTTOptions at the time of configuration.

Memory Usage

Memory usage is the amount of memory used by the code during the Timer interval. This is measured in number of bytes.

Against each timer, 3 Memory measurements are being sent, minimum, maximum, and average.

To set the interval (in ms) at which the Memory usage is being captured, set the following field:

const bttOptions = new BTTOptions()
bttOptions.performanceMonitoringInterval = 1000


To disable Memory usage, set the following field:

const bttOptions = new BTTOptions()
bttOptions.performanceMonitoring = false

CPU Usage

CPU Usage is the amount of CPU being used by the code during the Timer interval. This is measured in the form of 0-100%.

Against each timer, 3 CPU measurements are being sent, minimum, maximum and average.

To set the interval (in ms) at which the CPU usage is being captured, set the following field in BlueTriangleConfiguration:

const bttOptions = new BTTOptions()
bttOptions.performanceMonitoringInterval = 1000


To disable CPU usage set the following field in BTTOptions:

const bttOptions = new BTTOptions()
bttOptions.performanceMonitoring = false

Track Crashes 

The SDK automatically tracks and reports crashes. To disable this feature, just set the trackCrash property to false from BTTOptions at the time of configuration.

Offline Caching 

To support offline usage tracking, timer and crash reports that cannot be sent immediately will be cached in the application's cache directory and retried when a successful submission of a timer occurs.

Memory Limit

The amount of memory the cache uses (in bytes) can be configured by setting the cacheMemoryLimit property of the BTTOptions object:

const bttOptions = new BTTOptions()
bttOptions.cacheMemoryLimit = 200000L

If new data is sent to the cache after the memory limit is exceeded, the cache deletes the oldest data and then adds the new data. So, only the most recently captured user data is tracked by the cache. By default the memory limit is 30Mb.

Expiry Duration

The amount of time (in milliseconds) the data is kept in the cache before it expires can be configured by setting the cacheExpiryDuration property of the BTTOptions object:

const bttOptions = new BTTOptions()
bttOptions.cacheExpiryDuration = 86400000L

The data that is kept longer in cache than the expiry duration is automatically deleted. By default the expiry duration is 48 hours.

Launch Time 

Blue Triangle tracks app launch performance. Launch time refers to the duration it takes for an app to become ready for user interaction after it has been started. Blue Triangle automatically tracks both hot launch and cold launch.

Cold Launch

A cold launch is a launch wherein the app process was not already in main memory. This can happen if the System or user terminated your app's process or the app is launching for the first time since it's installed/updated or since the device was booted.

The latency for cold launch is calculated differently based on the platform. It's as follows:

Android
It is the time between the onCreate of the BlueTriangle SDK's ContentProvider and onResume call for the first Activity.

iOS
It is the time between the process start time and end of 'applicationDidBecomeActive(:)'

Warm Launch (Only applicable to Android)

A Warm Launch occurs when the app is evicted from memory by the system when it's in the background and the user re-launches it bringing it back to the foreground. This type of launch has less overhead than the cold start, but since the activity needs to be recreated, it takes somewhat longer than a hot start.
The BlueTriangle SDK measures the warm launch latency, which is the time between the onCreate and onResume of the first Activity after the app is brought into foreground.

You can disable the Launch Time feature by setting the following field in BTTOptions:

const bttOptions = new BTTOptions()
bttOptions.launchTime = false
Hot Launch

A hot launch is launch when app process was already in main memory. This can happen when user launches the app from the background.

The latency for hot launch is calculated differently based on the platform. It's as follows:

Android
It is the time between the onStart and onResume of the first Activity after the app is brought into the foreground.

iOS
It is the time between the end of 'applicationWillEnterForeground(:)' and end of 'applicationDidBecomeActive(:)'. So that hot launch time taken by 'applicationDidBecomeActive(:)'.

In both the platforms, Locking and Unlocking the device is considered as a Hot Launch.

Warm Launch (Only applicable to Android)
A Warm Launch occurs when the app is evicted from memory by the system when it's in the background and the user re-launches it bringing it back to foreground. This type of launch has less overhead than the cold start but since the activity needs to be recreated, it takes somewhat longer than a hot start.
The BlueTriangle SDK measures the warm launch latency, which is the time between the onCreate and onResume of the first Activity after the app is brought into foreground.

You can disable Launch Time feature by setting the following field in BTTOptions:

const bttOptions = new BTTOptions()
bttOptions.launchTime = false

How to Test your React SDK

Site ID

Log onto your Blue Triangle Portal account, head over to "Native App" => "Performance Overview" and see that you can observe both native views and webviews as you expected.

Memory Warning

Android

Call the following function to generate a memory warning:

import {BTTTestsEmulator} from "@bluetriangle/react-native-btt-sdk"

function testMemoryWarning() {
BTTTestsEmulator.emulateMemoryWarning()
}

iOS

To test Memory Warning, In the iOS Simulator, you can generate a memory warning using the following steps:

  • Launch the Simulator

  • Go to XCode 'Debug' menu

  • Select 'Simulate Memory Warning' to generate memory warning

ANR Tracking

You can call the following function to generate an ANR. This function will block the native main thread for the duration of ANR

import {BTTTestsEmulator} from "@bluetriangle/react-native-btt-sdk"

function testANRTracking() {
BTTTestsEmulator.emulateANR()
}

Crash Tracking

To test Crash Tracking, you can declare and call the following function:

import {BTTTestsEmulator} from "@bluetriangle/react-native-btt-sdk"

function testCrashTracking() {
BTTTestsEmulator.emulateCrash()
}

Testing Warm Launch

In order to test Warm Launch, you need to enable the "Don't Keep Activities" setting. To enable the "Don't Keep Activities" option on an Android device, follow these steps:

1. Open Settings

Tap on the "Settings" icon on your device to open the Settings menu.

2. Go to Developer Options

  • If Developer Options are already enabled, you can skip to step 5.

  • If Developer Options are not enabled, follow these steps to enable it:

    1. Scroll down and tap on "About phone" (or "About device").

    2. Find "Build number" (you might need to tap on "Software information" first on some devices).

    3. Tap "Build number" multiple times (usually 7 times) until you see a message that says "You are now a developer!" or "Developer mode has been enabled".

    4. You may be prompted to enter your device's PIN or password.

3. Return to the Main Settings Menu

Once Developer Options are enabled, go back to the main Settings menu.

4. Open Developer Options

Scroll down and tap on "System" (or "System & updates" on some devices), then select "Developer options".

5. Enable Don't Keep Activities

  • Scroll down to find the "Don't keep activities" option.

  • Toggle the switch to enable it.

Important Notes

Enabling "Don't Keep Activities" forces the system to destroy every activity as soon as the user leaves it. This is useful for testing purposes to ensure that your app properly handles activity lifecycle transitions, but it might make the device behave differently than normal usage, leading to unexpected behavior in other apps.

Apps build using the React Native framework will not be able to use this method for testing warm launch. If the “Don’t keep activities” option is enabled on an app within this framework, it will cause a crash and not capture a warm launch.

Limitations/Known Issues

Tracking Navigation

If the app is using Navigation framework other than React Navigation, each screen need to be instrumented manually to track. In case of React Navigation, easy to use code snippets at one place instruments the whole app.

Crashes

Android- Crashes that happened due to JS errors are not tracked.

Release Notes

Version

Date

Notes

0.2.1

May 30, 2025

No-code support for integrated Clarity (session playback) experience. The SDK will automatically detect the presence of Clarity, request a playback URL, which would show in the performance details page. To read more about Blue Triangle's Clarity integration, please visit here.