How to add session replay to a React Native app

Record a synthetic report export in React Native, pause recording, and verify masking in the processed replay. The app keeps report exports usable before recording starts.

  • React Native 0.88
  • Community CLI
  • Replay plugin 0.5.12
  • 30 min

Chris Tam · Last updated 11 November 2026

React Native needs a native recorder to show what happens inside the app. I use Amplitude session replay to inspect a report export while protecting the synthetic private label and note on the same screen.

In this tutorial, you'll install the replay plugin, add recording controls, mask native views, and check a processed recording on Android and iOS.

A native usage report with Start demo, Export report and Pause recording controls, a masked label, a masked input and a blocked panel. Report Exported stays in analytics after replay is paused.

Prerequisites

  • React Native 0.88.0 and React 19.3.0 with the New Architecture. Node.js 22.13+ in the 22.x series, 24.3+ in the 24.x series, or 26+; Corepack and pnpm 10.33.2.
  • An Android device/emulator and its development tools, or macOS with Xcode, an iOS device/simulator, Bundler and CocoaPods. Follow React Native environment setup.
  • A separate Amplitude development project, its public project API key from Settings > Projects > your project > General, and its US or EU data center. The app uses a fixed synthetic test identity; host apps use verified authentication.
  • Access and allowance for session replay. Use a bare native project or an Expo development/native build, not Expo Go.

Sign up for Amplitude if you need a project, and compare plans for your product allowances. Use synthetic data throughout this walkthrough.

1. Create the native app and install dependencies

I use the Community CLI to create the native Android and iOS projects. This page includes the complete custom files for a fresh app; another Build tutorial is optional context. In an existing app, merge dependencies and instrumentation into the current project while preserving its framework, native settings, authentication, routing and enabled products.

The mobile SDK quickstart supplies Analytics and AsyncStorage. The product SDK reference supplies the plugin. The standalone app pins released versions for reproducibility.

Terminal
mkdir -p amplitude-react-native/tooling
tooling/package.json
{
  "name": "react-native-build-tooling",
  "private": true,
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8"
}
tooling/pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
Terminal
cd amplitude-react-native/tooling
pnpm --config.minimumReleaseAge=10080 --config.trustPolicy=no-downgrade dlx @react-native-community/cli@20.2.0 init AmplitudeReports --version 0.88.0 --skip-install --skip-git-init
cd AmplitudeReports

Keep the generated android/, ios/ and Gemfile. The CLI separately downloads its native template; the pnpm safeguards govern the fetched CLI package and the app dependency install, not that internal template download. Save the following files in AmplitudeReports.

Terminal
mkdir -p src __tests__
package.json
{
  "name": "AmplitudeReports",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "typecheck": "tsc --noEmit",
    "bundle:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output artifacts/index.android.bundle --assets-dest artifacts/android",
    "bundle:ios": "react-native bundle --platform ios --dev false --entry-file index.js --bundle-output artifacts/main.jsbundle --assets-dest artifacts/ios"
  },
  "dependencies": {
    "react": "19.3.0",
    "react-native": "0.88.0",
    "@react-native/new-app-screen": "0.88.0",
    "react-native-safe-area-context": "^5.5.2",
    "@amplitude/analytics-react-native": "1.13.0",
    "@react-native-async-storage/async-storage": "2.1.2",
    "@amplitude/plugin-session-replay-react-native": "0.5.12"
  },
  "devDependencies": {
    "@babel/core": "^7.25.2",
    "@babel/preset-env": "^7.25.3",
    "@babel/runtime": "^7.25.0",
    "@react-native-community/cli": "20.2.0",
    "@react-native-community/cli-platform-android": "20.2.0",
    "@react-native-community/cli-platform-ios": "20.2.0",
    "@react-native/babel-preset": "0.88.0",
    "@react-native/jest-preset": "0.88.0",
    "@react-native/metro-config": "0.88.0",
    "@react-native/typescript-config": "0.88.0",
    "@types/jest": "^29.5.13",
    "@types/react": "^19.2.0",
    "@types/react-test-renderer": "^19.1.0",
    "jest": "^29.6.3",
    "react-test-renderer": "19.3.0",
    "typescript": "^6.0.3"
  },
  "engines": {
    "node": "^22.13.0 || ^24.3.0 || >=26.0.0",
    "pnpm": ">=10.21.0"
  },
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8"
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
nodeLinker: hoisted
overrides:
  "semver@6.3.1": "7.8.5"
.gitignore
node_modules/
artifacts/
.env*
ios/Pods/
android/.gradle/
android/app/build/
app.json
{
  "name": "AmplitudeReports",
  "displayName": "AmplitudeReports"
}
index.js
/**
 * @format
 */

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);
babel.config.js
module.exports = {
  presets: ['module:@react-native/babel-preset'],
};
metro.config.js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('@react-native/metro-config').MetroConfig}
 */
const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);
tsconfig.json
{
  "extends": "@react-native/typescript-config",
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["**/node_modules", "**/Pods"]
}
jest.config.js
module.exports = {
  preset: '@react-native/jest-preset',
};

The workspace retains the explicit semver 6.3.1 to 7.8.5 override tested with this scaffold. Retest that major-version override when updating Babel or React Native. Optional template lint tooling is omitted; preserve your lint setup in an existing app. Keep release-age and trust safeguards enabled if installation reports a dependency problem.

Terminal
pnpm install
# Commit the generated pnpm-lock.yaml; repeat installs with:
pnpm install --frozen-lockfile

2. Configure one client and the product plugin

I keep the project key in one explicit client configuration file. Project API keys ship in a mobile binary; secret management and server deployment keys stay on the backend. Set apiKey and serverZone for the development project. The fixed demoUserId identifies synthetic activity only. Replace it with the confirmed account from your authentication system when merging into a signed-in app.

src/amplitude-config.ts
// Public client configuration for a separate development project.
// Never put a secret management key in a mobile application.
export const config = {
  "apiKey": "",
  "serverZone": "US" as "US" | "EU",
  "demoUserId": "build-rn-session-replay-demo"
};
src/instrumentation.ts
// Merge into the existing client when extending another React Native Build page.
import * as amplitude from '@amplitude/analytics-react-native';
import {SessionReplayPlugin} from '@amplitude/plugin-session-replay-react-native';
import {config} from './amplitude-config';

let ready: Promise<boolean> | undefined;
let replay: SessionReplayPlugin | undefined;

export function startDemo(): Promise<boolean> {
  if (!ready) {
    ready = (async () => {
      if (!config.apiKey.trim() || !['US', 'EU'].includes(config.serverZone)) return false;
      await amplitude.init(config.apiKey, config.demoUserId, {
        serverZone: config.serverZone,
        autocapture: false,
      }).promise;
      replay = new SessionReplayPlugin({
        sampleRate: 1,
        autoStart: false,
        enableRemoteConfig: true,
        privacyConfig: {maskLevel: 'medium'},
      });
      await amplitude.add(replay).promise;
      await replay.start();
      return true;
    })().catch(() => false);
  }
  return ready;
}

export async function pauseReplay(): Promise<void> {
  await replay?.stop();
}

export async function recordExport(): Promise<void> {
  if (ready && await ready) {
    void amplitude.track('Report Exported', {report_type: 'usage', days: 7}).promise.catch(() => undefined);
  }
}

export function deviceId(): string | undefined {
  return amplitude.getDeviceId();
}

The shared ready promise prevents parallel Start actions from creating more than one client. A blank configuration leaves the local report usable. Failed setup stays failed until an app restart; check SDK logs and fix the configuration before retrying. An initialization promise is a local ordering signal, not proof of ingestion or a native product result.

The plugin takes the Analytics region and identity. Set privacyConfig.maskLevel with the lowercase value medium for this pinned release. AmpMaskView controls individual native regions in the next step. Keep autoStart false and request start only after the test control is used.

The report ScrollView keeps keyboardShouldPersistTaps set to handled so its buttons receive taps while the note or preview field has focus. React Native documents this keyboard behavior.

MCP. An optional Amplitude MCP connection can help your coding agent inspect existing event names. It uses account permissions independently of this app's ingestion key. Keep an established Report Exported event name if your project already has one.

3. Add the native report screen

I keep local report behavior independent of uploads. Save this complete screen for the standalone app. For an existing application, merge its controls into the current screen and preserve the current root, navigation and lifecycle handlers.

App.tsx
import React, {useState} from 'react';
import {Button, ScrollView, Text, TextInput, View} from 'react-native';
import {SafeAreaProvider, SafeAreaView} from 'react-native-safe-area-context';
import {AmpMaskView} from '@amplitude/plugin-session-replay-react-native';
import {deviceId, pauseReplay, recordExport, startDemo} from './src/instrumentation';

export default function App() {
  const [status, setStatus] = useState('Demo stopped. Use synthetic data only.');
  const [busy, setBusy] = useState(false);
  const [active, setActive] = useState(false);
  const [exports, setExports] = useState(0);
  async function start() {
    if (busy || active) return;
    setBusy(true);
    try {
      const enabled = await startDemo();
      setActive(enabled);
      setStatus(enabled ? `Replay requested; device ${deviceId()}. Check the processed recording.` : 'Check configuration, native linking and SDK logs, then restart.');
    } finally { setBusy(false); }
  }
  async function pause() {
    setBusy(true);
    try {
      await pauseReplay();
      setStatus('Pause requested. Analytics remains active.');
    } catch { setStatus('Pause failed. Stop the test and check native logs.'); }
    finally { setBusy(false); }
  }
  return <SafeAreaProvider><SafeAreaView style={{flex: 1, backgroundColor: '#FFFFFF'}}>
    <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{padding: 24, gap: 16}}>
      <Text style={{fontSize: 28, color: '#000000'}}>Usage report</Text>
      <Text>84 synthetic report actions in seven days.</Text>
      <Button title="Start demo" onPress={() => {void start();}} disabled={busy || active} />
      <Button title="Export report" onPress={() => {setExports(n => n + 1); void recordExport();}} />
      <Text>Local exports: {exports}</Text>
      <AmpMaskView mask="amp-mask" style={{alignSelf: 'stretch'}}>
        <Text>SYNTHETIC PRIVATE LABEL</Text>
      </AmpMaskView>
      <TextInput accessibilityLabel="Synthetic note" defaultValue="SYNTHETIC INPUT ONLY" />
      <AmpMaskView mask="amp-block" style={{height: 60, alignSelf: 'stretch'}}>
        <View><Text>SYNTHETIC EXCLUDED PANEL</Text></View>
      </AmpMaskView>
      <Button title="Pause recording" onPress={() => {void pause();}} disabled={!active || busy} />
      <Text accessibilityRole="alert">{status}</Text>
    </ScrollView>
  </SafeAreaView></SafeAreaProvider>;
}

AmpMaskView is a native layout node. Keep sizing constraints on each wrapper; the blocked panel has an explicit height. The example uses only synthetic text and never adds note values to Report Exported.

4. Configure the development project

I check the development project's replay access and quota, then open Settings > Organizational Settings > Session Replay Settings. An Admin or Manager enables session capture for this project. Confirm its sampling settings: a remote value can override the local development rate.

Development check
Project: separate development project
Identity: build-rn-session-replay-demo
Data: synthetic labels and notes only
Local sample rate: 1 during testing
Recording: starts only after Start demo

Open the native app and choose Start demo. The action initializes Analytics, installs the plugin, then requests recording. It also starts sending this demo's analytics events. It is a test control; connect your actual consent lifecycle before recording real users. Confirm a replay is captured instead of treating the status message as proof.

Tap Export report twice, edit the synthetic note, and tap Pause recording. Export once more. The analytics event remains active; pausing recording is different from opting out of all analytics. After checking the recording, lower the local or remote test sample rate to your intended production rate.

5. Check and run the native app

I include focused tests for the JavaScript adapter. They mock SDK boundaries, so they test application ordering and event decisions without real keys or native services. Native capture, flag evaluation and saved survey responses require the separate verification below.

__tests__/instrumentation.test.ts
function setup(key = 'synthetic-key', zone = 'EU') {
  jest.resetModules();
  const calls: string[] = [];
  const analytics = {
    init: jest.fn(() => {calls.push('init'); return {promise: Promise.resolve()};}),
    add: jest.fn(() => {calls.push('add'); return {promise: Promise.resolve()};}),
    track: jest.fn(() => ({promise: Promise.resolve({code: 200})})),
    getDeviceId: jest.fn(() => 'synthetic-device'), getUserId: jest.fn(() => 'synthetic-user'),
  };
  jest.doMock('@amplitude/analytics-react-native', () => analytics);
  jest.doMock('../src/amplitude-config', () => ({config: {
    apiKey: key, serverZone: zone, demoUserId: 'synthetic-user', deploymentKey: 'synthetic-deployment', flagKey: 'report-layout',
  }}));
  const replay = {start: jest.fn(async () => {calls.push('start');}), stop: jest.fn(async () => undefined)};
  const Constructor = jest.fn(() => replay);
  jest.doMock('@amplitude/plugin-session-replay-react-native', () => ({SessionReplayPlugin: Constructor}));
  const api = require('../src/instrumentation');
  return {api, calls, analytics, replay, Constructor};
}
test('missing keys and invalid region leave exports usable without initializing', async () => {
  for (const args of [['', 'US'], ['synthetic-key', 'invalid']]) {
    const x = setup(...args); expect(await x.api.startDemo()).toBe(false);
    await x.api.recordExport(); expect(x.analytics.init).not.toHaveBeenCalled();
  }
});
test('concurrent Start initializes once and installs replay after analytics', async () => {
  const x = setup(); await Promise.all([x.api.startDemo(), x.api.startDemo()]);
  expect(x.calls).toEqual(['init', 'add', 'start']);
  expect(x.Constructor).toHaveBeenCalledWith(expect.objectContaining({autoStart: false, privacyConfig: {maskLevel: 'medium'}}));
  expect(x.analytics.init).toHaveBeenCalledWith('synthetic-key', 'synthetic-user', expect.objectContaining({serverZone: 'EU'}));
});
test('pause stops replay while the export event still uses analytics and omits private input', async () => {
  const x = setup(); await x.api.startDemo(); await x.api.pauseReplay(); await x.api.recordExport();
  expect(x.replay.stop).toHaveBeenCalledTimes(1);
  expect(x.analytics.track).toHaveBeenCalledWith('Report Exported', {report_type: 'usage', days: 7});
});
test('failed initialization stays failed until restart instead of adding duplicate clients', async () => {
  const x = setup(); x.analytics.init.mockImplementation(() => ({promise: Promise.reject(new Error('synthetic failure'))}));
  expect(await x.api.startDemo()).toBe(false); expect(await x.api.startDemo()).toBe(false);
  expect(x.analytics.init).toHaveBeenCalledTimes(1); expect(x.Constructor).not.toHaveBeenCalled();
});
Terminal
pnpm typecheck
pnpm test --runInBand
mkdir -p artifacts
pnpm bundle:android --max-workers 2
pnpm bundle:ios --max-workers 2

Metro bundles check the JavaScript graph for both platforms. They do not compile the Android or iOS native project. Build a native app after installing the plugin; Fast Refresh cannot link new native modules.

Terminal, Android
pnpm start
# In another terminal inside AmplitudeReports:
pnpm android
Terminal, iOS on macOS
bundle install
cd ios
bundle exec pod install
cd ..
pnpm start
# In another terminal inside AmplitudeReports:
pnpm ios

Verify it worked

  1. With a blank key, tap Export report. The local count changes and no SDK initialization is requested. Add the development key and selected region, then restart the app.
  2. Tap Start demo, export twice, edit the synthetic note and request Pause recording. Inspect native SDK logs for configuration or linking failures. A successful JavaScript call does not prove capture.
  3. Find build-rn-session-replay-demo in Amplitude's user event stream and confirm Report Exported. Use the session time and replay association to find the matching recording; replays are generally available about five minutes after a session begins.
  4. Inspect the processed recording on both Android and iOS. Confirm the report actions appear, the private label and input value are hidden, and the excluded panel's contents are absent. Android and iOS use different masked representations, so do not expect identical pixels.
  5. Check the post-pause export separately. Its analytics event should arrive; new replay capture should stop after the pause request completes. Also test background/reopen and your real consent flow before rollout.

Test masked regions without putting amp-unmask inside a masked parent. Android and iOS resolve nested markers differently. A native wrapper, local test, upload response or replay ID cannot establish that sensitive content was removed from the processed recording.

Troubleshooting

The replay plugin is missing. Install dependencies, run CocoaPods on iOS and rebuild the native binary. Fast Refresh cannot add a missing native module; Expo Go cannot run this setup.

The app compiles but the replay is empty. Check project capture, remote sampling, remaining quota, native SDK logs and processing time. The Start demo status means recording was requested.

A wrapped region changed size. AmpMaskView participates in native layout. Keep the width, height or flex constraints on the wrapper, as shown for the blocked panel.

Android and iOS show different masked areas. Check both platforms. A masked iOS parent wins over nested markers; Android uses the nearest explicit marker. Keep visible regions outside masked parents.

An event still arrives after pause. Pause controls replay capture. This demo intentionally keeps Report Exported in analytics; use your application consent and opt-out policy when stopping all collection.

FAQ

Does this use the browser replay SDK?

This app uses the native React Native replay plugin. Browser DOM selectors and browser replay privacy options do not configure native views.

Can I add this to the existing analytics tutorial?

Yes. Reuse its Analytics client and ready promise. Add the replay plugin after initialization, preserve its authentication and events, and merge the AmpMaskView wrappers and controls into the existing screen.

Does this support Expo Go?

No. The plugin includes native code. Use a bare React Native app or a development/native Expo build and rebuild after installation.

Full code reference

Steps 1 through 3 and the test file in step 5 contain every custom file for this standalone project. The Community CLI supplies the native scaffold and Gemfile. Keep the generated lockfile with the project. The public Amplitude React Native examples provide additional SDK examples; this report screen is the complete implementation shown above.

Hand it to your agent

Give the agent the complete files above and this bounded implementation request.

Agent prompt
Implement this complete React Native report example. Read the current official docs and report source URLs. Inspect the existing app, package manager, native settings, authentication, consent and Amplitude integrations before changing files. Preserve its single Analytics client and existing functionality; do not replace a host app with this standalone scaffold. Use @amplitude/plugin-session-replay-react-native 0.5.12 after the existing analytics client initializes. Use privacyConfig.maskLevel with a lowercase string, not a runtime MaskLevel enum. Keep autoStart false, await start/stop, and use AmpMaskView for private native views. Preserve wrapper layout. Keep exports functional before capture; never send form values as event properties. Verify native processed masking on both Android and iOS; never infer it from Metro or mocked tests. Keep the pnpm integrity pin, age/trust settings, lockfile and native rebuild requirements. Never reset identity during anonymous startup or an unresolved login. Report type checks, mocked tests, Metro bundles, native compilation and live product outcomes separately. If sources disagree, record both statements and pause the affected claim until released SDK evidence or its owner resolves it.

What this unlocks

Product analytics records Report Exported under the same test identity as this integration. Keep that event and its properties consistent when connecting the native experience to your report workflow.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Build the native experience, then verify it

Connect your development project and check the real native result before rolling out the integration.