> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixpanel.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Implement Session Replay (React Native)

Mixpanel's React Native Session Replay SDK enables you to capture and analyze user interactions in your mobile applications. Built as a Turbo Module for React Native's New Architecture, it provides native implementations for both iOS and Android with a unified JavaScript API.

## Features

* **📱 Cross-Platform Support** - Unified API for iOS and Android
* **🎥 Session Recording** - Capture user interactions and screen recordings
* **🔒 Privacy-First** - Built-in data masking for sensitive information
* **⚡ High Performance** - Native implementation with minimal JavaScript bridge overhead
* **🎯 Selective Recording** - Configurable sampling rates and recording controls
* **🚀 New Architecture Ready** - Built as a Turbo Module with full type safety
* **🛡️ Granular Privacy Controls** - Auto-masking and manual masking via wrapper components

## Requirements

* React Native >= 0.70
* iOS >= 13.0
* Android API Level >= 21
* New Architecture support (backward compatible with old architecture)

## Installation

```sh theme={"system"}
npm install @mixpanel/react-native-session-replay
```

or

```sh theme={"system"}
yarn add @mixpanel/react-native-session-replay
```

### Platform Setup

#### iOS

The SDK dependencies are automatically added via CocoaPods. Your project must target iOS 13 or later.

```sh theme={"system"}
cd ios && pod install
```

#### Android

Dependencies are automatically added through Gradle. Requirements:

* Minimum Android SDK 21+
* Kotlin support enabled

## Quick Start

Here's a minimal example to get started with Session Replay:

```typescript theme={"system"}
import {
  MPSessionReplay,
  MPSessionReplayConfig,
  MPSessionReplayMask,
} from "@mixpanel/react-native-session-replay";

// Initialize session replay
const config = new MPSessionReplayConfig({
  wifiOnly: false,
  recordingSessionsPercent: 100,
  autoStartRecording: true,
  autoMaskedViews: [MPSessionReplayMask.Image, MPSessionReplayMask.Text],
  flushInterval: 5,
  enableLogging: true,
});

await MPSessionReplay.initialize(token, distinctId, config).catch((error) => {
  console.error("Initialization error:", error);
});

// Control recording
await MPSessionReplay.startRecording();
await MPSessionReplay.stopRecording();

// Check recording status
const recording = await MPSessionReplay.isRecording();
```

## Data Residency

<Info>
  Available in React Native Session Replay SDK version `1.3.0` and later.
</Info>

If your Mixpanel project lives in the EU or India data center, or you route all Mixpanel traffic through a self-hosted proxy, set `serverURL` on `MPSessionReplayConfig`. The SDK exposes a `MPDataResidency` constant set with the managed region URLs so you don't have to hardcode them.

| Region       | `MPDataResidency` constant | URL                           |
| ------------ | -------------------------- | ----------------------------- |
| US (default) | `MPDataResidency.US`       | `https://api.mixpanel.com`    |
| EU           | `MPDataResidency.EU`       | `https://api-eu.mixpanel.com` |
| India        | `MPDataResidency.IN`       | `https://api-in.mixpanel.com` |

**Example Usage**

```typescript theme={"system"}
import {
  MPSessionReplay,
  MPSessionReplayConfig,
  MPDataResidency,
} from "@mixpanel/react-native-session-replay";

const config = new MPSessionReplayConfig({
  recordingSessionsPercent: 100,
  serverURL: MPDataResidency.EU,
});

await MPSessionReplay.initialize(token, distinctId, config);
```

You can also pass any fully-qualified HTTPS URL — useful when routing replay traffic through a self-hosted proxy:

```typescript theme={"system"}
const config = new MPSessionReplayConfig({
  serverURL: "https://mixpanel-proxy.yourcompany.com",
});
```

Learn more about [EU Data Residency](/docs/privacy/eu-residency) and [India Data Residency](/docs/privacy/in-residency).

## Configuration

The `MPSessionReplayConfig` class provides comprehensive control over session replay behavior:

```typescript theme={"system"}
const config = new MPSessionReplayConfig({
  wifiOnly: boolean,                // Default: true
  autoStartRecording: boolean,      // Default: true
  recordingSessionsPercent: number, // Default: 100 (range: 0-100)
  autoMaskedViews: MPSessionReplayMask[], // Default: all types
  flushInterval: number,            // Default: 10 (seconds)
  enableLogging: boolean,           // Default: false
});
```

### Configuration Options

| Option                     | Type                              | Default    | Description                                                                                                   |
| -------------------------- | --------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------- |
| `wifiOnly`                 | boolean                           | `true`     | Only transmit recordings over WiFi                                                                            |
| `autoStartRecording`       | boolean                           | `true`     | Automatically start recording on initialization                                                               |
| `recordingSessionsPercent` | number                            | `100`      | Percentage of sessions to record (0-100)                                                                      |
| `autoMaskedViews`          | MPSessionReplayMask\[]            | All types  | View types to automatically mask                                                                              |
| `flushInterval`            | number                            | `10`       | Interval in seconds to flush recordings                                                                       |
| `enableLogging`            | boolean                           | `false`    | Enable debug logging                                                                                          |
| `remoteSettingsMode`       | MPSessionReplayRemoteSettingsMode | `Disabled` | Setting for handling remote configuration during SDK initialization. Can be `Disabled`/ `Fallback`/ `Strict`. |

### Auto-Masked View Types

The `MPSessionReplayMask` enum defines view types that can be automatically masked:

```typescript theme={"system"}
enum MPSessionReplayMask {
  Text = "text", // Text inputs and labels
  Web = "web", // WebView content
  Map = "map", // Map views (iOS only)
  Image = "image", // Image components
}
```

**Example - Custom Auto-Masking:**

```typescript theme={"system"}
import {
  MPSessionReplayConfig,
  MPSessionReplayMask,
} from "mixpanel-react-native-session-replay";

// Only mask text inputs and images
const config = new MPSessionReplayConfig({
  autoMaskedViews: [MPSessionReplayMask.Text, MPSessionReplayMask.Image],
});
```

## API Reference

### initialize

Initialize the Session Replay SDK with your configuration.

```typescript theme={"system"}
initialize(
  token: string,
  distinctId: string,
  config: MPSessionReplayConfig
): Promise<void>
```

**Parameters:**

* `token` (required) - Your Mixpanel project token
* `distinctId` (required) - User identifier for the session
* `config` (required) - Session replay configuration

**Validation:**

* Token must be a non-empty string
* distinctId must be a non-empty string
* recordingSessionsPercent must be between 0 and 100

**Example:**

```typescript theme={"system"}
const config = new MPSessionReplayConfig({
  autoStartRecording: true,
  enableLogging: __DEV__, // Enable logging in development
});

try {
  await MPSessionReplay.initialize("YOUR_TOKEN", "user-123", config);
  console.log("Session Replay initialized");
} catch (error) {
  console.error("Failed to initialize:", error);
}
```

### startRecording

Start recording user interactions.

```typescript theme={"system"}
startRecording(): Promise<void>
```

**Example:**

```typescript theme={"system"}
await MPSessionReplay.startRecording();
```

### stopRecording

Stop recording user interactions.

```typescript theme={"system"}
stopRecording(): Promise<void>
```

**Example:**

```typescript theme={"system"}
await MPSessionReplay.stopRecording();
```

### isRecording

Check if session recording is currently active.

```typescript theme={"system"}
isRecording(): Promise<boolean>
```

**Returns:** Boolean indicating recording status

**Example:**

```typescript theme={"system"}
const recording = await MPSessionReplay.isRecording();
if (recording) {
  console.log("Session is being recorded");
}
```

### identify

Update the user identifier for the current recording session.

```typescript theme={"system"}
identify(distinctId: string): Promise<void>
```

**Parameters:**

* `distinctId` (required) - New user identifier

**Example:**

```typescript theme={"system"}
// Update user ID after authentication
await MPSessionReplay.identify("authenticated-user-456");
```

## Remote Configuration

<Note>
  Available in React Native Session Replay SDK version `1.2.0` and later. Requires a paid Session Replay add-on.
</Note>

You can set the `remote_settings_mode` for your project in Mixpanel under `Settings > Organization Settings > Session Replay`. Using this, you can quickly set SDK options remotely without needing to update your app. This allows you to adjust recording settings, such as sampling rates, on the fly based on your needs.

Three modes are available:

* `Disabled`: Do not use remote configuration and proceed to use the hardcoded initial options provided by the user during initialization. This is the default behavior.
* `Fallback`: Attempt to retrieve remote configuration and proceed with those settings. If there is failure or timeout (500 ms), we will use the previously cached remote settings (if one exists from the last successful fetch). If no existing remote settings are cached, we will use the values from the SDK initialization config.
* `Strict`: Requires successful remote configuration fetch for SDK initialization. If there is failure or timeout (500 ms), SDK initialization will fail and the Session Replay features will be unavailable for that app launch.

You can use this setting to quickly update and adjust configurations to your liking.

List of currently supported remote settings:

* `recordingSessionsPercent`

Settings not yet supported by remote configuration will use the value provided during initialization, or the default value if none was provided

## Privacy & Data Masking

Session Replay provides two approaches to protect sensitive data: automatic masking and manual masking.

### Automatic Masking

Configure which view types are automatically masked during initialization:

```typescript theme={"system"}
const config = new MPSessionReplayConfig({
  autoMaskedViews: [
    MPSessionReplayMask.Text, // Masks all text inputs
    MPSessionReplayMask.Image, // Masks all images
    MPSessionReplayMask.Web, // Masks all WebViews
    MPSessionReplayMask.Map, // Masks map views (iOS only)
  ],
});
```

**Default Behavior:** All view types are masked by default for maximum privacy.

### Manual Masking with MPSessionReplayView

Use the `MPSessionReplayView` wrapper component for granular control over what gets masked:

```typescript theme={"system"}
import { MPSessionReplayView } from 'mixpanel-react-native-session-replay';

// Mask sensitive content
<MPSessionReplayView sensitive={true}>
  <TextInput
    value={password}
    onChangeText={setPassword}
    secureTextEntry
  />
  <Text>Social Security Number: {ssn}</Text>
</MPSessionReplayView>

// Explicitly mark content as safe (not masked)
<MPSessionReplayView sensitive={false}>
  <Text>Public information that should always be visible</Text>
</MPSessionReplayView>
```

### Complete Masking Example

```typescript theme={"system"}
import React, { useState } from "react";
import { View, TextInput, Image, Text } from "react-native";
import { MPSessionReplayView } from "mixpanel-react-native-session-replay";
import { WebView } from "react-native-webview";

function ProfileScreen() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <View>
      {/* Public information - not masked */}
      <Text>Welcome to Your Profile</Text>

      {/* Sensitive user data - masked */}
      <MPSessionReplayView sensitive={true}>
        <View>
          <Text>Email: {email}</Text>
          <TextInput
            value={email}
            onChangeText={setEmail}
            placeholder="email@example.com"
          />

          <Text>Password:</Text>
          <TextInput
            value={password}
            onChangeText={setPassword}
            secureTextEntry
          />

          <Image source={{ uri: profilePhotoUrl }} />
        </View>
      </MPSessionReplayView>

      {/* WebView masked by default if Web type is in autoMaskedViews */}
      <WebView source={{ uri: "https://example.com/terms" }} />
    </View>
  );
}
```
