---
isPrivate: true
title: Client SDK Setup
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: Docs > Client SDKs > Client SDK Setup
---

# Client SDK Setup

## Overview{% #overview %}

Follow the instructions below to install and configure the Datadog SDK for your platform.

{% section displayed-if="SDK is Browser" %}
This section only applies to users who meet the following criteria: SDK is Browser

This page describes how to instrument your web applications with the Datadog Browser SDK. The Browser SDK supports [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/setup/client), [Error Tracking](https://docs.datadoghq.com/error_tracking/frontend/browser), [Session Replay](https://docs.datadoghq.com/session_replay/browser/), and [Product Analytics](https://docs.datadoghq.com/product_analytics/).

The Browser SDK supports all modern desktop and mobile browsers.

## Setup{% #setup %}

**Choose your setup method:**

- **[Server-side auto-instrumentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/setup/server)**: Automatically inject the RUM SDK into HTML responses through your web server or proxy.
- **[Agentic Onboarding (in Preview)](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/agentic_onboarding/?tab=realusermonitoring)**: Use AI coding agents (Cursor, Claude Code) to automatically instrument your application with one prompt.
- **Manual client-side setup** (below): Manually add the SDK to your application code.

### Step 1 - Create the application in the UI{% #step-1--create-the-application-in-the-ui %}

1. In Datadog, navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/list) and select the JavaScript (JS) application type.
1. Enter a name for your application, then click **Create Application**. This generates a `clientToken` and an `applicationId` for your application.

### Step 2 - Install the Browser SDK{% #step-2--install-the-browser-sdk %}

Choose the installation method for the Browser SDK.

{% tab title="NPM" %}
Installing through Node Package Manager (npm) registry is recommended for modern web applications. The Browser SDK is packaged with the rest of your frontend JavaScript code. It has no impact on page load performance. However, the SDK may miss errors, resources, and user actions triggered before the SDK is initialized. Datadog recommends using a matching version with the Browser Logs SDK.

Add [`@datadog/browser-rum`](https://www.npmjs.com/package/@datadog/browser-rum) to your `package.json` file, for example if you use npm cli:

```
npm install --save @datadog/browser-rum
```

{% /tab %}

{% tab title="CDN async" %}
Installing through CDN async is recommended for web applications with performance targets. The Browser SDK loads from Datadog's CDN asynchronously, ensuring the SDK download does not impact page load performance. However, the SDK may miss errors, resources, and user actions triggered before the SDK is initialized.

Add the generated code snippet to the head tag of every HTML page you want to monitor in your application.

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.eu

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/eu/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap1.datadoghq.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/ap1/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap2.datadoghq.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/ap2/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us3.datadoghq.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/us3/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us5.datadoghq.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/us5/v6/datadog-rum.js','DD_RUM')
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

```
<script>
  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/datadog-rum-v6.js','DD_RUM')
</script>
```

{% /callout %}

{% /tab %}

{% tab title="CDN sync" %}
Installing through CDN sync is recommended for collecting all events. The Browser SDK loads from Datadog's CDN synchronously, ensuring the SDK loads first and collects all errors, resources, and user actions. This method may impact page load performance.

Add the generated code snippet to the head tag (in front of any other script tags) of every HTML page you want to monitor in your application. Placing the script tag higher and loading it synchronously ensures Datadog RUM can collect all performance data and errors.

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.com

```
<script
    src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.eu

```
<script
    src="https://www.datadoghq-browser-agent.com/eu/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap1.datadoghq.com

```
<script
    src="https://www.datadoghq-browser-agent.com/ap1/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap2.datadoghq.com

```
<script
    src="https://www.datadoghq-browser-agent.com/ap2/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us3.datadoghq.com

```
<script
    src="https://www.datadoghq-browser-agent.com/us3/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us5.datadoghq.com

```
<script
    src="https://www.datadoghq-browser-agent.com/us5/v6/datadog-rum.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

```
<script
    src="https://www.datadoghq-browser-agent.com/datadog-rum-v6.js"
    type="text/javascript">
</script>
```

{% /callout %}

{% /tab %}

### Step 3 - Initialize the Browser SDK{% #step-3--initialize-the-browser-sdk %}

The SDK should be initialized as early as possible in the app lifecycle. This ensures all measurements are captured correctly.

In the initialization snippet, set an environment name, service name, and client token. See the full list of [initialization parameters](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html).

{% tab title="NPM" %}

```
import { datadogRum } from '@datadog/browser-rum';

datadogRum.init({
   applicationId: '<APP_ID>',
   clientToken: '<CLIENT_TOKEN>',
   // `site` refers to the Datadog site parameter of your organization
   // see https://docs.datadoghq.com/getting_started/site/
   site: '<DATADOG_SITE>',
  //  service: 'my-web-application',
  //  env: 'production',
  //  version: '1.0.0',
});

```

{% alert level="info" %}
Types are compatible with TypeScript >= 3.8.2. For earlier versions of TypeScript, import JavaScript sources and use global variables to avoid any compilation issues.
{% /alert %}

```
import '@datadog/browser-rum/bundle/datadog-rum'

window.DD_RUM.init({
  ...
})
```

{% /tab %}

{% tab title="CDN async" %}

```
<script>
  window.DD_RUM.onReady(function() {
    window.DD_RUM.init({
      clientToken: '<CLIENT_TOKEN>',
      applicationId: '<APP_ID>',
      // `site` refers to the Datadog site parameter of your organization
      // see https://docs.datadoghq.com/getting_started/site/
      site: '<DATADOG_SITE>',
      //  service: 'my-web-application',
      //  env: 'production',
      //  version: '1.0.0',
    });
  })
</script>
```

{% /tab %}

{% tab title="CDN sync" %}

```
<script>
    window.DD_RUM && window.DD_RUM.init({
      clientToken: '<CLIENT_TOKEN>',
      applicationId: '<APP_ID>',
      // `site` refers to the Datadog site parameter of your organization
      // see https://docs.datadoghq.com/getting_started/site/
      site: '<DATADOG_SITE>',
      //  service: 'my-web-application',
      //  env: 'production',
      //  version: '1.0.0',

    });
</script>
```

{% /tab %}

#### Configure tracking consent (GDPR compliance){% #configure-tracking-consent--gdpr-compliance %}

To be compliant with GDPR, CCPA, and similar regulations, the Browser SDK lets you provide the [tracking consent value at initialization](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser).

#### Configure Content Security Policy (CSP){% #configure-content-security-policy--csp %}

If you're using the Datadog Content Security Policy (CSP) integration on your site, see [the CSP documentation](https://docs.datadoghq.com/integrations/content_security_policy_logs/) for additional setup steps.
{% /section %}

{% section displayed-if="SDK is Android" %}
This section only applies to users who meet the following criteria: SDK is Android

This page describes how to instrument your applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the Android SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/frontend/mobile/android) for specific steps.

The Datadog Android SDK supports Android 6.0+ (API level 23) and Android TV.

## Setup{% #setup-2 %}

**Choose your setup method:**

- **[Agentic Onboarding (in Preview)](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/agentic_onboarding/?tab=realusermonitoring)**: Use AI coding agents (Cursor, Claude Code) to automatically instrument your application with one prompt. The agent detects your project structure and configures the RUM SDK for you.
- **Manual setup** (below): Follow the step-by-step instructions to manually add and configure the SDK.

### Step 1 - Declare the Android SDK as a dependency{% #step-1--declare-the-android-sdk-as-a-dependency %}

Declare [dd-sdk-android-rum](https://github.com/DataDog/dd-sdk-android/tree/develop/features/dd-sdk-android-rum) and the [Gradle plugin](https://github.com/DataDog/dd-sdk-android-gradle-plugin) as dependencies in your **application module's** `build.gradle` file.

```
buildscript {
    dependencies {
        classpath("com.datadoghq:dd-sdk-android-gradle-plugin:x.x.x")
    }
}
plugins {
    id("com.datadoghq.dd-sdk-android-gradle-plugin")
    //(...)
}
android {
    //(...)
}
dependencies {
    implementation "com.datadoghq:dd-sdk-android-rum:x.x.x"
    //(...)
}

```

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui %}

1. Navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/list).
1. Select `android` as the application type and enter an application name to generate a unique Datadog application ID and client token.
1. To instrument your web views, click the **Instrument your webviews** toggle. For more information, see [Web View Tracking](https://docs.datadoghq.com/real_user_monitoring/android/web_view_tracking/).
1. To disable automatic user data collection for either client IP or geolocation data, use the toggles for those settings. For more information, see [RUM Android Data Collected](https://docs.datadoghq.com/real_user_monitoring/android/data_collected/).

{% image
   source="https://datadog-docs.imgix.net/images/real_user_monitoring/android/android-new-application.fe329bfc1c6e54126fcc8822dff1d2f0.png?auto=format"
   alt="Create a RUM application for Android in Datadog" /%}

For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 3 - Initialize the Datadog SDK with application context{% #step-3--initialize-the-datadog-sdk-with-application-context %}

#### Update the initialization snippet{% #update-the-initialization-snippet %}

In the initialization snippet, set an environment name, service name, and version number. In the examples below, `APP_VARIANT_NAME` specifies the variant of the application that generates data. For more information, see [Using Tags](https://docs.datadoghq.com/getting_started/tagging/using_tags/#rum--session-replay).

During initialization, you can also set the sample rate (RUM sessions) and set the tracking consent for GDPR compliance, as described below. See [other configuration options](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#initialization-parameters) to initialize the library.

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
            clientToken = "<CLIENT_TOKEN>",
            env = "<ENV_NAME>",
            variant = "<APP_VARIANT_NAME>"
        ).build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.eu

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.EU1)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.EU1)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us3.datadoghq.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.US3)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.US3)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us5.datadoghq.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.US5)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.US5)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.US1_FED)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.US1_FED)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap1.datadoghq.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.AP1)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.AP1)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap2.datadoghq.com

{% tab title="Kotlin" %}

```
class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val configuration = Configuration.Builder(
                clientToken = "<CLIENT_TOKEN>",
                env = "<ENV_NAME>",
                variant = "<APP_VARIANT_NAME>"
            )
            .useSite(DatadogSite.AP2)
            .build()

        Datadog.initialize(this, configuration, trackingConsent)
    }
}
```

{% /tab %}

{% tab title="Java" %}

```
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Configuration configuration =
                new Configuration.Builder("<CLIENT_TOKEN>", "<ENV_NAME>", "<APP_VARIANT_NAME>")
                        .useSite(DatadogSite.AP2)
                        .build();

        Datadog.initialize(this, configuration, trackingConsent);
    }
}
```

{% /tab %}

{% /callout %}

The initialization credentials require your application's variant name and use the value of `BuildConfig.FLAVOR`. With the variant, the SDK can match the errors reported from your application to the mapping files uploaded by the Gradle plugin. If you do not have variants, the credentials use an empty string.

The Gradle plugin automatically uploads the appropriate ProGuard `mapping.txt` file at build time so you can view deobfuscated error stack traces. For more information, see the [Track Android Errors](https://docs.datadoghq.com/real_user_monitoring/error_tracking/android/#upload-your-mapping-file).

#### Sample session rates{% #sample-session-rates %}

To control the data your application sends to Datadog, you can specify a sample rate for sessions when [initializing RUM](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#initialization-parameters). The sample rate is a percentage between 0 and 100. By default, `sessionSamplingRate` is set to 100 (keep all sessions).

```
val rumConfig = RumConfiguration.Builder(applicationId)
        // Here 75% of the RUM sessions are sent to Datadog
        .setSessionSampleRate(75.0f)
        .build()
Rum.enable(rumConfig)
```

#### Set tracking consent (GDPR compliance){% #set-tracking-consent--gdpr-compliance %}

To be compliant with the GDPR regulation, the SDK requires the tracking consent value upon initialization.

Tracking consent can be one of the following values:

- `TrackingConsent.PENDING`: (Default) The SDK starts collecting and batching the data but does not send it to the collection endpoint. The SDK waits for the new tracking consent value to decide what to do with the batched data.
- `TrackingConsent.GRANTED`: The SDK starts collecting the data and sends it to the data collection endpoint.
- `TrackingConsent.NOT_GRANTED`: The SDK does not collect any data. You are not able to manually send any logs, traces, or events.

To **update the tracking consent** after the SDK is initialized, call `Datadog.setTrackingConsent(<NEW CONSENT>)`. The SDK changes its behavior according to the new consent. For example, if the current tracking consent is `TrackingConsent.PENDING` and you update it to:

- `TrackingConsent.GRANTED`: The SDK sends all current batched data and future data directly to the data collection endpoint.
- `TrackingConsent.NOT_GRANTED`: The SDK wipes all batched data and does not collect any future data.

### Step 4 - Enable the feature to start sending data{% #step-4--enable-the-feature-to-start-sending-data %}

To enable the Android SDK to start sending data:

{% tab title="Kotlin" %}

```
val rumConfig = RumConfiguration.Builder(applicationId)
    .trackInteractions()
    .trackLongTasks(durationThreshold) // Not applicable to Error Tracking
    .useViewTrackingStrategy(strategy)
    .build()
Rum.enable(rumConfig)
```

{% /tab %}

{% tab title="Java" %}

```
RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
    .trackInteractions()
    .trackLongTasks(durationThreshold) // Not applicable to Error Tracking
    .useViewTrackingStrategy(strategy)
    .build();
Rum.enable(rumConfig);
```

{% /tab %}

See [`ViewTrackingStrategy`](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#automatically-track-views) to enable automatic tracking of all your views (activities, fragments, and more).

### Step 5 - Initialize the interceptor to track network events{% #step-5--initialize-the-interceptor-to-track-network-events %}

To initialize an interceptor for tracking network events:

1. For distributed tracing, [add and enable the Trace feature](https://docs.datadoghq.com/tracing/trace_collection/dd_libraries/android/).
1. Add the Gradle dependency to the `dd-sdk-android-okhttp` library in the module-level `build.gradle` file:

```
dependencies {
    implementation "com.datadoghq:dd-sdk-android-okhttp:x.x.x"
}
```
To track your OkHttp requests as resources, add the provided [interceptor](https://square.github.io/okhttp/features/interceptors/):
{% tab title="Kotlin" %}

```
val tracedHostsWithHeaderType = mapOf(
    "example.com" to setOf(
        TracingHeaderType.DATADOG,
        TracingHeaderType.TRACECONTEXT),
    "example.eu" to setOf(
        TracingHeaderType.DATADOG,
        TracingHeaderType.TRACECONTEXT))
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
    .build()
```

{% /tab %}

{% tab title="Java" %}

```
Map<String, Set<TracingHeaderType>> tracedHostsWithHeaderType = new HashMap<>();
Set<TracingHeaderType> datadogAndW3HeadersTypes = new HashSet<>(Arrays.asList(TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT));
tracedHostsWithHeaderType.put("example.com", datadogAndW3HeadersTypes);
tracedHostsWithHeaderType.put("example.eu", datadogAndW3HeadersTypes);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
    .build();
```

{% /tab %}

To automatically create RUM resources and spans for your OkHttp requests, use the `DatadogInterceptor` as an interceptor.

- This records each request processed by the `OkHttpClient` as a resource, with all the relevant information (URL, method, status code, and error) automatically filled in. Only the network requests that started when a view is active are tracked. To track requests when your application is in the background, [create a view manually](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#automatically-track-views).

To monitor the network redirects or retries, you can use the `DatadogInterceptor` as a [network interceptor](https://square.github.io/okhttp/features/interceptors/#network-interceptors):

{% tab title="Kotlin" %}

```
val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
    .build()
```

{% /tab %}

{% tab title="Java" %}

```
OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addNetworkInterceptor(new DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
    .build();
```

{% /tab %}

**Notes**:

- To use spans but not RUM resources, you can use the `TracingInterceptor` instead of `DatadogInterceptor` as described above.
- If you use multiple interceptors, add `DatadogInterceptor` first.

You can also add an `EventListener` for the `OkHttpClient` to [automatically track resource timing](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#automatically-track-network-requests) for third-party providers and network requests.

#### Cronet{% #cronet %}

If you use Cronet instead of OkHttp, you can instrument your `CronetEngine` for RUM resource tracking and distributed tracing.

1. Add the Gradle dependencies in the module-level `build.gradle` file:

   ```
   dependencies {
       implementation "com.datadoghq:dd-sdk-android-cronet:x.x.x"
   }
   ```

1. Instrument the `CronetEngine.Builder`:

   {% tab title="Kotlin" %}

   ```
   val tracedHostsWithHeaderType = mapOf(
       "example.com" to setOf(
           TracingHeaderType.DATADOG,
           TracingHeaderType.TRACECONTEXT),
       "example.eu" to setOf(
           TracingHeaderType.DATADOG,
           TracingHeaderType.TRACECONTEXT))
   val cronetEngine = CronetEngine.Builder(context)
       .configureDatadogInstrumentation(
           rumInstrumentationConfiguration = RumNetworkInstrumentationConfiguration(),
           apmInstrumentationConfiguration = ApmNetworkInstrumentationConfiguration(
               tracedHostsWithHeaderType
           )
       )
       .build()
   ```

   {% /tab %}

   {% tab title="Java" %}

   ```
   Map<String, Set<TracingHeaderType>> tracedHostsWithHeaderType = new HashMap<>();
   Set<TracingHeaderType> headerTypes = new HashSet<>(Arrays.asList(
       TracingHeaderType.DATADOG, TracingHeaderType.TRACECONTEXT));
   tracedHostsWithHeaderType.put("example.com", headerTypes);
   tracedHostsWithHeaderType.put("example.eu", headerTypes);
   CronetEngine.Builder builder = new CronetEngine.Builder(context);
   CronetEngine cronetEngine = CronetIntegrationPluginKt
       .configureDatadogInstrumentation(
           builder,
           new RumNetworkInstrumentationConfiguration(),
           new ApmNetworkInstrumentationConfiguration(tracedHostsWithHeaderType)
       )
       .build();
   ```

   {% /tab %}

**Known limitations**:

- Tracing headers are not propagated for redirected requests due to Cronet API limitations.
- Retries cannot be instrumented.

To filter out specific errors reported by `DatadogInterceptor`, you can configure a custom `EventMapper` in your `RumConfiguration`:

{% tab title="Kotlin" %}

```
val rumConfig = RumConfiguration.Builder(applicationId)
    .setErrorEventMapper { errorEvent ->
        if (errorEvent.shouldBeDiscarded()) {
            null
        } else {
            errorEvent
        }
    }
    .build();
```

{% /tab %}

{% tab title="Java" %}

```
RumConfiguration rumConfig = new RumConfiguration.Builder("applicationId")
             .setErrorEventMapper(errorEvent -> {
                 if (errorEvent.shouldBeDiscarded()) {
                     return null;
                 } else {
                     return errorEvent;
                 }
             })
             .build();

```

{% /tab %}

## Track background events{% #track-background-events %}

You can track events such as crashes and network requests when your application is in the background (for example, no active view is available).

Add the following snippet during configuration:

{% tab title="Kotlin" %}

```
val rumConfig = RumConfiguration.Builder(applicationId)
  // …
  .trackBackgroundEvents(true)
```

{% /tab %}

{% tab title="Java" %}

```
RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
  // …
  .trackBackgroundEvents(true)
```

{% /tab %}

{% alert level="info" %}
Tracking background events may lead to additional sessions, which can impact billing. For questions, [contact Datadog support](https://docs.datadoghq.com/help/).
{% /alert %}

## Sending data when device is offline{% #sending-data-when-device-is-offline %}

The Android SDK helps ensure availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches.

Each batch follows the intake specification. Batches are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.

## Kotlin extensions{% #kotlin-extensions %}

### `Closeable` extension

You can monitor `Closeable` instance usage with the `useMonitored` method, which reports errors to Datadog and closes the resource afterwards.

```
val closeable: Closeable = ...
closeable.useMonitored {
    // Your code here
}
```

### Track local assets as resources{% #track-local-assets-as-resources %}

You can track access to the assets by using `getAssetAsRumResource` extension method:

```
val inputStream = context.getAssetAsRumResource(fileName)
```

Usage of the local resources can be tracked by using `getRawResAsRumResource` extension method:

```
val inputStream = context.getRawResAsRumResource(id)
```

## Start monitoring{% #start-monitoring %}

Visualize the [data collected](https://docs.datadoghq.com/real_user_monitoring/android/data_collected/) in [dashboards](https://docs.datadoghq.com/real_user_monitoring/platform/dashboards/) or create a search query in the [RUM Explorer](https://app.datadoghq.com/rum/list).

Your application appears as pending on the Applications page until Datadog starts receiving data.

## Next steps{% #next-steps %}

See [Advanced Configuration](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/android/advanced_configuration/#initialization-parameters).
{% /section %}

{% section displayed-if="SDK is iOS" %}
This section only applies to users who meet the following criteria: SDK is iOS

This page describes how to instrument your iOS and tvOS applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the iOS SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/) for specific steps.

## Prerequisites{% #prerequisites %}

Before you begin, ensure you have:

- Xcode 12.0 or later
- iOS 11.0+ or tvOS 11.0+ deployment target
- A Datadog account with RUM or Error Tracking enabled

## Setup{% #setup-3 %}

**Choose your setup method:**

- **[Agentic Onboarding (in Preview)](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/agentic_onboarding/?tab=realusermonitoring)**: Use AI coding agents (Cursor, Claude Code) to automatically instrument your iOS application with one prompt. The agent detects your project structure and configures the RUM SDK for you.
- **Manual setup** (below): Follow the instructions to manually add and configure the RUM SDK in your iOS application.

### Manual setup{% #manual-setup %}

To send RUM data from your iOS or tvOS application to Datadog, complete the following steps.

### Step 1 - Add the iOS SDK as a dependency{% #step-1--add-the-ios-sdk-as-a-dependency %}

Add the iOS SDK to your project using your preferred package manager. Datadog recommends using Swift Package Manager (SPM).

{% tab title="Swift Package Manager (SPM)" %}
To integrate using Apple's Swift Package Manager, add the following as a dependency to your `Package.swift`:

```
.package(url: "https://github.com/Datadog/dd-sdk-ios.git", .upToNextMajor(from: "3.0.0"))
```

In your project, link the following libraries:

```
DatadogCore
DatadogRUM
```

{% /tab %}

{% tab title="CocoaPods" %}
You can use [CocoaPods](https://cocoapods.org/) to install `dd-sdk-ios`:

```
pod 'DatadogCore'
pod 'DatadogRUM'
```

{% /tab %}

{% tab title="Carthage" %}
You can use [Carthage](https://github.com/Carthage/Carthage) to install `dd-sdk-ios`:

```
github "DataDog/dd-sdk-ios"
```

{% alert level="info" %}
Datadog does not provide prebuilt Carthage binaries. This means Carthage builds the SDK from source.
{% /alert %}

To build and integrate the SDK, run:

```
carthage bootstrap --use-xcframeworks --no-use-binaries
```

After building, add the following XCFrameworks to your Xcode project (in the "Frameworks, Libraries, and Embedded Content" section):

```
DatadogInternal.xcframework
DatadogCore.xcframework
DatadogRUM.xcframework
```

{% /tab %}

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui-2 %}

1. Navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Select `iOS` as the application type and enter an application name to generate a unique Datadog application ID and client token.
1. To instrument your web views, click the **Instrument your webviews** toggle. For more information, see [Web View Tracking](https://docs.datadoghq.com/real_user_monitoring/ios/web_view_tracking/).

### Step 3 - Initialize the library{% #step-3--initialize-the-library %}

In the initialization snippet, set an environment name, service name, and client token.

The SDK should be initialized as early as possible in the app lifecycle, specifically in the `AppDelegate`'s `application(_:didFinishLaunchingWithOptions:)` callback. The `AppDelegate` is your app's main entry point that handles app lifecycle events.

This ensures the SDK can correctly capture all measurements, including application startup duration. For apps built with SwiftUI, you can use `@UIApplicationDelegateAdaptor` to hook into the `AppDelegate`.

{% alert level="warning" %}
Initializing the SDK elsewhere (for example later during view loading) may result in inaccurate or missing telemetry, especially around app startup performance.
{% /alert %}

For more information, see [Using Tags](https://docs.datadoghq.com/getting_started/tagging/using_tags/#rum--session-replay).

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.com

{% tab title="Swift" %}

```
import DatadogCore

// Initialize Datadog SDK with your configuration
Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",  // From Datadog UI
    env: "<environment>",             // for example, "production", "staging"
    service: "<service name>"        // Your app's service name
  ),
  trackingConsent: trackingConsent  // GDPR compliance setting
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

// Initialize Datadog SDK with your configuration
DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";  // Your app's service name

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];  // GDPR compliance setting
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.eu

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .eu1,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite eu1];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us3.datadoghq.com

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .us3,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us3];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us5.datadoghq.com

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .us5,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us5];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .us1_fed,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite us1_fed];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap1.datadoghq.com

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .ap1,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite ap1];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: ap2.datadoghq.com

{% tab title="Swift" %}

```
import DatadogCore

Datadog.initialize(
  with: Datadog.Configuration(
    clientToken: "<client token>",
    env: "<environment>",
    site: .ap2,
    service: "<service name>"
  ),
  trackingConsent: trackingConsent
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogCore;

DDConfiguration *configuration = [[DDConfiguration alloc] initWithClientToken:@"<client token>" env:@"<environment>"];
configuration.service = @"<service name>";
configuration.site = [DDSite ap2];

[DDDatadog initializeWithConfiguration:configuration
                       trackingConsent:trackingConsent];
```

{% /tab %}

{% /callout %}

The iOS SDK automatically tracks user sessions based on the options you provide during SDK initialization. To add GDPR compliance for your EU users (required for apps targeting European users) and configure other [initialization parameters](https://docs.datadoghq.com/real_user_monitoring/ios/advanced_configuration/#initialization-parameters), see the Set tracking consent documentation.

#### Sample session rates{% #sample-session-rates-2 %}

To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while [initializing the RUM iOS SDK](https://github.com/DataDog/dd-sdk-ios). The rate is a percentage between 0 and 100. By default, `sessionSamplingRate` is set to 100 (keep all sessions).

For example, to only keep 50% of sessions use:

{% tab title="Swift" %}

```
// Configure RUM with 50% session sampling
let configuration = RUM.Configuration(
    applicationID: "<rum application id>",
    sessionSampleRate: 50  // Only track 50% of user sessions
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
// Configure RUM with 50% session sampling
DDRUMConfiguration *configuration = [[DDRUMConfiguration alloc] initWithApplicationID:@"<rum application id>"];
configuration.sessionSampleRate = 50;  // Only track 50% of user sessions
```

{% /tab %}

#### Set tracking consent (GDPR compliance){% #set-tracking-consent--gdpr-compliance-2 %}

To be compliant with the GDPR regulation (required for apps targeting European users), the iOS SDK requires the tracking consent value at initialization.

The `trackingConsent` setting can be one of the following values:

1. `.pending`: The iOS SDK starts collecting and batching the data but does not send it to Datadog. The iOS SDK waits for the new tracking consent value to decide what to do with the batched data.
1. `.granted`: The iOS SDK starts collecting the data and sends it to Datadog.
1. `.notGranted`: The iOS SDK does not collect any data. No logs, traces, or events are sent to Datadog.

To **change the tracking consent value** after the iOS SDK is initialized, use the `Datadog.set(trackingConsent:)` API call. The iOS 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 RUM iOS SDK sends all current and future data to Datadog;
- If you change the value to `.notGranted`, the RUM iOS SDK wipes all current data and does not collect future data.

### Step 4 - Start sending data{% #step-4--start-sending-data %}

#### Enable RUM{% #enable-rum %}

Configure and start RUM. This should be done once and as early as possible, specifically in your `AppDelegate`:

{% tab title="Swift" %}

```
import DatadogRUM

RUM.enable(
  with: RUM.Configuration(
    applicationID: "<rum application id>",
    uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(),
    uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(),
    swiftUIViewsPredicate: DefaultSwiftUIRUMViewsPredicate(),
    swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate(isLegacyDetectionEnabled: true),
    urlSessionTracking: RUM.Configuration.URLSessionTracking()
  )
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
@import DatadogRUM;

DDRUMConfiguration *configuration = [[DDRUMConfiguration alloc] initWithApplicationID:@"<rum application id>"];
configuration.uiKitViewsPredicate = [DDDefaultUIKitRUMViewsPredicate new];
configuration.uiKitActionsPredicate = [DDDefaultUIKitRUMActionsPredicate new];
configuration.swiftUIViewsPredicate = [DDDefaultSwiftUIRUMViewsPredicate new];
configuration.swiftUIActionsPredicate = [[DDDefaultSwiftUIRUMActionsPredicate alloc] initWithIsLegacyDetectionEnabled:YES];
[configuration setURLSessionTracking:[DDRUMURLSessionTracking new]];

[DDRUM enableWith:configuration];
```

{% /tab %}

#### Enable `URLSessionInstrumentation`{% #enable- %}

To monitor requests sent from the `URLSession` instance as resources, enable `URLSessionInstrumentation` for your delegate type and pass the delegate instance to the `URLSession`:

{% tab title="Swift" %}

```
URLSessionInstrumentation.enable(
    with: .init(
        delegateClass: <YourSessionDelegate>.self
    )
)

let session = URLSession(
    configuration: .default,
    delegate: <YourSessionDelegate>(),
    delegateQueue: nil
)
```

{% /tab %}

{% tab title="Objective-C" %}

```
DDURLSessionInstrumentationConfiguration *config = [[DDURLSessionInstrumentationConfiguration alloc] initWithDelegateClass:[<YourSessionDelegate> class]];
[DDURLSessionInstrumentation enableWithConfiguration:config];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                      delegate:[[<YourSessionDelegate> alloc] init]
                                                 delegateQueue:nil];
```

{% /tab %}

### Instrument views{% #instrument-views %}

The Datadog iOS SDK allows you to instrument views of `SwiftUI` applications. The instrumentation also works with hybrid `UIKit` and `SwiftUI` applications.

To instrument a `SwiftUI.View`, add the following method to your view declaration:

```
import SwiftUI
import DatadogRUM

struct FooView: View {

    var body: some View {
        FooContent {
            ...
        }
        .trackRUMView(name: "Foo")
    }
}
```

The `trackRUMView(name:)` method starts and stops a view when the `SwiftUI` view appears and disappears from the screen.

### Instrument tap actions{% #instrument-tap-actions %}

The Datadog iOS SDK allows you to instrument tap actions of `SwiftUI` applications. The instrumentation also works with hybrid `UIKit` and `SwiftUI` applications.

{% alert level="warning" %}
Using `.trackRUMTapAction(name:)` for `SwiftUI` controls inside a `List` can break its default gestures. For example, it may disable the `Button` action or break `NavigationLink`. To track taps in a `List` element, use the [Custom Actions](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/ios/advanced_configuration#custom-actions) API instead.
{% /alert %}

To instrument a tap action on a `SwiftUI.View`, add the following method to your view declaration:

```
import SwiftUI
import DatadogRUM

struct BarView: View {

    var body: some View {
        Button("BarButton") {
            // Your button action here
        }
        .trackRUMTapAction(name: "Bar")
    }
}
```

## Track iOS errors{% #track-ios-errors %}

[iOS Crash Reporting and Error Tracking](https://docs.datadoghq.com/error_tracking/frontend/mobile/ios) displays any issues in your application and the latest available errors. You can view error details and attributes including JSON in the [RUM Explorer](https://docs.datadoghq.com/real_user_monitoring/explorer/).

## Disable automatic user data collection{% #disable-automatic-user-data-collection %}

You may want to disable automatic collection of user data to comply with privacy regulations or organizational data governance policies.

To disable automatic user data collection for client IP or geolocation data:

1. After creating your application, go to the [Application Management](https://app.datadoghq.com/rum/application/) page and click your application.
1. Click **User Data Collection**.
1. Use the toggles for those settings. For more information, see [RUM iOS Data Collected](https://docs.datadoghq.com/real_user_monitoring/ios/data_collected/).

To ensure the safety of your data, you must use a client token. Using only [Datadog API keys](https://cocoapods.org/) to configure the `dd-sdk-ios` library would expose them client-side in your iOS application's byte code.

For more information about setting up a client token, see the [Client token documentation](https://github.com/Carthage/Carthage).

## Sending data when device is offline{% #sending-data-when-device-is-offline-2 %}

The iOS SDK ensures availability of data when your user device is offline. In cases of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches. They are sent as soon as the network is available, and the battery is high enough to ensure the iOS SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost.

**Note**: The data on the disk is automatically discarded if it gets too old to ensure the iOS SDK does not use too much disk space.

## Supported versions{% #supported-versions %}

See [Supported versions](https://docs.datadoghq.com/real_user_monitoring/mobile_and_tv_monitoring/supported_versions/ios/) for a list of operating system versions and platforms that are compatible with the iOS SDK.
{% /section %}

{% section displayed-if="SDK is Flutter" %}
This section only applies to users who meet the following criteria: SDK is Flutter

This page describes how to instrument your applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the Flutter SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/frontend/mobile/flutter/) for specific steps.

## Setup{% #setup-4 %}

### Step 1 - Specify application details in the UI{% #step-1--specify-application-details-in-the-ui %}

1. In Datadog, navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Choose `Flutter` as the application type.
1. Provide an application name to generate a unique Datadog application ID and client token.

To secure your data, you must use a client token. For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 2 - Instrument your application{% #step-2--instrument-your-application %}

First, make sure you have your environment set up properly for each platform.

{% alert level="info" %}
Datadog supports Flutter Monitoring for iOS, Android, and Web for Flutter 3.27+.
{% /alert %}

Datadog supports Flutter Web starting with v3 of the SDK, with a few known limitations.

- Long running actions (`startAction` and `stopAction`) are not supported
- Actions (`addAction`) and manually reported Resources (`startResource` and `stopResource`) do not properly associate with Errors or Actions.
- Event mappers are not supported.

#### iOS{% #ios %}

The Datadog SDK for Flutter supports integration with both Cocoapods and Swift Package Manager (SPM).

If you are using Cocoapods, your iOS Podfile, located in `ios/Podfile`, must have `use_frameworks!` set to true (which is the default in Flutter) and must set its target iOS version >= 12.0.

This constraint is usually commented out on the top line of the Podfile, and should read:

```
platform :ios, '12.0'
```

You can replace `12.0` with any minimum version of iOS you want to support that is 12.0 or higher.

#### Android{% #android %}

For Android, your `minSdkVersion` version must be >= 23, and your `compileSdkVersion` must be >= 35. Clients using Flutter after 3.27 usually have these variables set to Flutter constants (`flutter.minSdkVersion` and `flutter.compileSdkVersion`), and they do not have to be manually changed.

If you are using Kotlin, it should be a version >= 2.1.0. Flutter versions above 3.27 emit a warning stating that older versions of Kotlin are not supported, and provide instructions for updating.

These constraints are usually held in your `android/app/build.gradle` file, or in your `android/gradle.properties` file.

#### Web{% #web %}

For Web, add the following to your `index.html` under the `head` tag:

```
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/"></script>
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/"></script>
```

This loads the CDN-delivered Datadog Browser SDKs for Logs and RUM. The synchronous CDN-delivered version of the Browser SDK is the only version supported by the Datadog Flutter Plugin.

#### Add the plugin{% #add-the-plugin %}

1. Add the following to your `pubspec.yaml` file:

```
dependencies:
  datadog_flutter_plugin: ^3.0.0
```
Create a configuration object for each Datadog feature (such as Logs or RUM) with the following snippet. If you do not pass a configuration for a given feature, that feature is disabled.
```
// Determine the user's consent to be tracked
final trackingConsent = ...
final configuration = DatadogConfiguration(
  clientToken: '<CLIENT_TOKEN>',
  env: '<ENV_NAME>',
  site: DatadogSite.us1,
  nativeCrashReportEnabled: true,
  loggingConfiguration: DatadogLoggingConfiguration(),
  rumConfiguration: DatadogRumConfiguration(
    applicationId: '<RUM_APPLICATION_ID>',
  )
);
```

For more information on available configuration options, see the [DatadogConfiguration object documentation](https://pub.dev/documentation/datadog_flutter_plugin/latest/datadog_flutter_plugin/DatadogConfiguration-class.html).

To secure data, you must use a client token. You cannot use Datadog API keys to configure the Datadog [Flutter Plugin](https://pub.dev/documentation/datadog_flutter_plugin/latest/datadog_flutter_plugin/ViewInfoExtractor.html).

- If you are using RUM, set up a **Client Token** and **Application ID**.
- If you are only using Logs, initialize the library with a client token.

### Step 3 - Initialize the library{% #step-3--initialize-the-library-2 %}

You can initialize the library using one of two methods in your `main.dart` file.

- Use `DatadogSdk.runApp` to automatically set up [Error Tracking](https://docs.datadoghq.com/real_user_monitoring/error_tracking/flutter).

```
await DatadogSdk.runApp(configuration, TrackingConsent.granted, () async {
  runApp(const MyApp());
})
```

- You can also manually set up [Error Tracking](https://docs.datadoghq.com/real_user_monitoring/error_tracking/flutter). `DatadogSdk.runApp` calls `WidgetsFlutterBinding.ensureInitialized`, so if you are not using `DatadogSdk.runApp`, you need to call this method prior to calling `DatadogSdk.instance.initialize`.

```
WidgetsFlutterBinding.ensureInitialized();
final originalOnError = FlutterError.onError;
FlutterError.onError = (details) {
  DatadogSdk.instance.rum?.handleFlutterError(details);
  originalOnError?.call(details);
};
final platformOriginalOnError = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (e, st) {
  DatadogSdk.instance.rum?.addErrorInfo(
    e.toString(),
    RumErrorSource.source,
    stackTrace: st,
  );
  return platformOriginalOnError?.call(e, st) ?? false;
};
await DatadogSdk.instance.initialize(configuration, TrackingConsent.granted);
runApp(const MyApp());
```

#### Sample session rates{% #sample-session-rates-3 %}

To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while initializing the Flutter RUM SDK. The rate is a percentage between 0 and 100. By default, `sessionSamplingRate` is set to 100 (keep all sessions).

For example, to keep only 50% of sessions, use:

```
final config = DatadogConfiguration(
    // other configuration...
    rumConfiguration: DatadogRumConfiguration(
        applicationId: '<YOUR_APPLICATION_ID>',
        sessionSamplingRate: 50.0,
    ),
);
```

#### Set tracking consent (GDPR compliance){% #set-tracking-consent--gdpr-compliance-3 %}

To be compliant with the GDPR regulation, the Datadog Flutter SDK requires the `trackingConsent` value during initialization.

Set `trackingConsent` to one of the following values:

- `TrackingConsent.pending`: The Datadog Flutter SDK starts collecting and batching the data but does not send it to Datadog. It waits for the new tracking consent value to decide what to do with the batched data.
- `TrackingConsent.granted`: The Datadog Flutter SDK starts collecting the data and sends it to Datadog.
- `TrackingConsent.notGranted`: The Datadog Flutter SDK does not collect any data, which means no logs, traces, or events are sent to Datadog.

To change the tracking consent value after the SDK is initialized, use the `DatadogSdk.setTrackingConsent` API call.

The SDK changes its behavior according to the new value. For example, if the current tracking consent is `TrackingConsent.pending`:

- You change it to `TrackingConsent.granted`, the SDK sends all current and future data to Datadog;
- You change it to `TrackingConsent.notGranted`, the SDK wipes all current data and does not collect any future data.

#### Manage user data collection{% #manage-user-data-collection %}

To manage user data collection settings for client IP or geolocation data:

1. Go to **Manage Applications**.
1. Select your application.
1. Click **User Data Collection**, then toggle the settings to enable/disable **Collect geolocation data** and **Collect client IP data**.

For more information about the data collected, see [Flutter Data Collected](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/flutter/data_collected/).

## Automatically track views{% #automatically-track-views %}

If you are using Flutter Navigator v2.0, your setup for automatic view tracking differs depending on your routing middleware. See [Flutter Integrated Libraries](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/flutter/integrated_libraries/) for instructions on how to integrate with [go_router](https://pub.dev/packages?q=go_router), [AutoRoute](https://pub.dev/packages/auto_route), and [Beamer](https://pub.dev/packages/beamer).

### Flutter Navigator v1{% #flutter-navigator-v1 %}

The Datadog Flutter Plugin can automatically track named routes using the `DatadogNavigationObserver` on your MaterialApp:

```
MaterialApp(
  home: HomeScreen(),
  navigatorObservers: [
    DatadogNavigationObserver(DatadogSdk.instance),
  ],
);
```

This works if you are using named routes or if you have supplied a name to the `settings` parameter of your `PageRoute`.

If you are not using named routes, you can use `DatadogRouteAwareMixin` in conjunction with the `DatadogNavigationObserverProvider` widget to start and stop your RUM views automatically. With `DatadogRouteAwareMixin`, move any logic from `initState` to `didPush`.

### Flutter Navigator v2{% #flutter-navigator-v2 %}

If you are using Flutter Navigator v2.0, which uses the `MaterialApp.router` named constructor, the setup varies based on the routing middleware you are using, if any. Since [`go_router`](https://pub.dev/packages?q=go_router) uses the same observer interface as Flutter Navigator v1, `DatadogNavigationObserver` can be added to other observers as a parameter to `GoRouter`.

```
final _router = GoRouter(
  routes: [
    // Your route information here
  ],
  observers: [
    DatadogNavigationObserver(datadogSdk: DatadogSdk.instance),
  ],
);
MaterialApp.router(
  routerConfig: _router,
  // Your remaining setup
)
```

For examples that use routers other than `go_router`, see Automatically track views.

### Renaming views{% #renaming-views %}

For all setups, you can rename views or supply custom paths by providing a [`viewInfoExtractor`](https://pub.dev/documentation/datadog_flutter_plugin/latest/datadog_flutter_plugin/ViewInfoExtractor.html) callback. This function can fall back to the default behavior of the observer by calling `defaultViewInfoExtractor`. For example:

```
RumViewInfo? infoExtractor(Route<dynamic> route) {
  var name = route.settings.name;
  if (name == 'my_named_route') {
    return RumViewInfo(
      name: 'MyDifferentName',
      attributes: {'extra_attribute': 'attribute_value'},
    );
  }

  return defaultViewInfoExtractor(route);
}

var observer = DatadogNavigationObserver(
  datadogSdk: DatadogSdk.instance,
  viewInfoExtractor: infoExtractor,
);
```

## Automatically track actions{% #automatically-track-actions %}

Use [`RumUserActionDetector`](https://pub.dev/documentation/datadog_flutter_plugin/latest/datadog_flutter_plugin/RumUserActionDetector-class.html) to track user taps that happen in a given Widget tree:

```
RumUserActionDetector(
  rum: DatadogSdk.instance.rum,
  child: Scaffold(
    appBar: AppBar(
      title: const Text('RUM'),
    ),
    body: // Rest of your application
  ),
);
```

`RumUserActionDetector` automatically detects tap user actions that occur in its tree and sends them to RUM. It detects interactions with several common Flutter widgets.

For most Button types, the detector looks for a `Text` widget child, which it uses for the description of the action. In other cases it looks for a `Semantics` object child, or an `Icon` with its `Icon.semanticsLabel` property set.

Alternatively, you can enclose any Widget tree with a [`RumUserActionAnnotation`](https://pub.dev/documentation/datadog_flutter_plugin/latest/datadog_flutter_plugin/RumUserActionAnnotation-class.html), which uses the provided description when reporting user actions detected in the child tree, without changing the Semantics of the tree.

```
Container(
  margin: const EdgeInsets.all(8),
  child: RumUserActionAnnotation(
    description: 'My Image Button',
    child: InkWell(
      onTap: onTap,
      child: Column(
        children: [
          FadeInImage.memoryNetwork(
            placeholder: kTransparentImage,
            image: image,
          ),
          Center(
            child: Text(
              text,
              style: theme.textTheme.headlineSmall,
            ),
          )
        ],
      ),
    ),
  ),
);
```

## Sending data when device is offline{% #sending-data-when-device-is-offline-3 %}

The Flutter SDK ensures availability of data when your user device is offline. In cases of low-network areas, or when the device battery is too low, all events are first stored on the local device in batches. They are sent as soon as the network is available, and the battery is high enough to ensure the Flutter SDK does not impact the end user's experience. If the network is not available with your application running in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost.

**Note**: The data on the disk is automatically deleted if it gets too old to ensure the Flutter SDK does not use too much disk space.
{% /section %}

{% section displayed-if="SDK is React Native" %}
This section only applies to users who meet the following criteria: SDK is React Native

The minimum supported version for the React Native SDK is React Native v0.65+. Compatibility with older versions is not guaranteed out-of-the-box.

{% tab title="React Native" %}
### Step 1 - Install the SDK{% #step-1--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-dependencies-for-ios %}

Install the added pod:

```
(cd ios && pod install)
```

### Android{% #android-2 %}

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.

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui-3 %}

1. In Datadog, navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Choose `react-native` as the application type.
1. Provide an application name to generate a unique Datadog application ID and client token.
1. To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.

{% alert level="info" %}
If you've purchased Error Tracking as a standalone product (without RUM), navigate to [**Error Tracking** > **Settings** > **Browser and Mobile** > **Add an Application**](https://app.datadoghq.com/error-tracking/settings/setup/client/) instead.
{% /alert %}

For data security, you must use a client token. If you used only [Datadog API keys](https://docs.datadoghq.com/account_management/api-app-keys/#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](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 3 - Initialize the library with application context{% #step-3--initialize-the-library-with-application-context %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.com

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

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>', 
    '<ENVIRONMENT_NAME>',
    // 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
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: us3.datadoghq.com

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

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>', 
    '<ENVIRONMENT_NAME>',
    // 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
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.datadoghq.eu

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

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>', 
    '<ENVIRONMENT_NAME>',
    // 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
```

{% /callout %}

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

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

// Configure Datadog SDK
const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>', 
    '<ENVIRONMENT_NAME>',
    // 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
```

{% /callout %}

#### Sample session rates{% #sample-session-rates-4 %}

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.

#### Set tracking consent (GDPR compliance){% #set-tracking-consent--gdpr-compliance-4 %}

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.
1. `.GRANTED`: The React Native SDK starts collecting the data and sends it to Datadog.
1. `.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{% #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{% #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{% #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){% #codepush-integration--optional %}

If you're deploying updates with [CodePush](https://docs.microsoft.com/en-us/appcenter/distribution/codepush/), see the [CodePush setup documentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/react_native/setup/codepush) for additional configuration steps.
{% /tab %}

{% tab title="Expo" %}
### Step 1 - Install the SDK{% #step-1--install-the-sdk-2 %}

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
```

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui-4 %}

1. In Datadog, navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Choose `react-native` as the application type.
1. Provide an application name to generate a unique Datadog application ID and client token.
1. To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings.

{% alert level="info" %}
If you've purchased Error Tracking as a standalone product (without RUM), navigate to [**Error Tracking** > **Settings** > **Browser and Mobile** > **Add an Application**](https://app.datadoghq.com/error-tracking/settings/setup/client/) instead.
{% /alert %}

For data security, you must use a client token. For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 3 - Initialize the library with application context{% #step-3--initialize-the-library-with-application-context-2 %}

Add the following code snippet to your initialization file:

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

const config = new DatadogProviderConfiguration(
    '<CLIENT_TOKEN>', 
    '<ENVIRONMENT_NAME>',
    // 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{% #sample-session-rates-5 %}

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{% #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{% #user-interactions-tracking-2 %}

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){% #codepush-integration--optional-2 %}

If you're deploying updates with [CodePush](https://docs.microsoft.com/en-us/appcenter/distribution/codepush/), see the [CodePush setup documentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/react_native/setup/codepush) for additional configuration steps.
{% /tab %}
{% /section %}

{% section displayed-if="SDK is Kotlin Multiplatform" %}
This section only applies to users who meet the following criteria: SDK is Kotlin Multiplatform

This page describes how to instrument your applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the Kotlin Multiplatform SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/frontend/mobile/kotlin-multiplatform/) for specific steps.

The Datadog Kotlin Multiplatform SDK supports Android 5.0+ (API level 21) and iOS v12+.

## Setup{% #setup-5 %}

### Step 1 - Declare the Kotlin Multiplatform SDK as a dependency{% #step-1--declare-the-kotlin-multiplatform-sdk-as-a-dependency %}

Declare [`dd-sdk-kotlin-multiplatform-rum`](https://github.com/DataDog/dd-sdk-kotlin-multiplatform/tree/develop/features/rum) as a common source set dependency in your Kotlin Multiplatform module's `build.gradle.kts` file.

```
kotlin {
  // declare targets
  // ...

  sourceSets {
    // ...
    commonMain.dependencies {
      implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-rum:<latest_version>")
    }
  }
}
```

### Step 2 - Add native dependencies for iOS{% #step-2--add-native-dependencies-for-ios %}

{% alert level="info" %}
Kotlin 2.0.20 or higher is required if crash tracking is enabled on iOS. Otherwise, due to the compatibility with `PLCrashReporter`, the application may hang if crash tracking is enabled.
{% /alert %}

Add the following Datadog iOS SDK dependencies, which are needed for the linking step:

- `DatadogCore`
- `DatadogRUM`
- `DatadogCrashReporting`

**Note**: Versions of these dependencies should be aligned with the version used by the Datadog Kotlin Multiplatform SDK itself. You can find the complete mapping of iOS SDK versions for each Kotlin Multiplatform SDK release in the [version compatibility guide](https://github.com/DataDog/dd-sdk-kotlin-multiplatform/blob/develop/NATIVE_SDK_VERSIONS.md). If you are using Kotlin Multiplatform SDK version 1.3.0 or below, add `DatadogObjc` dependency instead of `DatadogCore` and `DatadogRUM`.

#### Adding native iOS dependencies using the CocoaPods plugin{% #adding-native-ios-dependencies-using-the-cocoapods-plugin %}

If you are using Kotlin Multiplatform library as a CocoaPods dependency for your iOS application, you can add dependencies as following:

```
cocoapods {
   // ...

   framework {
     baseName = "sharedLib"
   }

   pod("DatadogCore") {
     linkOnly = true
     version = x.x.x
   }

   pod("DatadogRUM") {
     linkOnly = true
     version = x.x.x
   }

   pod("DatadogCrashReporting") {
     linkOnly = true
     version = x.x.x
   }
}
```

#### Adding native iOS dependencies using Xcode{% #adding-native-ios-dependencies-using-xcode %}

If you are integrating Kotlin Multiplatform library as a framework with an `embedAndSignAppleFrameworkForXcode` Gradle task as a part of your Xcode build, you can add the necessary dependencies directly in Xcode as following:

1. Click on your project in Xcode and go to the **Package Dependencies** tab.
1. Add the iOS SDK package dependency by adding `https://github.com/DataDog/dd-sdk-ios.git` as a package URL.
1. Select the version from the table above.
1. Click on the necessary application target and open the **General** tab.
1. Scroll down to the **Frameworks, Libraries, and Embedded Content** section and add the dependencies mentioned above.

### Step 3 - Specify application details in the UI{% #step-3--specify-application-details-in-the-ui %}

1. Navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Select `Kotlin Multiplatform` as the application type and enter an application name to generate a unique Datadog application ID and client token.
1. To disable automatic user data collection for either client IP or geolocation data, uncheck the boxes for those settings. For more information, see [RUM Kotlin Multiplatform Data Collected](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/kotlin_multiplatform/data_collected).

{% alert level="info" %}
If you've purchased Error Tracking as a standalone product (without RUM), navigate to [**Error Tracking** > **Settings** > **Browser and Mobile** > **Add an Application**](https://app.datadoghq.com/error-tracking/settings/setup/client) instead.
{% /alert %}

To ensure the safety of your data, you must use a client token. If you use only [Datadog API keys](https://docs.datadoghq.com/account_management/api-app-keys/#api-keys) to configure the Datadog SDK, they are exposed client-side in the Android application's APK byte code.

For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 4 - Initialize Datadog SDK{% #step-4--initialize-datadog-sdk %}

In the initialization snippet, set an environment name. For Android, set a variant name if it exists. For more information, see [Using Tags](https://docs.datadoghq.com/getting_started/tagging/using_tags/).

See `trackingConsent` to add GDPR compliance for your EU users, and [other configuration options](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/advanced_configuration/kotlin_multiplatform/#initialization-parameters) to initialize the library.

```
// in common source set
fun initializeDatadog(context: Any? = null) {
    // context should be application context on Android and can be null on iOS
    val appClientToken = <CLIENT_TOKEN>
    val appEnvironment = <ENV_NAME>
    val appVariantName = <APP_VARIANT_NAME>

    val configuration = Configuration.Builder(
            clientToken = appClientToken,
            env = appEnvironment,
            variant = appVariantName
    )7ae6e469-e055-4ddf-af26-9a785f2dc717
        .build()

    Datadog.initialize(context, configuration, trackingConsent)
}
```

### Step 5 - Sample RUM sessions{% #step-5--sample-rum-sessions %}

To control the data your application sends to Datadog RUM, you can specify a sample rate for RUM sessions while [initializing the RUM feature](https://app.datadoghq.com/rum/application/create). The rate is a percentage between 0 and 100. By default, `sessionSamplingRate` is set to 100 (keep all sessions).

```
val rumConfig = RumConfiguration.Builder(applicationId)
        // Here 75% of the RUM sessions are sent to Datadog
        .setSessionSampleRate(75.0f)
        .build()
Rum.enable(rumConfig)
```

### Step 6 - Enable RUM to start sending data{% #step-6--enable-rum-to-start-sending-data %}

```
// in a common source set
fun initializeRum(applicationId: String) {
    val rumConfiguration = RumConfiguration.Builder(applicationId)
            .trackLongTasks(durationThreshold)
            .apply {
                // platform specific setup
                rumPlatformSetup(this)
            }
            .build()

    Rum.enable(rumConfiguration)
}

internal expect fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder)

// in iOS source set
internal actual fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder) {
    with(rumConfigurationBuilder) {
        trackUiKitViews()
        trackUiKitActions()
        // check more iOS-specific methods
    }
}

// in Android source set
internal actual fun rumPlatformSetup(rumConfigurationBuilder: RumConfiguration.Builder) {
    with(rumConfigurationBuilder) {
        useViewTrackingStrategy(/** choose view tracking strategy **/)
        trackUserInteractions()
        // check more Android-specific methods
    }
}
```

See [Automatically track views](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/advanced_configuration/kotlin_multiplatform/#automatically-track-views) to enable automatic tracking of all your views.

### Set tracking consent (GDPR compliance){% #set-tracking-consent--gdpr-compliance-5 %}

To be compliant with GDPR, the SDK requires the tracking consent value at initialization. Tracking consent can be one of the following values:

- `TrackingConsent.PENDING`: (Default) The SDK starts collecting and batching the data but does not send it to the collection endpoint. The SDK waits for the new tracking consent value to decide what to do with the batched data.
- `TrackingConsent.GRANTED`: The SDK starts collecting the data and sends it to the data collection endpoint.
- `TrackingConsent.NOT_GRANTED`: The SDK does not collect any data. You are not able to manually send any logs, traces, or RUM events.

To update the tracking consent after the SDK is initialized, call `Datadog.setTrackingConsent(<NEW CONSENT>)`. The SDK changes its behavior according to the new consent. For example, if the current tracking consent is `TrackingConsent.PENDING` and you update it to:

- `TrackingConsent.GRANTED`: The SDK sends all current batched data and future data directly to the data collection endpoint.
- `TrackingConsent.NOT_GRANTED`: The SDK wipes all batched data and does not collect any future data.

### Step 7 - Initialize the RUM Ktor plugin to track network events made with Ktor{% #step-7--initialize-the-rum-ktor-plugin-to-track-network-events-made-with-ktor %}

1. In your `build.gradle.kts` file, add the Gradle dependency to `dd-sdk-kotlin-multiplatform-ktor` for Ktor 2.x, or `dd-sdk-kotlin-multiplatform-ktor3` for Ktor 3.x:

```
kotlin {
    // ...
    sourceSets {
        // ...
        commonMain.dependencies {
            // Use this line if you are using Ktor 2.x
            implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-ktor:x.x.x")
            // Use this line if you are using Ktor 3.x
            // implementation("com.datadoghq:dd-sdk-kotlin-multiplatform-ktor3:x.x.x")
        }
    }
}
```
To track your Ktor requests as resources, add the provided [Datadog Ktor plugin](https://github.com/DataDog/dd-sdk-kotlin-multiplatform/tree/develop/integrations/ktor):
```
val ktorClient = HttpClient {
    install(
        datadogKtorPlugin(
            tracedHosts = mapOf(
                "example.com" to setOf(TracingHeaderType.DATADOG),
                "example.eu" to setOf(TracingHeaderType.DATADOG)
            ),
            traceSampleRate = 100f
        )
    )
}
```

This records each request processed by the `HttpClient` as a resource in RUM, with all the relevant information automatically filled (URL, method, status code, and error). Only the network requests that started when a view is active are tracked. To track requests when your application is in the background, [create a view manually](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/advanced_configuration/kotlin_multiplatform/#custom-views) or enable background view tracking.

## Track errors{% #track-errors %}

[Kotlin Multiplatform Crash Reporting and Error Tracking](https://docs.datadoghq.com/real_user_monitoring/error_tracking/kotlin_multiplatform/) displays any issues in your application and the latest available errors. You can view error details and attributes including JSON in the [RUM Explorer](https://docs.datadoghq.com/real_user_monitoring/explorer/).

## Sending data when device is offline{% #sending-data-when-device-is-offline-4 %}

RUM ensures availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.

Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
{% /section %}

{% section displayed-if="SDK is Roku" %}
This section only applies to users who meet the following criteria: SDK is Roku

This page describes how to instrument your applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the Roku SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/frontend/mobile/roku/) for specific steps.

The Datadog Roku SDK supports BrightScript channels for Roku OS 10 and higher.

## Setup{% #setup-6 %}

### Step 1 - Declare the SDK as a dependency{% #step-1--declare-the-sdk-as-a-dependency %}

#### Using ROPM (recommended){% #using-ropm--recommended %}

`ROPM` is a package manager for the Roku platform (based on NPM). If you're not already using `ROPM` in your Roku project, read their [Getting started guide](https://github.com/rokucommunity/ropm). Once your project is set up to use `ROPM`, you can use the following command to install the Datadog dependency:

```
ropm install datadog-roku
```

#### Setup manually{% #setup-manually %}

If your project does not use `ROPM`, install the library manually by downloading the [Roku SDK](https://github.com/DataDog/dd-sdk-roku) zip archive and unzipping it in your project's root folder.

Make sure you have a `roku_modules/datadogroku` subfolder in both the `components` and `source` folders of your project.

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui-5 %}

1. Navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Select **Roku** as the application type and enter an application name to generate a unique Datadog application ID and client token.
1. To disable automatic user data collection for client IP or geolocation data, uncheck the boxes for those settings. For more information, see [Roku Data Collected](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/roku/data_collected).

{% alert level="info" %}
If you've purchased Error Tracking as a standalone product (without RUM), navigate to [**Error Tracking** > **Settings** > **Browser and Mobile** > **Add an Application**](https://app.datadoghq.com/error-tracking/settings/setup/client) instead.
{% /alert %}

To ensure the safety of your data, you must use a client token. If you use only [Datadog API keys](https://docs.datadoghq.com/account_management/api-app-keys/#api-keys) to configure the `dd-sdk-roku` library, they are exposed client-side in the Roku channel's BrightScript code.

For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 3 - Initialize the library{% #step-3--initialize-the-library-3 %}

In the initialization snippet, set an environment name. For more information, see [Using Tags](https://docs.datadoghq.com/getting_started/tagging/using_tags/#rum--session-replay).

```
sub RunUserInterface(args as dynamic)
    screen = CreateObject("roSGScreen")
    scene = screen.CreateScene("MyScene")
    screen.show()

    datadogroku_initialize({
        clientToken: "<CLIENT_TOKEN>",
        applicationId: "<APPLICATION_ID>"
        site: "",
        env: "<ENV_NAME>",
        sessionSampleRate: 100, ' the percentage (integer) of sessions to track
        launchArgs: args
    })

    ' complete your channel setup here
end sub
```

#### Sample session rates{% #sample-session-rates-6 %}

To control the data your application sends to Datadog RUM, you can specify a sampling rate for RUM sessions while [initializing the RUM Roku SDK](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/roku/advanced_configuration/#enrich-user-sessions). The rate is a percentage between 0 and 100. By default, `sessionSamplingRate` is set to 100 (keep all sessions).

## Instrument the channel{% #instrument-the-channel %}

See **Track RUM Resources** to enable automatic tracking of all your resources, and **Enrich user sessions** to add custom global or user information to your events.

### Track Views{% #track-views %}

To split [user sessions](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/roku/data_collected) into logical steps, manually start a View using the following code. Every navigation to a new screen within your channel should correspond to a new View.

```
    viewName = "VideoDetails"
    viewUrl = "components/screens/VideoDetails.xml"
    m.global.datadogRumAgent.callfunc("startView", viewName, viewUrl)
```

### Track RUM Actions{% #track-rum-actions %}

RUM Actions represent the interactions your users have with your channel. You can forward actions to Datadog as follows:

```
    targetName = "playButton" ' the name of the SG Node the user interacted with
    actionType = "click" ' the type of interaction, should be one of "click", "back", or "custom" 
    m.global.datadogRumAgent.callfunc("addAction", { target: targetName, type: actionType})
```

### Track RUM errors{% #track-rum-errors %}

Whenever you perform an operation that might throw an exception, you can forward the error to Datadog as follows:

```
    try
        doSomethingThatMightThrowAnException()
    catch error
        m.global.datadogRumAgent.callfunc("addError", error)
    end try
```

## Sending data when device is offline{% #sending-data-when-device-is-offline-5 %}

RUM ensures availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.

Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost. To ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
{% /section %}

{% section displayed-if="SDK is Unity" %}
This section only applies to users who meet the following criteria: SDK is Unity

This page describes how to instrument your applications for [Real User Monitoring (RUM)](https://docs.datadoghq.com/real_user_monitoring/) with the Unity SDK. RUM includes Error Tracking by default, but if you have purchased Error Tracking as a standalone product, see the [Error Tracking setup guide](https://docs.datadoghq.com/error_tracking/frontend/mobile/unity/) for specific steps.

{% alert level="info" %}
Datadog supports Unity Monitoring for iOS and Android for Unity LTS 2022+.
{% /alert %}

Datadog does not support Desktop (Windows, Mac, or Linux) or console deployments from Unity. If you have a game or application and want to use Datadog RUM to monitor its performance, create a ticket with [Datadog support](https://docs.datadoghq.com/help/).

### Step 1 - Install the SDK{% #step-1--install-the-sdk-3 %}

1. Install the [External Dependency Manager for Unity (EDM4U)](https://github.com/googlesamples/unity-jar-resolver). This can be done using [Open UPM](https://openupm.com/packages/com.google.external-dependency-manager/).

1. Add the Datadog SDK Unity package from its Git URL at [https://github.com/DataDog/unity-package](https://github.com/DataDog/unity-package). The package URL is `https://github.com/DataDog/unity-package.git`.

1. (Android only) Configure your project to use [Gradle templates](https://docs.unity3d.com/Manual/gradle-templates.html), and enable both `Custom Main Template` and `Custom Gradle Properties Template`.

1. (Android only) If you build and receive `Duplicate class` errors (common in Unity 2022.x), add the following code to the `dependencies` block of your `mainTemplate.gradle`:

```
constraints {
     implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0") {
         because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
     }
}
```

#### WebGL{% #webgl %}

1. Create a custom WebGL template, following the instructions provided by [Unity](https://docs.unity3d.com/2022.3/Documentation/Manual/webgl-templates.html), or by using the minimally modified version in Datadog's [GitHub repo](https://github.com/DataDog/dd-sdk-unity/tree/develop/samples/Datadog%20Sample/Assets/WebGLTemplates).

1. If you are using your own WebGL template, or have added a new WebGL template, modify it to include the Datadog Browser SDK delivered by CDN.

```
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-logs.js"></script>
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum-slim.js"></script>
```

### Step 2 - Specify application details in the UI{% #step-2--specify-application-details-in-the-ui-6 %}

1. In Datadog, navigate to [**Digital Experience** > **Add an Application**](https://app.datadoghq.com/rum/application/create).
1. Choose **Unity** as the application type.
1. Provide an application name to generate a unique Datadog application ID and client token.
1. To disable automatic user data collection for either client IP or geolocation data, uncheck the boxes for those settings.

To ensure the safety of your data, you must use a client token. For more information about setting up a client token, see the [Client Token documentation](https://docs.datadoghq.com/account_management/api-app-keys/#client-tokens).

### Step 3 - Configure Datadog settings in Unity{% #step-3--configure-datadog-settings-in-unity %}

After installing the Datadog Unity SDK, you need to set Datadog's settings in the Unity UI. Navigate to your `Project Settings` and click on the `Datadog` section on the left hand side.

The following parameters are available:

| Parameter                       | Required?               | Description                                                                                                                                                                                                                                                                                                                                             |
| ------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable Datadog                  | No                      | Whether Datadog should be enabled. Disabling Datadog does not cause any of the Datadog APIs to fail, throw exceptions, or return `null` from any calls. It only stops the SDK from sending any information.                                                                                                                                             |
| Output Symbol Files             | No                      | This option enables the output of symbol files for Datadog symbolication and file/line mapping features in Datadog Error Tracking.                                                                                                                                                                                                                      |
| Perform Native Stack Mapping    | No                      | Converts C# stacks traces to native stack traces in non-development builds. This allows for file and line mapping to C# code if symbol files are uploaded to Datadog. This is not supported if Output Symbols is disabled.                                                                                                                              |
| Client Token                    | Yes                     | Your client token created for your application on Datadog's website.                                                                                                                                                                                                                                                                                    |
| Env                             | No                      | The name of the environment for your application. Defaults to `"prod"`.                                                                                                                                                                                                                                                                                 |
| Service Name                    | No                      | The service name for your application. If this is not set, it is automatically set to your application's package name or bundle name (e.g.: com.example.android).                                                                                                                                                                                       |
| Datadog Site                    | Yes                     | The site you send your data to.                                                                                                                                                                                                                                                                                                                         |
| Batch Size                      | Yes                     | Sets the preferred size of batched data uploaded to Datadog. This value impacts the size and number of requests performed by the SDK (small batches mean more requests, but each request becomes smaller in size).                                                                                                                                      |
| Upload Frequency                | Yes                     | Sets the preferred frequency of uploading data to Datadog.                                                                                                                                                                                                                                                                                              |
| Batch Processing Level          | Yes                     | Defines the maximum amount of batches processed sequentially without a delay within one reading/uploading cycle.                                                                                                                                                                                                                                        |
| Enable Crash Reporting          | No                      | Enables crash reporting in the RUM SDK.                                                                                                                                                                                                                                                                                                                 |
| Forward Unity Logs              | No                      | Whether to forward logs made from Unity's `Debug.Log` calls to Datadog's default logger.                                                                                                                                                                                                                                                                |
| Remote Log Threshold            | Yes                     | The level at which the default logger forwards logs to Datadog. Logs below this level are not sent.                                                                                                                                                                                                                                                     |
| Enable RUM                      | No                      | Whether to enable sending data from Datadog's Real User Monitoring APIs                                                                                                                                                                                                                                                                                 |
| Enable Automatic Scene Tracking | No                      | Whether Datadog should automatically track new Views by intercepting Unity's `SceneManager` loading.                                                                                                                                                                                                                                                    |
| RUM Application ID              | Yes (if RUM is enabled) | The RUM Application ID created for your application on Datadog's website.                                                                                                                                                                                                                                                                               |
| Session Sample Rate             | Yes                     | The percentage of sessions to send to Datadog. Between 0 and 100.                                                                                                                                                                                                                                                                                       |
| Trace Sample Rate               | Yes                     | The percentage of distributed traces to send to Datadog. Between 0 and 100.                                                                                                                                                                                                                                                                             |
| Trace Context Injection         | Yes                     | Whether to inject trace context into `All` or `Only Sampled` resource requests.                                                                                                                                                                                                                                                                         |
| Track Non-Fatal ANRs            | No                      | (Android Only) Whether to track non-fatal ANRs (Application Not Responding) errors. The "SDK Default" option disables ANR detection on Android 30+ because it would create too much noise over fatal ANRs. On Android 29 and below, however, the reporting of non-fatal ANRs is enabled by default, as fatal ANRs cannot be reported on those versions. |
| Track Non-Fatal App Hangs       | No                      | (iOS Only) Whether to track non-fatal app hangs. App hangs are detected when the app is unresponsive for a certain amount of time. The supplied "Threshold" is the amount of time in seconds that the app must be unresponsive before it is considered a non-fatal app hang.                                                                            |
| First Party Hosts               | No                      | To enable distributed tracing, you must specify which hosts are considered "first party" and have trace information injected.                                                                                                                                                                                                                           |

### Sample RUM sessions{% #sample-rum-sessions %}

You can control the data your application sends to Datadog RUM during instrumentation of the RUM Unity SDK. Specify the **Session Sample Rate** as a percentage between 0 and 100 in the Project Settings window in Unity.

## Using Datadog{% #using-datadog %}

### Setting tracking consent{% #setting-tracking-consent %}

To be compliant with data protection and privacy policies, the Datadog Unity SDK requires setting a tracking consent value.

The `trackingConsent` setting can be one of the following values:

- `TrackingConsent.Pending`: The Unity SDK starts collecting and batching the data but does not send it to Datadog. The Unity SDK waits for the new tracking consent value to decide what to do with the batched data.
- `TrackingConsent.Granted`: The Unity SDK starts collecting the data and sends it to Datadog.
- `TrackingConsent.NotGranted`: The Unity SDK does not collect any data. No logs are sent to Datadog.

Before Datadog sends any data, confirm the user's `Tracking Consent`. This is set to `TrackingConsent.Pending` during initialization, and needs to be set to `TrackingConsent.Granted` before Datadog sends any information.

```
DatadogSdk.Instance.SetTrackingConsent(TrackingConsent.Granted);
```

### Logging{% #logging %}

You can intercept and send logs from Unity's default debug logger by enabling the option and threshold in your projects settings.

Datadog maps the Unity levels to the following in Datadog's Logging Levels:

| Unity LogType | Datadog Log Level |
| ------------- | ----------------- |
| Log           | Info              |
| Error         | Error             |
| Assert        | Critical          |
| Warning       | Warn              |
| Exception     | Critical          |

You can access this default logger to add attributes or tags through the `DatadogSdk.DefaultLogger` property.

You can also create additional loggers for more fine grained control of thresholds, service names, logger names, or to supply additional attributes.

```
var logger = DatadogSdk.Instance.CreateLogger(new DatadogLoggingOptions()
{
    NetworkInfoEnabled = true,
    DatadogReportingThreshold = DdLogLevel.Debug,
});
logger.Info("Hello from Unity!");

logger.Debug("Hello with attributes", new()
{
    { "my_attribute", 122 },
    { "second_attribute", "with_value" },
    { "bool_attribute", true },
    {
        "nested_attribute", new Dictionary<string, object>()
        {
            { "internal_attribute", 1.234 },
        }
    },
});
```

### Real User Monitoring (RUM){% #real-user-monitoring--rum %}

#### Manual Scene (View) Tracking{% #manual-scene--view-tracking %}

To manually track new Scenes (`Views` in Datadog), use the `StartView` and `StopView` methods:

```
public void Start()
{
    DatadogSdk.Instance.Rum.StartView("My View", new()
    {
        { "view_attribute": "active" }
    });
}
```

Starting a new view automatically ends the previous view.

#### Automatic Scene Tracking{% #automatic-scene-tracking %}

You can also set `Enable Automatic Scene Tracking` in your Project Settings to enable automatically tracking active scenes. This uses Unity's `SceneManager.activeSceneChanged` event to automatically start new scenes.

#### Web Requests / Resource Tracking{% #web-requests--resource-tracking %}

Datadog offers `DatadogTrackedWebRequest`, which is a `UnityWebRequest` wrapper intended to be a drop-in replacement for `UnityWebRequest`. `DatadogTrackedWebRequest` enables [Datadog Distributed Tracing](https://docs.datadoghq.com/real_user_monitoring/correlate_with_other_telemetry/apm/?tab=browserrum).

To enable Datadog Distributed Tracing, you must set the `First Party Hosts` in your project settings to a domain that supports distributed tracing. You can also modify the sampling rate for distributed tracing by setting the `Tracing Sampling Rate`.

`First Party Hosts` does not allow wildcards, but matches any subdomains for a given domain. For example, api.example.com matches staging.api.example.com and prod.api.example.com, but not news.example.com.

## Sending data when device is offline{% #sending-data-when-device-is-offline-6 %}

RUM helps ensure availability of data when your user device is offline. In case of low-network areas, or when the device battery is too low, all the RUM events are first stored on the local device in batches.

Each batch follows the intake specification. They are sent as soon as the network is available, and the battery is high enough to help ensure the Datadog SDK does not impact the end user's experience. If the network is not available while your application is in the foreground, or if an upload of data fails, the batch is kept until it can be sent successfully.

This means that even if users open your application while offline, no data is lost. To help ensure the SDK does not use too much disk space, the data on the disk is automatically discarded if it gets too old.
{% /section %}

{% image
   source="https://datadog-docs.imgix.net/images/real_user_monitoring/android/android-new-application.fe329bfc1c6e54126fcc8822dff1d2f0.png?auto=format"
   alt="" /%}
