Datadog SDK for React Native

repository·develop·Indexed 40 days ago

https://github.com/datadog/dd-sdk-reactnative

A client-side React Native module providing Real User Monitoring (RUM) capabilities to visualize and analyze real-time performance and user journeys. Includes support for @apollo/client GraphQL monitoring, CodePush integration via @datadog/mobile-react-native-code-push, and manual view tracking using DdRum.

Tokens
20.9K
Snippets
63
Records
82
Agent score
48%

What's inside Datadog

  1. Monitor web views with @datadog/mobile-react-native-webview

    develop

    Real User Monitoring (RUM) for web views allows you to eliminate blind spots in hybrid React Native applications. By using this package, you can track user journeys across both web and native components, identify whether latency is caused by web pages or native components, and better support users experiencing web loading issues.

    To enable this, you must have the Datadog RUM Browser SDK set up on the web pages being rendered within your mobile application.

  2. Understand Datadog SDK data storage behavior

    develop

    Before data is uploaded to Datadog, it is stored in cleartext in the application's cache directory.

    • Android: Data is stored in the application's cache directory, protected by the Android Application Sandbox. On rooted devices or compromised kernels, this data might be readable.
    • iOS: Data is stored in the application sandbox's cache directory (Library/Caches), which is inaccessible to other installed applications.
  3. Customize RUM view tracking with NavigationTrackingOptions

    develop

    The NavigationTrackingOptions object allows you to override default tracking behavior using three optional predicate functions:

    1. viewNamePredicate (ViewNamePredicate): Determines the name of the view sent to RUM.
      • Default: Forwards the view name directly to RUM.
    2. viewTrackingPredicate (ViewTrackingPredicate): Determines if a specific route should be tracked as a view.
      • Default: Tracks all views.
    3. paramsTrackingPredicate (ParamsTrackingPredicate): Determines which navigation parameters are forwarded to RUM. This is useful for filtering or masking sensitive data.
      • Default: Does not forward any parameters to RUM.
    import { Route } from "@react-navigation/native";
    import { 
      ViewNamePredicate, 
      ViewTrackingPredicate, 
      ParamsTrackingPredicate 
    } from '@datadog/mobile-react-navigation';
    
    // Custom view name
    const viewNamePredicate: ViewNamePredicate = (route: Route<string, any>, trackedName: string) => {
      return "My custom View Name";
    };
    
    // Filter views (e.g., ignore modals)
    const viewTrackingPredicate: ViewTrackingPredicate = (route: Route<string, any>) => {
      return route.name !== "AlertModal";
    };
    
    // Mask or filter parameters
    const paramsTrackingPredicate: ParamsTrackingPredicate = (route: Route<string, any>) => {
      const filteredParams: any = {};
      if (route.params?.username) {
        filteredParams["username"] = route.params.username;
      }
      // creditCardNumber is omitted or masked
      return filteredParams;
    };
  4. Attribute Encoding and Sanitization

    develop

    All attributes passed to Datadog SDK APIs are automatically sanitized and encoded:

    • Unsupported values (functions, symbols, non-finite numbers) are dropped with a warning.
    • Common types (Date, Error, Map) are properly serialized.
    • Nested objects are flattened using dot notation (e.g., a.b.c = value).
    • Root-level primitives and arrays are wrapped under a context key for schema consistency.
    • Custom Encoders: You can register custom encoders via the attributeEncoders option in CoreConfiguration for domain-specific types.
  5. Override the reported version in CodePush

    develop

    If you use datadog-ci react-native upload to upload your CodePush bundle and source maps with a version format that differs from the default, you can override the reported version in the SDK configuration object using one of the following keys:

    • versionSuffix (recommended): Adds a suffix to the commercial version of your app.
    • version: Completely overrides the reported version.
  6. Install @datadog/mobile-react-native-code-push

    develop

    This package provides integration for the react-native-code-push library. Before installing this package, you must have already installed and set up the core @datadog/mobile-react-native SDK.

    To install via NPM:

    npm install @datadog/mobile-react-native-code-push

    To install via Yarn:

    yarn add @datadog/mobile-react-native-code-push
    npm install @datadog/mobile-react-native-code-push
  7. Run or stop test scenarios via deep links

    develop

    You can control the benchmark app using deep links to trigger specific scenarios or stop the current one.

    Start a scenario

    Use the start method with scenario (from the Scenario enum) and runType (instrumented|baseline|profiling).

    iOS: xcrun simctl openurl booted "benchmark://start?scenario=navigation&runType=instrumented"

    Android: adb shell am start -W -a android.intent.action.VIEW -d 'benchmark://start?scenario=navigation\&runType=instrumented' com.benchmarkrunner

    Stop a scenario

    Use the stop method to halt the current scenario.

    iOS: xcrun simctl openurl booted "benchmark://stop"

    Android: adb shell am start -W -a android.intent.action.VIEW -d 'benchmark://stop' com.benchmarkrunner

    # iOS Start
    xcrun simctl openurl booted "benchmark://start?scenario=navigation&runType=instrumented"
    
    # Android Start
    adb shell am start -W -a android.intent.action.VIEW -d 'benchmark://start?scenario=navigation\&runType=instrumented' com.benchmarkrunner
    
    # iOS Stop
    xcrun simctl openurl booted "benchmark://stop"
    
    # Android Stop
    adb shell am start -W -a android.intent.action.VIEW -d 'benchmark://stop' com.benchmarkrunner
  8. Enable SVG Support for Session Replay

    develop

    To capture SVG images in your Session Replay recordings, you must configure the Datadog Babel and Metro plugins.

    1. Install the Babel Plugin

    npm install @datadog/mobile-react-native-babel-plugin
    # or
    yarn add @datadog/mobile-react-native-babel-plugin

    2. Configure Babel

    In your babel.config.js, add the @datadog/mobile-react-native-babel-plugin and set sessionReplay.svgTracking to true.

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

    3. Configure Metro

    In your metro.config.js, wrap your existing configuration with withSessionReplayAssetBundler from @datadog/mobile-react-native-session-replay/metro.

    // metro.config.js
    const { withSessionReplayAssetBundler } = require('@datadog/mobile-react-native-session-replay/metro');
    
    module.exports = withSessionReplayAssetBundler({
      /* your existing Metro config */
    });
  9. Install the Datadog React Native Babel Plugin

    develop

    The @datadog/mobile-react-native-babel-plugin enhances the Datadog React Native SDK by automatically enriching React components with contextual metadata, improving the accuracy of RUM Action tracking and Session Replay.

    Prerequisite: You must have already integrated the Datadog React Native SDK.

    # Using NPM
    npm install @datadog/mobile-react-native-babel-plugin
    
    # Using Yarn
    yarn add @datadog/mobile-react-native-babel-plugin
  10. Switch between New and Old Architecture in Benchmarks

    develop

    The Benchmark app uses React Native's New Architecture by default. To switch to the Old Architecture for performance comparison or bug reproduction, use the following methods:

    iOS

    Run pod install with the architecture flag disabled: RCT_NEW_ARCH_ENABLED=0 pod install

    Android

    Set newArchEnabled=false in benchmarks/android/gradle.properties.

    ```bash
    # iOS
    RCT_NEW_ARCH_ENABLED=0 pod install

    Android (in benchmarks/android/gradle.properties)

    newArchEnabled=false

  11. Initialize Datadog SDK and OpenFeature Provider

    develop

    You can initialize the Datadog SDK and set up the OpenFeature provider using either manual initialization or the <DatadogProvider /> component.

    Manual Initialization

    Use this approach if you are managing the lifecycle of DdSdkReactNative manually.

    Using <DatadogProvider />

    Use this approach to wrap your application and handle initialization via the onInitialized callback.

    Note: Sending flag evaluation data to Datadog is automatically enabled. You can configure this by passing rumIntegrationEnabled and trackExposures to the DdFlags.enable() call.

    import { CoreConfiguration, DatadogProvider, DdFlags } from '@datadog/mobile-react-native';
    import { DatadogOpenFeatureProvider } from '@datadog/mobile-react-native-openfeature';
    import { OpenFeature } from '@openfeature/react-sdk';
    
    // Example using <DatadogProvider />
    <DatadogProvider
        configuration={coreConfiguration}
        onInitialized={async () => {
            await DdFlags.enable();
    
            const provider = new DatadogOpenFeatureProvider();
            OpenFeature.setProvider(provider);
        }}
    >
        {/* ... */}
    </DatadogProvider>
  12. Migrate from 2.x to 3.0: Core SDK Initialization

    develop

    In SDK 3.0, the configuration structure has changed. Feature configuration is now split into feature-specific properties: rumConfiguration, logsConfiguration, and traceConfiguration.

    Mandatory Fields:

    • clientToken, environment, and trackingConsent are mandatory for Core SDK initialization.
    • applicationId is mandatory for RUM to work.

    Important Behavior Change: Unlike v2.x, v3 will not initialize or enable a feature module if no configuration is provided for it.

    const config = new CoreConfiguration(
        CLIENT_TOKEN,
        ENVIRONMENT,
        TrackingConsent.GRANTED,
        {
        rumConfiguration: {
            applicationId: APPLICATION_ID,
            trackInteractions: true,
            trackResources: true,
            trackFrustrations: true,
            sessionSampleRate: 100,
            telemetrySampleRate: 100
        }
        },
        logsConfiguration: {
            logEventMapper: (logEvent) => {
                logEvent.message = `[CUSTOM] ${logEvent.message}`;
                return logEvent;
            }
        },
        traceConfiguration: {}
    });
    
    await DdSdkReactNative.initialize(config);