---
title: "React Native"
description: "Set up Middleware RUM for React Native apps on iOS and Android to track user interactions and monitor performance."
section: "RUM"
breadcrumb: "RUM > Mobile > React Native"
canonical: "https://docs.middleware.io/get-started/rum/react"
---
# React Native

The Middleware React Native RUM SDK collects user activity, performance data, and errors across iOS and Android applications. It connects JavaScript and native application activity with the sessions in which problems occur.

Collected data includes app startup, navigation, network requests, JavaScript errors, and native crashes. Session Replay helps explain what the user experienced—for example, a failed request that prevented navigation to the next screen.

## Prerequisites

Before installing the SDK, make sure you have:

- React Native 0.68 or later.
- A Middleware account and RUM application credentials.
- Access to your React Native application source code.
- HTTPS connectivity to the Middleware ingestion endpoint.

For SDK 2.x, the native platform requirements are:

| Platform | Requirements |
| --- | --- |
| Android | `compileSdk` 35+, Kotlin Gradle Plugin 2.0+, core library desugaring enabled |
| iOS | iOS 13.0+, CocoaPods support |

**Note:** On iOS, MiddlewareRum is a static framework. If your project uses use_frameworks!, ensure dependent pods use static linking.

## Installation

#### 1 Create a RUM application

1. Log in to Middleware.
2. Go to **Installation → RUM**.
3. Select **React Native** as the platform.
4. Click **New Application**.
5. Enter your application name and click **Create Application**.
6. Copy the generated RUM credentials and target URL.

#### 2 Install the React Native SDK

Install the Middleware SDK in your React Native project:

```bash
yarn add @middleware.io/middleware-react-native
```

Alternatively, use npm:

```bash
npm install @middleware.io/middleware-react-native
```

For iOS, add the Middleware specs repo and the CocoaPods CDN to the top of `ios/Podfile`:

```ruby
source 'https://github.com/middleware-labs/cocoapods-specs.git'
source 'https://cdn.cocoapods.org/'
```

Keep both sources: new `MiddlewareRum` versions are published to the Middleware repo, and the SDK's dependencies still come from the CocoaPods CDN. CocoaPods trunk stops accepting new pods on December 2, 2026, so without the Middleware source your app stays on the last version published to trunk.

Then install the native dependencies:

```bash
cd ios
pod install
cd ..
```

For production applications, pin the SDK to a tested version. The latest release is `2.3.2`:

```bash
yarn add @middleware.io/middleware-react-native@2.3.2
```

#### 3 Initialize Middleware

Wrap your root application component with `MiddlewareWrapper`.
For example, in `index.tsx`:

```js
import React from 'react';
import {
  MiddlewareWrapper,
  type ReactNativeConfiguration,
} from '@middleware.io/middleware-react-native';

import App from './App';

const middlewareConfig: ReactNativeConfiguration = {
  serviceName: 'my-react-native-app',
  projectName: 'My-React-Native-App',
  accountKey: '<MW_API_KEY>',
  target: 'https://<MW_UID>.middleware.io',
  deploymentEnvironment: 'PROD',

  globalAttributes: {
    'app.version': '1.0.0',
  },
};

export default function Root() {
  return (
    <MiddlewareWrapper config={middlewareConfig}>
      <App />
    </MiddlewareWrapper>
  );
}
```

Replace the placeholders with your Middleware credentials.

**Important**: Initialize Middleware before your application renders to capture startup activity and early network requests.

| Parameter | Required | Description |
| --- | --- | --- |
| `serviceName` | Yes | Service name used to identify the application |
| `projectName` | Yes | Project name associated with the application |
| `accountKey` | Yes | Middleware API key |
| `target` | Yes | Middleware ingestion endpoint |
| `deploymentEnvironment` | No | Environment, such as `PROD` or `DEV` |
| `globalAttributes` | No | Custom attributes added to telemetry |

If your application uses React Navigation, keep `NavigationContainer` inside `MiddlewareWrapper` so navigation changes are captured automatically.

#### 4 Run and verify

Build and run your application on an Android or iOS emulator or physical device.

1. Open the application.
2. Navigate between screens and trigger a few API requests.
3. Go to RUM → Session Explorer in Middleware.
4. Verify that your application sessions appear.

Read more about [RUM explorer](https://docs.middleware.io/features/rum/session-explorer) and see what data to monitor for frontend performance.

## Optional configuration

### Configure network monitoring

Network instrumentation is enabled by default for requests made through `fetch` and `XMLHttpRequest`.

The SDK captures request methods, URLs, response status codes, timings, and selected headers.

You can exclude specific URLs or headers from collection:

```js
const middlewareConfig: ReactNativeConfiguration = {
  serviceName: 'my-react-native-app',
  projectName: 'My-React-Native-App',
  accountKey: '<MW_API_KEY>',
  target: 'https://<MW_UID>.middleware.io',

  ignoreUrls: [
    /\/api\/health/,
    /\/api\/internal\/.*/,
  ],

  ignoreHeaders: new Set([
    'x-internal-header',
  ]),
};
```

The SDK always masks the value of the `x-access-token` header.

To disable network instrumentation entirely, add:

```js
networkInstrumentation: false
```

**Note**: Network libraries that bypass the global fetch or XHR implementation may require separate instrumentation.

## Configure Session Replay

Session Replay is enabled by default and starts automatically when the SDK initializes.

It records native screen activity and connects recordings with navigation, errors, and network requests.

### Configure recording quality and privacy

Add `recordingOptions` to your SDK configuration:

```js
const middlewareConfig: ReactNativeConfiguration = {
  serviceName: 'my-react-native-app',
  projectName: 'My-React-Native-App',
  accountKey: '<MW_API_KEY>',
  target: 'https://<MW_UID>.middleware.io',

  sessionRecording: true,

  recordingOptions: {
    frequency: 'standard',
    quality: 'standard',
    maskAllTextInputs: true,
    maskAllImages: true,
  },
};
```

| Option | Description |
| --- | --- |
| `sessionRecording` | Enables or disables Session Replay |
| `frequency` | Recording frequency: `low`, `standard`, or `high` |
| `quality` | Recording quality: `low`, `standard`, or `high` |
| `maskAllTextInputs` | Masks text input values; enabled by default |
| `maskAllImages` | Masks images; enabled by default |

### Disable Session Replay

To collect RUM telemetry without recording user sessions:

```js
sessionRecording: false
```

### Session recording limits

- **Maximum session duration**: 4 hours.
- **Idle timeout**: 15 minutes.
- **Default**: Session Replay enabled.

A new session starts when activity resumes after the idle timeout.

## Mask sensitive information

The SDK masks text inputs and images by default.

To mask additional UI elements, wrap sensitive components with `MiddlewareSanitizedView`:

```js
import {
  MiddlewareSanitizedView,
} from '@middleware.io/middleware-react-native';

function PaymentScreen() {
  return (
    <MiddlewareSanitizedView>
      <PaymentDetails />
    </MiddlewareSanitizedView>
  );
}
```

Use this for payment information, authentication screens, OTP fields, or other sensitive UI elements.

Masking happens on the device before recording data is uploaded.

**Privacy recommendation**: Review sensitive screens before enabling Session Replay in production. Avoid sending passwords, tokens, or personal information through custom attributes and logs.

## Configure distributed tracing

Distributed tracing connects React Native network requests with backend APM traces.

By default, the SDK injects W3C `traceparent` and B3 tracing headers into supported HTTP requests.

### Prerequisites

- Middleware APM instrumentation must be enabled on backend services.
- Backend services must support W3C Trace Context or B3 propagation.
- Network instrumentation must be enabled.

### Restrict trace propagation targets

To send tracing headers only to your backend APIs:

```js
const middlewareConfig: ReactNativeConfiguration = {
  serviceName: 'my-react-native-app',
  projectName: 'My-React-Native-App',
  accountKey: '<MW_API_KEY>',
  target: 'https://<MW_UID>.middleware.io',

  tracePropagationTargets: [
    /api\.example\.com/,
    /checkout\.example\.com/,
  ],

  tracePropagationFormat: 'w3c',
};
```

Requests to other domains are still monitored but do not receive trace propagation headers.

Use regular expressions for matching domains. Plain string entries must match the complete URL exactly.

To disable trace propagation, set:

```js
tracePropagationTargets: []
```

### Verify trace correlation

1. Open your application and trigger a backend API request.
2. Go to **RUM → Session Explorer**.
3. Open the session and select the network request.
4. Follow the associated backend trace.

If the request contains a trace ID but no backend spans, verify that the backend has APM instrumentation and supports the configured propagation format.

## Add custom logs and errors

### Custom logs

Use `MiddlewareRum` to record application-specific logs:

```js
import {
  MiddlewareRum,
} from '@middleware.io/middleware-react-native';

MiddlewareRum.debug('Loading checkout');
MiddlewareRum.info('Payment initiated');
MiddlewareRum.warn('API response delayed');
MiddlewareRum.error('Payment request failed');
```

These logs provide additional context when investigating user sessions.

### Report handled exceptions

JavaScript errors and native crashes are captured automatically.

For handled exceptions, use `reportError()`:

```js
try {
  throw new Error('Payment request failed');
} catch (error) {
  MiddlewareRum.reportError(error as Error);
}
```

## Add custom attributes

Use global attributes to filter sessions by application version, environment, or user group.

Set attributes during initialization:

```js
globalAttributes: {
  'app.version': '1.0.0',
  'user.type': 'premium',
}
```

To update attributes after initialization:

```js
MiddlewareRum.setGlobalAttributes({
  'app.version': '1.0.1',
  'user.type': 'premium',
});
```

Prefer stable, non-sensitive attributes.

### Configure session sampling

Use `sessionSamplingRatio` to control the percentage of sessions collected:

```js
sessionSamplingRatio: 0.5
```

The value ranges from `0.0` to `1.0`.

| Value | Behavior |
| --- | --- |
| `1.0` | Collects all eligible sessions |
| `0.5` | Collects approximately 50% of sessions |
| `0.1` | Collects approximately 10% of sessions |
| `0.0` | Collects no sessions |

Sampling applies to session traces and recordings.

## Configuration reference

All options accepted by `ReactNativeConfiguration`:

| Parameter | Default | Description |
| --- | --- | --- |
| `target` | Required | Middleware ingestion endpoint |
| `accountKey` | Required | Middleware API key |
| `serviceName` | Required | Application service name |
| `projectName` | Required | Application project name |
| `deploymentEnvironment` | — | Deployment environment |
| `globalAttributes` | `{}` | Custom attributes added to telemetry |
| `appStartEnabled` | `true` | Enables app startup monitoring |
| `debug` | `false` | Enables verbose SDK diagnostic logs |
| `sessionRecording` | `true` | Enables Session Replay |
| `recordingOptions` | SDK defaults | Configures recording quality and masking |
| `sessionSamplingRatio` | `1.0` | Percentage of sessions collected |
| `networkInstrumentation` | `true` | Enables fetch/XHR monitoring |
| `tracePropagationTargets` | All URLs | Defines which requests receive tracing headers |
| `tracePropagationFormat` | Both | Configures W3C or B3 propagation |
| `ignoreUrls` | Middleware endpoints | Additional URLs excluded from monitoring |
| `ignoreHeaders` | Empty set | Headers excluded from captured telemetry |

## Troubleshooting

### No RUM data appears

If the application runs but telemetry does not appear:

- Verify that the SDK is installed and native dependencies are linked.
- Confirm that `MiddlewareWrapper` is initialized at the application root.
- Check the API key and target URL.
- Verify that the device can connect to Middleware over HTTPS.
- Enable `debug: true` to review SDK diagnostic logs.

### Network requests are missing

If sessions appear but HTTP requests are not captured:

- Confirm that `networkInstrumentation` is enabled.
- Verify that requests use `fetch` or `XMLHttpRequest`.
- Check whether the URLs match an `ignoreUrls` rule.
- Check whether a networking library bypasses the global HTTP implementation.

### Navigation changes are not tracked

- Keep `NavigationContainer` inside `MiddlewareWrapper`.
- Confirm that your application uses a supported React Navigation setup.
- Verify that screen transitions update the navigation state.

### Session Replay is missing

- Confirm that `sessionRecording` is not set to `false`.
- Verify that the application remains active long enough to generate a recording.
- Check that the session is not excluded by sampling.
- Review SDK diagnostic logs for recording errors.

### Same recording appears under multiple session IDs

If one recording appears in several sessions and only one of them plays:

- Upgrade to SDK `2.3.1` or later. This was caused by app lifecycle instrumentation in earlier versions and is fixed in `2.3.1`.

### Sensitive information appears in recordings

- Verify that `maskAllTextInputs` and `maskAllImages` are enabled.
- Wrap sensitive components with `MiddlewareSanitizedView`.
- Review custom attributes and logs for sensitive values.

### Backend traces are not correlated

- Verify that backend APM instrumentation is enabled.
- Confirm that tracePropagationTargets matches the requested backend URL.
- Check that the backend accepts the configured propagation format.
- Ensure that tracing headers are not removed by gateways or proxies.

### iOS or Android build errors

#### For iOS:

- Run `cd ios && pod install`.
- If CocoaPods can't find or upgrade `MiddlewareRum`, check both sources are in your Podfile and run `pod update MiddlewareRum`.
- Verify that the deployment target is iOS 13 or later.
- Check static framework linking if `use_frameworks!` is enabled.

#### For Android:

- Verify that `compileSdk` is 35 or later.
- Confirm that Kotlin Gradle Plugin 2.0+ is configured.
- Ensure core library desugaring is enabled.
- Rebuild the Android project after installing the SDK.

If the issue persists, contact Middleware Support at support@middleware.io.

Need assistance or want to learn more about Middleware? Get in touch with us via our Contact Us page or join our Slack channel.
