Skip to content

Latest commit

 

History

History
378 lines (273 loc) · 17.9 KB

File metadata and controls

378 lines (273 loc) · 17.9 KB
title Set Up Session Replay
sidebar_title Session Replay
sidebar_order 5
sidebar_section features
notSupported
description Learn how to enable Session Replay in your mobile app.

Session Replay helps you get to the root cause of an error or latency issue faster by providing you with a reproduction of what was happening in the user's device before, during, and after the issue. You can rewind and replay your application's state and see key user interactions, like taps, swipes, network requests, and console entries, in a single UI.

By default, our Session Replay SDK masks all text content, images, and user input, giving you heightened confidence that no sensitive data will leave the device. To learn more, see product docs.

Pre-requisites

Make sure your Sentry React Native SDK version is at least 6.5.0.

Install

If you already have the SDK installed, you can update it to the latest version with:

npm install @sentry/react-native --save
yarn add @sentry/react-native
pnpm add @sentry/react-native

Set Up

To set up the integration, add the following to your Sentry initialization.

import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  integrations: [Sentry.mobileReplayIntegration()],
});
import * as Sentry from '@sentry/react-native';
import { Platform } from 'react-native';

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  integrations: (integrations) => {
    if (Platform.OS === 'web') {
      integrations.push(Sentry.browserReplayIntegration());
    }
    integrations.push(Sentry.mobileReplayIntegration());
    return integrations;
  },
});

Verify

While you're testing, we recommend that you set to 1.0. This ensures that every user session will be sent to Sentry.

Once testing is complete, we recommend lowering this value in production. We still recommend keeping set to 1.0.

User Session

A user session starts when the Sentry SDK is initialized or when the application enters the foreground. The session will capture screen transitions, navigations, touches and other events until the application is sent to the background. If the application is brought back to the foreground within 30 seconds (default), the same replay_id will be used and the session will continue.

The session will be terminated if the application has spent in the background more than 30 seconds or when the maximum duration of 60 minutes is reached. You can adjust the session tracking interval to extend or shorten the duration of a single replay, depending on your needs. Note that if the application exits abnormally while running in the background, the session will also be terminated.

Replay Captures on Errors Only

If you prefer not to record an entire session, you can elect to capture a replay only if an error occurs. In this case, the integration will buffer up to one minute worth of events prior to the error being thrown. It will continue to record the session, following the rules above regarding session life and activity. Read the sampling section for configuration options.

Sampling

Sampling allows you to control how much of your website's traffic will result in a Session Replay. There are two sample rates you can adjust to get the replays relevant to you:

  1. - The sample rate for replays that begin recording immediately and last the entirety of the user's session.
  2. - The sample rate for replays that are recorded when an error happens. This type of replay will record up to a minute of events prior to the error and continue recording until the session ends.

Sampling begins as soon as a session starts. is evaluated first. If it's sampled, the replay recording will begin. Otherwise, is evaluated and if it's sampled, the integration will begin buffering the replay and will only upload it to Sentry if an error occurs. The remainder of the replay will behave similarly to a whole-session replay.

Ignore Certain Errors from Error Sampling

Once you've enabled , you can further customize which errors should trigger a replay capture by using the beforeErrorSampling callback. This is useful if you want to capture replays only for unhandled errors, or exclude certain error types from replay capture.

The beforeErrorSampling callback is called when an error occurs and receives the event and hint as arguments. Returning false will prevent the replay from being captured for that specific error.

import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  replaysOnErrorSampleRate: 1.0,
  integrations: [
    Sentry.mobileReplayIntegration({
      beforeErrorSampling: (event, hint) => {
        // Only capture replays for unhandled errors
        const isHandled = event.exception?.values?.some(
          exception => exception.mechanism?.handled === true
        );
        return !isHandled;
      },
    }),
  ],
});

Privacy

The SDK is recording and aggressively masking all text, images, and webviews by default. If your app has any sensitive data, you should only turn the default masking off after explicitly masking out any sensitive data, using the APIs described below. However, if you're working on a mobile app that doesn't contain any PII or private data, you can opt out of the default text and image-masking settings. To learn more about Session Replay privacy, read our docs.

If you are manually initializing native SDKs before JS, use Sentry React Native SDK version 6.15.1 or newer (includes Sentry Cocoa SDK version 8.52.1). For more details, please, see GH-4853.

To disable redaction altogether (not to be used on applications with sensitive data):

integrations: [
  // You can pass options to the mobileReplayIntegration function during init:
  Sentry.mobileReplayIntegration({
    maskAllText: false,
    maskAllImages: false,
    maskAllVectors: false,
  }),
]
integrations: (integrations) => {
  if (Platform.OS === 'web') {
    // You can pass options to the browserReplayIntegration function during init:
    integrations.push(Sentry.browserReplayIntegration({
      maskAllText: true,
      maskAllInputs: true,
    }));
  }
  // You can pass options to the mobileReplayIntegration function during init:
  integrations.push(Sentry.mobileReplayIntegration({
    maskAllText: false,
    maskAllImages: false,
    maskAllVectors: false,
  }));
  return integrations;
}

If you encounter any data not being redacted with the default settings, please let us know through a GitHub issue.

Screenshot Strategy (Android only)

Available in version 7.5.0 of the React Native SDK

The SDK offers two strategies for recording replays on Android: PixelCopy and Canvas.

PixelCopy uses Android's PixelCopy API to capture screenshots of the current screen and takes a snapshot of the view hierarchy within the same frame. The view hierarchy is then used to find the position of controls such as text boxes, images, labels, and buttons and mask them with a block that's drawn over these controls. This strategy has slightly lower performance overhead but may result in masking misalignments due to the asynchronous nature of the PixelCopy API. We recommend using this strategy for apps that do not have strict PII requirements or do not require masking functionality.

Canvas uses Android's custom Canvas API to redraw the screen contents onto a bitmap, masking all drawText and drawBitmap operations in the process to produce a masked screenshot. This strategy has a slightly higher performance overhead but provides more reliable masking. We recommend using this strategy for apps with strict PII requirements.

The Canvas screenshot strategy is currently experimental and does not support any masking options. When the screenshot strategy is set to Canvas, it will always mask all texts, input fields and images, disregarding any masking options set. If you need more flexibility with masking, switch back to PixelCopy.

You can change the strategy as follows:

integrations: [
  // You can pass options to the mobileReplayIntegration function during init:
  Sentry.mobileReplayIntegration({
    screenshotStrategy: 'canvas' // or 'pixelCopy' (default)
  }),
]

SurfaceView Capture (Android only)

By default, content rendered inside SurfaceView components (e.g. video players, map SDKs) appears as black or transparent regions in Session Replay. You can enable captureSurfaceViews to include this content in recordings.

This option is experimental. Masking granularity is at the SurfaceView level only — individual elements inside a SurfaceView cannot be masked separately. Only works with the pixelCopy screenshot strategy (the default). See the Android SurfaceView Capture docs for more details.

integrations: [
  Sentry.mobileReplayIntegration({
    captureSurfaceViews: true,
  }),
]

Network Details

Available in React Native SDK 8.15.0 and later

By default, Replay captures basic information about all outgoing HTTP requests in your application — URL, request and response body sizes, method, and status code. To limit the chance of collecting private data, request/response headers and bodies are not captured unless you explicitly opt in.

You opt in by listing the URLs you want enriched in networkDetailAllowUrls. Pick only URLs that are safe for capturing bodies and avoid any endpoints that may contain Personally Identifiable Information (PII).

Body and header content will be PII-sanitized server-side, based on object keys and values. Refer to Server-Side Scrubbing for more details.

Only XHR-based requests are currently supported (this covers axios and most popular HTTP clients on React Native). Native fetch body capture will be added in a follow-up.

The SDK exposes the following options on mobileReplayIntegration:

Key Type Default Description
networkDetailAllowUrls (string | RegExp)[] [] URL patterns to enable capture of request/response headers (and bodies, when networkCaptureBodies is true). String patterns use substring matching; RegExp is matched via .test(url).
networkDetailDenyUrls (string | RegExp)[] [] URL patterns to never enable capture for, even if an allow pattern matches them.
networkCaptureBodies boolean true Controls whether request and response bodies are captured for allow-listed URLs. Set to false to capture only headers. URLs only enter the capture path after being explicitly listed in networkDetailAllowUrls, so this default does not capture every request body. Aligned with the iOS and Android native SDK defaults.
networkRequestHeaders string[] [] Additional request header names to capture for allow-listed URLs, in addition to the defaults (Content-Type, Content-Length, Accept).
networkResponseHeaders string[] [] Additional response header names to capture for allow-listed URLs, in addition to the defaults (Content-Type, Content-Length, Accept).

Any URL matching the given pattern(s) will be enriched with headers and bodies:

import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  replaysSessionSampleRate: 1.0,
  replaysOnErrorSampleRate: 1.0,
  integrations: [
    Sentry.mobileReplayIntegration({
      networkDetailAllowUrls: ["https://api.example.com"],
    }),
  ],
});

String patterns use substring matching — any URL containing the string will match. For exact or more complex matches, pass a RegExp:

integrations: [
  Sentry.mobileReplayIntegration({
    networkDetailAllowUrls: [
      "api.example.com",                 // substring match
      /^https:\/\/api\.example\.com\/.*/, // regex match
    ],
    networkDetailDenyUrls: [/\/auth\//],  // never capture details for auth endpoints
  }),
]

Requests to a matching URL will include request and response bodies (unless you opt out with networkCaptureBodies: false) as well as the following default headers:

  • Content-Type
  • Content-Length
  • Accept

To capture additional headers, configure networkRequestHeaders and networkResponseHeaders. The defaults are always included:

integrations: [
  Sentry.mobileReplayIntegration({
    networkDetailAllowUrls: ["https://api.example.com"],
    networkRequestHeaders: ["Cache-Control", "X-My-Header"],
    networkResponseHeaders: ["Referrer-Policy", "X-Response-Header"],
  }),
]

If you want headers only — e.g. for endpoints where the body is too sensitive to record — disable body capture for the integration as a whole:

integrations: [
  Sentry.mobileReplayIntegration({
    networkDetailAllowUrls: ["https://api.example.com"],
    networkCaptureBodies: false,
  }),
]

Authorization-like headers (Authorization, Cookie, Set-Cookie, X-API-Key, X-Auth-Token, Proxy-Authorization) are always stripped, regardless of configuration. Captured bodies are truncated to ~150 KB; truncated payloads include a MAX_BODY_SIZE_EXCEEDED warning. Binary bodies (Blob, ArrayBuffer, typed arrays) are skipped with an UNPARSEABLE_BODY_TYPE warning instead of being inlined.

React Component Names

Sentry helps you capture your React components and unlock additional insights in your application. You can set it up to use React component names.

So instead of looking at this:

View > Touchable > View > Text

You can also see exactly which React component was used, like:

MyCard (View, MyCard.ts) > MyButton (Touchable, MyCard.ts) > View > Text

To add React Component Names use annotateReactComponents in metro.config.js.

const { getDefaultConfig } = require("@react-native/metro-config");
const { withSentryConfig } = require("@sentry/react-native/metro");
module.exports = withSentryConfig(getDefaultConfig(__dirname), {
  annotateReactComponents: true,
});
const { getSentryExpoConfig } = require("@sentry/react-native/metro");
const config = getSentryExpoConfig(__dirname, {
  annotateReactComponents: true,
});

Error Linking

Errors that happen while a replay is running will be linked to the replay, making it possible to jump between related issues and replays. However, it's possible that in some cases the error count reported on the Replays Details page won't match the actual errors that have been captured. That's because errors can be lost, and while this is uncommon, there are a few reasons why it could happen:

  • The replay was rate-limited and couldn't be accepted.
  • The replay was deleted by a member of your org.
  • There were network errors and the replay wasn't saved.

Troubleshooting

Crashes During View Hierarchy Traversal on iOS

Supported in React Native SDK v7.9.0 and later

When capturing session replays on iOS, the SDK traverses the view hierarchy to capture screenshots and view information. Some view hierarchies may contain problematic views that can cause crashes during traversal. You can prevent these crashes by filtering which views are included or excluded from traversal. Use includedViewClasses to only traverse specific view classes (only views that are instances of these classes or their subclasses will be traversed), or excludedViewClasses to skip problematic view classes (views of these classes or their subclasses will be skipped entirely, including all their children). If both includedViewClasses and excludedViewClasses are set, excludedViewClasses takes precedence: views matching excluded classes won't be traversed even if they match an included class.

import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  integrations: [
    Sentry.mobileReplayIntegration({
      includedViewClasses: ['UILabel', 'UIView', 'MyCustomView'],
      excludedViewClasses: ['WKWebView', 'UIWebView'],
    }),
  ],
});

For more information, see the Ignore View Types from Subtree Traversal section in the iOS documentation.