Setup Method

Setup Method


Cette page décrit comment instrumenter vos applications pour le Suivi des utilisateurs réels (RUM) avec le SDK React Native. Le RUM inclut le suivi des erreurs par défaut, mais si vous avez acheté le suivi des erreurs en tant que produit autonome, consultez le guide de configuration du suivi des erreurs pour des étapes spécifiques.

La version minimale prise en charge pour le SDK React Native est React Native v0.65+. La compatibilité avec les versions antérieures n'est pas garantie par défaut.

Configuration

Install the SDK

To install with npm, run:

npm install @datadog/mobile-react-native

To install with Yarn, run:

yarn add @datadog/mobile-react-native

Install dependencies for iOS

Install the added pod:

(cd ios && pod install)

Install dependencies for Android

If you use a React Native version strictly over 0.67, make sure to use Java version 17. If you use React Native version equal or below 0.67, make sure to use Java version 11.

In your android/build.gradle file, specify the kotlinVersion to avoid clashes among kotlin dependencies:

buildscript {
    ext {
        // targetSdkVersion = ...
        kotlinVersion = "1.8.21"
    }
}

The minimum supported Android SDK version is API level 23. Make sure to set minSdkVersion to 23 (or higher) in your Android configuration.

The Datadog React Native SDK requires you to have compileSdkVersion = 31 or higher in the Android application setup, which implies that you should use Build Tools version 31 or higher, Android Gradle Plugin version 7, and Gradle version 7 or higher. To modify the versions, change the values in the buildscript.ext block of your application's top-level build.gradle file. Datadog recommends using a React Native version that's actively supported.

Specify application details in the UI

  1. In Datadog, navigate to Digital Experience > Add an Application.
  2. Choose react-native as the application type.
  3. Provide an application name to generate a unique Datadog application ID and client token.
  4. To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.

If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.

For data security, you must use a client token. If you used only Datadog API keys to configure the @datadog/mobile-react-native library, they would be exposed client-side in the React Native application's code.

For more information about setting up a client token, see the Client Token documentation.

Initialize the library with application context

import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from '@datadog/mobile-react-native';

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'US1',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from '@datadog/mobile-react-native';

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'US3',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from '@datadog/mobile-react-native';

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'EU1',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from '@datadog/mobile-react-native';

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'US1_FED',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard
import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from '@datadog/mobile-react-native';

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'US2_FED',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard

Sample session rates

To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the RUM React Native SDK as a percentage between 0 and 100. You can specify the rate with the config.sessionSamplingRate parameter.

To be compliant with the GDPR regulation, the React Native SDK requires the tracking consent value at initialization.

The trackingConsent setting can be one of the following values:

  1. .PENDING: The React Native SDK starts collecting and batching the data but does not send it to Datadog. The React Native SDK waits for the new tracking consent value to decide what to do with the batched data.
  2. .GRANTED: The React Native SDK starts collecting the data and sends it to Datadog.
  3. .NOTGRANTED: The React Native SDK does not collect any data. No logs, traces, or RUM events are sent to Datadog.

To change the tracking consent value after the React Native SDK is initialized, use the Datadog.set(trackingConsent:) API call. The React Native SDK changes its behavior according to the new value.

For example, if the current tracking consent is .PENDING:

  • If you change the value to .GRANTED, the React Native SDK sends all current and future data to Datadog;
  • If you change the value to .NOTGRANTED, the React Native SDK wipes all current data and does not collect future data.

User interactions tracking

The preferred way to set up interaction tracking is by using the Datadog React Native Babel Plugin (@datadog/mobile-react-native-babel-plugin). This plugin automatically enriches React components with contextual metadata, improving interaction tracking accuracy and enabling a range of configuration options.

Installation

To install with npm, run:

npm install @datadog/mobile-react-native-babel-plugin

To install with Yarn, run:

yarn add @datadog/mobile-react-native-babel-plugin

Configure Babel

Add the plugin to your Babel configuration file (babel.config.js, .babelrc, or similar):

module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: ['@datadog/mobile-react-native-babel-plugin']
};

After the plugin is installed and configured, it automatically tracks interactions on standard React Native components. No additional code changes are required for basic usage.

CodePush integration (optional)

If you're deploying updates with CodePush, see the CodePush setup documentation for additional configuration steps.

Install the SDK

The RUM React Native SDK supports Expo and Expo Go. To use it, install expo-datadog and @datadog/mobile-react-native.

expo-datadog supports Expo starting from SDK 45 and the plugin's versions follow Expo versions. For example, if you use Expo SDK 45, use expo-datadog version 45.x.x. Datadog recommends using Expo SDK 45 as a minimum version; previous versions may require manual steps.

To install with npm, run:

npm install expo-datadog @datadog/mobile-react-native

To install with Yarn, run:

yarn add expo-datadog @datadog/mobile-react-native

Specify application details in the UI

  1. In Datadog, navigate to Digital Experience > Add an Application.
  2. Choose react-native as the application type.
  3. Provide an application name to generate a unique Datadog application ID and client token.
  4. To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.

If you've purchased Error Tracking as a standalone product (without RUM), navigate to Error Tracking > Settings > Browser and Mobile > Add an Application instead.

For data security, you must use a client token. For more information about setting up a client token, see the Client Token documentation.

Initialize the library with application context

Add the following code snippet to your initialization file:

import {
    SdkVerbosity,
    DatadogProvider,
    DatadogProviderConfiguration,
    PropagatorType,
    TrackingConsent
} from 'expo-datadog';

const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>',
    '<ENVIRONMENT_NAME>',
    TrackingConsent.GRANTED,
    {
        // Optional: Configure the Datadog Site to target. Default is 'US1'.
        site: 'US1',
        // Optional: Set the reported service name (by default, it uses the package name or bundleIdentifier of your Android or iOS app respectively)
        service: 'com.example.reactnative',
        // Optional: Let the SDK print internal logs above or equal to the provided level. Default is undefined (meaning no logs)
        verbosity: SdkVerbosity.WARN,
        // Enable RUM
        rumConfiguration: {
            // Required: RUM Application ID
            applicationId: '<APPLICATION_ID>',
            // Track user interactions (set to false if using Error Tracking only)
            trackInteractions: true,
            // Track XHR resources (set to false if using Error Tracking only)
            trackResources: true,
            // Track errors
            trackErrors: true,
            // Optional: Sample sessions, for example: 80% of sessions are sent to Datadog. Default is 100%.
            sessionSampleRate: 80,
            // Optional: Enable or disable native crash reports.
            nativeCrashReportEnabled: true,
            // Optional: Sample tracing integrations for network calls between your app and your backend
            // (in this example, 80% of calls to your instrumented backend are linked from the RUM view to
            // the APM view. Default is 20%).
            // You need to specify the hosts of your backends to enable tracing with these backends
            resourceTraceSampleRate: 80,
            firstPartyHosts: [
                {
                    match: 'example.com',
                    propagatorTypes: [
                        PropagatorType.DATADOG,
                        PropagatorType.TRACECONTEXT
                    ]
                }
            ]
        },
        // Enable Logs with default configuration
        logsConfiguration: {},
        // Enable Trace with default configuration
        traceConfiguration: {}
    }
);

// Wrap the content of your App component in a DatadogProvider component, passing it your configuration:
export default function App() {
    return (
        <DatadogProvider configuration={config}>
            <Navigation />
        </DatadogProvider>
    );
}

// Once the Datadog React Native SDK for RUM is initialized, you need to setup view tracking to be able to see data in a dashboard

Sample session rates

To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions. To set this rate, use the config.sessionSamplingRate parameter and specify a percentage between 0 and 100.

Upload source maps on EAS builds

To enable crash reporting and error symbolication, add expo-datadog to your plugins in the app.json file:

{
    "expo": {
        "plugins": ["expo-datadog"]
    }
}

This plugin takes care of uploading the dSYMs, source maps and Proguard mapping files on every EAS build.

Add @datadog/datadog-ci as a development dependency. This package contains scripts to upload the source maps. You can install it with npm:

npm install @datadog/datadog-ci --save-dev

or with Yarn:

yarn add -D @datadog/datadog-ci

Run eas secret:create to set DATADOG_API_KEY to your Datadog API key, and DATADOG_SITE to the host of your Datadog site (for example, datadoghq.com).

User interactions tracking

Datadog recommends setting up interaction tracking by using the Datadog React Native Babel Plugin (@datadog/mobile-react-native-babel-plugin). This plugin automatically enriches React components with contextual metadata, improving interaction tracking accuracy and enabling a range of configuration options.

To install with npm, run:

npm install @datadog/mobile-react-native-babel-plugin

To install with Yarn, run:

yarn add @datadog/mobile-react-native-babel-plugin

Add the plugin to your Babel configuration file (babel.config.js, .babelrc, or similar):

module.exports = {
  presets: ["babel-preset-expo"],
  plugins: ['@datadog/mobile-react-native-babel-plugin']
};

After the plugin is installed and configured, it automatically tracks interactions on standard React Native components. No additional code changes are required for basic usage.

CodePush integration (optional)

If you're deploying updates with CodePush, see the CodePush setup documentation for additional configuration steps.

Envoi de données lorsque l'appareil est hors ligne

Le SDK React Native aide à rendre les données disponibles lorsque le dispositif de l'utilisateur est hors ligne. Dans les zones à faible réseau, ou lorsque la batterie de l'appareil est trop faible, tous les événements sont d'abord stockés sur l'appareil local par lots. Ils sont envoyés dès que le réseau est disponible et que la batterie est suffisamment chargée pour que le SDK React Native n'affecte pas l'expérience de l'utilisateur final. Si le réseau n'est pas disponible avec votre application en cours d'exécution au premier plan, ou si un téléchargement de données échoue, le lot est conservé jusqu'à ce qu'il puisse être envoyé avec succès.

Cela signifie que même si les utilisateurs ouvrent votre application en étant hors ligne, aucune donnée ne sera perdue.

Remarque : Les données sur le disque sont automatiquement supprimées si elles deviennent trop anciennes afin que le SDK React Native n'utilise pas trop d'espace disque.

Suivre les événements en arrière-plan

Le suivi des événements en arrière-plan peut entraîner des sessions supplémentaires, ce qui peut avoir un impact sur la facturation. Pour des questions, contactez le support Datadog.

Vous pouvez suivre des événements tels que des plantages et des requêtes réseau lorsque votre application est en arrière-plan (par exemple, lorsqu'aucune vue active n'est disponible).

Ajoutez l'extrait suivant lors de l'initialisation dans votre configuration Datadog :

rumConfiguration.trackBackgroundEvents = true;

Further reading