
{% callout type="note" heading="Session Replay instrumentation" %}
Session Replay isn't on by default, and requires setup beyond the standard Amplitude instrumentation.
{% /callout %}

This article covers Session Replay installation using the Browser SDK plugin. If your site already uses Amplitude instrumentation, use this option. If you use a provider other than Amplitude for in-product analytics, choose the [standalone implementation](/docs/sdks/session-replay/session-replay-standalone-sdk). For more information about the Browser SDK, go to [Browser SDK 2](/docs/sdks/analytics/browser/browser-sdk-2).

{% callout type="info" heading="Session Replay and performance" %}
Session Replay minimizes impact on the performance of the web pages where you install it by:

- Processing content asynchronously through webhooks for efficient compression and optimized bundle sizes.
- Batching requests and using lightweight compression to reduce network connections and bandwidth.
- Optimizing DOM processing.
{% /callout %}

### Bundle size

The Session Replay plugin adds to your application's bundle size.

For current bundle size information, check the [npm package page](https://www.npmjs.com/package/@amplitude/plugin-session-replay-browser) or [BundlePhobia](https://bundlephobia.com/package/@amplitude/plugin-session-replay-browser).

### Runtime performance

Session Replay runs asynchronously and processes replay data in the background to avoid blocking the main thread. Performance characteristics include:

- **DOM capture**: DOM snapshot capture typically adds less than 5ms of processing time for each page interaction. Initial page load snapshot capture may take 10-50ms depending on page complexity.
- **Memory usage**: Session Replay stores replay events in memory or IndexedDB (configurable using `storeType`). Memory usage scales with session length and page complexity, typically ranging from 1-10 MB for each active session.
- **CPU impact**: With default settings, Session Replay uses less than 2% of CPU time during normal operation. Session Replay defers compression operations to browser idle periods when `performanceConfig.enabled` is `true` (default).
- **Network bandwidth**: Session Replay compresses replay data before upload, typically reducing payload size by 60-80%. Session Replay batches network requests and sends them asynchronously.

### Performance optimization

To optimize Session Replay performance:

- Enable `useWebWorker`, which moves compression off the main thread and reduces CPU impact.
- Configure `performanceConfig.timeout` to control when deferred compression occurs.
- Set `storeType` to `memory` if you don't need persistence across page reloads, which reduces IndexedDB overhead.

For detailed performance testing results, go to the [Session Replay performance testing blog post](https://amplitude.com/blog/session-replay-performance-testing).

Session Replay captures changes to a page's Document Object Model (DOM), including elements in the shadow DOM. Session Replay then replays these changes to build a video-like replay. For example, at the start of a session, Session Replay captures a full snapshot of the page's DOM. As the user interacts with the page, Session Replay captures each change to the DOM as a diff. When you watch the replay of a session, Session Replay applies each diff back to the original DOM in sequential order to construct the replay. Session replays have no maximum length.

## Before you begin

The Session Replay Plugin requires that:

1. Your application is web-based.
2. You can provide a device ID to the SDK.
3. Your site uses the Browser 2.0 SDK.

### Supported browsers

Session Replay supports the same set of browsers as Amplitude's SDKs. For more information, refer to [Browser Compatibility](/docs/get-started/browser-compatibility).

Session Replay may not support all browser extensions or DOM elements that browser extensions introduce.

Session Replay supports Shadow DOM, but exceptions may exist depending on the frameworks your site uses.

## Quickstart

Install the plugin with npm or yarn.

{% callout type="info" heading="Unified SDK" %}
If you haven't installed the Browser SDK yet, consider using the [Browser Unified SDK](/docs/sdks/analytics/browser/browser-unified-sdk) instead. The Unified SDK provides a single entry point for all Amplitude features (Analytics, Session Replay, Experiment) and simplifies integration by handling initialization and configuration of all components.
{% /callout %}

{% code-group %}
```bash npm
# If you already have Browser SDK installed, install the Session Replay Plugin
npm install @amplitude/plugin-session-replay-browser --save

# OR if you haven't installed Browser SDK yet, use the Unified SDK instead
npm install @amplitude/unified
```

```bash yarn
# If you already have Browser SDK installed, install the Session Replay Plugin
yarn add @amplitude/plugin-session-replay-browser

# OR if you haven't installed Browser SDK yet, use the Unified SDK instead
yarn add @amplitude/unified
```
{% /code-group %}

Configure your application code.

{% code-group %}
```js Plugin configuration
import * as amplitude from "@amplitude/analytics-browser";
import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser";

// Create and Install Session Replay Plugin
const sessionReplayTracking = sessionReplayPlugin();
amplitude.add(sessionReplayTracking);

// Your existing initialization logic with Browser SDK
amplitude.init(API_KEY);
```

```js Unified SDK
import { initAll } from "@amplitude/unified";

// Initialize Unified SDK with Session Replay configuration
initAll("YOUR_API_KEY", {
  sessionReplay: {
    sampleRate: "<number>",
  },
});
```
{% /code-group %}

You can also add the code directly to the `<head>` of your site. With this method, make sure your application doesn't initialize the Browser SDK elsewhere. If you initialize the Browser SDK more than one time, you may experience mismatches in Device ID or Session ID.

```html
<script src="https://cdn.amplitude.com/libs/analytics-browser-2.44.1-min.js.gz"></script>
<script src="https://cdn.amplitude.com/libs/plugin-session-replay-browser-1.32.2-min.js.gz"></script>
<script>
  const sessionReplayTracking = window.sessionReplay.plugin();
  window.amplitude.add(sessionReplayTracking);
  window.amplitude.init(API_KEY);
</script>
```

{% callout type="info" heading="" %}
Session Replay instrumentation happens in the context of an Amplitude Project. Amplitude defines your replay quota at the Organization level. As a result, you can have multiple Session Replay implementations across multiple projects, each with its own sample rate, that pull from the same quota.
{% /callout %}

{% callout type="tip" heading="Compatibility with Google Tag Manager" %}
The Session Replay plugin scripts load asynchronously when you add them to the `<head>` tag of your page. As a result, this implementation isn't compatible with Google Tag Manager. For more information, go to [Session Replay Implementation with Google Tag Manager](/docs/sdks/session-replay/session-replay-google-tag-manager).
{% /callout %}

## Configuration

| Name                                    | Type      | Required | Default     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------------------------- | --------- | -------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sampleRate`                            | `number`  | No       | `0`         | Controls how many sessions to select for replay collection. The number is a decimal between 0 and 1, for example `0.4`, representing the fraction of sessions Amplitude randomly selects for replay collection. Over a large number of sessions, `0.4` selects `40%` of those sessions. This field isn't required because Session Replay supports [Remote Configuration](/docs/admin/account-management/account-settings#session-replay-settings) of settings including Sample Rate. |
| `privacyConfig`                         | `object`  | No       | `undefined` | Supports advanced masking configurations with CSS selectors.                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `applyBackgroundColorToBlockedElements` | `boolean` | No       | `false`     | If true, applies a background color to blocked elements for visual masking. This helps you see which elements Session Replay blocks from capture.                                                                                                                                                                                                                                                                                                                                    |
| `debugMode`                             | `boolean` | No       | `false`     | Adds an additional debug event property to help debug instrumentation issues (such as mismatching apps). Recommended only for debugging initial setup, not for production.                                                                                                                                                                                                                                                                                                           |
| `serverZone`                            | `string`  | No       | `US`        | EU or US. Sets the Amplitude server zone. Set this to EU for Amplitude projects in the EU data center.                                                                                                                                                                                                                                                                                                                                                                               |
| `configServerUrl`                       | `string`  | No       | `undefined` | The endpoint URL to fetch remote configuration. If provided, it overrides the default server zone configuration.                                                                                                                                                                                                                                                                                                                                                                     |
| `trackServerUrl`                        | `string`  | No       | `undefined` | The endpoint URL to send session replay data. If provided, Amplitude forwards requests from the SDK there instead of to the default Session Replay endpoint.                                                                                                                                                                                                                                                                                                                         |
| `shouldInlineStylesheet`                | `boolean` | No       | `true`      | If true, Session Replay stores the contents of inlined stylesheets. During replay, Session Replay uses the stored stylesheet instead of fetching it remotely. This prevents replays from appearing broken due to missing stylesheets. Inlining stylesheets may not work in all cases. If undefined, Session Replay inlines stylesheets.                                                                                                                                              |
| `storeType`                             | `string`  | No       | `idb`       | How Session Replay stores replay events. `idb` uses IndexedDB to persist replay events when Session Replay can't send all events during capture. `memory` stores replay events only in memory, so events are lost when the page closes. If IndexedDB is unavailable, the system falls back to memory.                                                                                                                                                                                |
| `performanceConfig.enabled`             | `boolean` | No       | `true`      | If enabled, Session Replay defers event compression to occur during the browser's idle periods.                                                                                                                                                                                                                                                                                                                                                                                      |
| `performanceConfig.timeout`             | `number`  | No       | `undefined` | Optional timeout in milliseconds for the requestIdleCallback API. If specified, this value sets a maximum time for the browser to wait before running the deferred compression task, even if the browser isn't idle.                                                                                                                                                                                                                                                                 |
| `useWebWorker`                          | `boolean` | No       | `false`     | Uses a web worker to compress replay events. This improves performance by moving compression off the main thread.                                                                                                                                                                                                                                                                                                                                                                    |

### API endpoints

Session Replay uses the following API endpoints:

- **Data ingestion**:
  - US: `https://api-sr.amplitude.com/sessions/v2/track`.
  - EU: `https://api-sr.eu.amplitude.com/sessions/v2/track`.
  - Session Replay sends captured replay data to these endpoints.
- **Remote configuration**:
  - US: `https://sr-client-cfg.amplitude.com/config`.
  - EU: `https://sr-client-cfg.eu.amplitude.com/config`.
  - Session Replay fetches remote configuration from these endpoints.

If you set up a domain proxy, forward requests to these endpoints. You can override these defaults using the `trackServerUrl` and `configServerUrl` configuration options.

### Track default session events

Session Replay enables session tracking by default. This ensures Session Replay captures Session Start and Session End events. If you didn't capture these events before you implement Session Replay, expect an increase in event volume. For more information about session tracking, go to [Browser SDK 2.0 | Tracking Sessions](/docs/sdks/analytics/browser/browser-sdk-2#track-sessions).

{% tabs tabs="SDK configuration, Plugin configuration" %}
{% tab name="SDK configuration" %}
Use the Browser SDK configuration to implicitly enable session tracking.

```js
amplitude.init(API_KEY, USER, {
  autocapture: {
    sessions: true,
  },
});
```

{% /tab %}
{% tab name="Plugin configuration" %}
Disable all default tracking by the Browser SDK. In this case, the plugin enables default session tracking.

```js
amplitude.init(API_KEY, USER, {
  autocapture: false,
});
```

{% /tab %}
{% /tabs %}

{% callout type="info" heading="Session Start and Session End events" %}
Starting with plugin version 1.12.1, Session Replay no longer captures `Session Start` and `Session End` events by default. To enable capture of these events, set `forceSessionTracking: true`:

```js
const sessionReplayTracking = window.sessionReplay.plugin({
  forceSessionTracking: true, // Enable capture of Session Start and Session End events
  sampleRate: 1, // 100% sample rate, should reduce for production traffic.
});
```

Amplitude requires at least one event in any captured session to enable playback of the replay.
{% /callout %}

### Mask on-screen data

{% partial file="session-replay/sr-mask-data.md" /%}

### User opt-out

The Session Replay plugin follows the Browser SDK's `optOut` setting and doesn't support user opt-outs on its own.

### Content Security Policy (CSP)

If your web application uses a strict Content Security Policy, add the following directives.

#### Required CSP directives

```text
script-src: https://cdn.amplitude.com;
connect-src: https://api-secure.amplitude.com;
worker-src: blob:;
```

#### CSP directives reference

| Directive     | Domain                             | Required                  | Description                                                                                           |
| ------------- | ---------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------- |
| `script-src`  | `https://cdn.amplitude.com`        | Yes, if using CDN         | Allows the Session Replay plugin and Browser SDK to load from Amplitude's CDN.                        |
| `connect-src` | `https://api-secure.amplitude.com` | Yes (US)                  | Allows the SDK to send replay data to Amplitude's US servers.                                         |
| `connect-src` | `https://api.eu.amplitude.com`     | Yes (EU)                  | Allows the SDK to send replay data to Amplitude's EU servers. Required if you set `serverZone: "EU"`. |
| `worker-src`  | `blob:`                            | Yes, if using web workers | Required if you enable the `useWebWorker` option for replay event compression.                        |

#### API endpoints

Session Replay sends data to the following endpoints:

| Region       | Endpoint                                           | Purpose                                      |
| ------------ | -------------------------------------------------- | -------------------------------------------- |
| US (default) | `https://api-secure.amplitude.com/sessions/track`  | Replay data ingestion.                       |
| EU           | `https://api.eu.amplitude.com/sessions/track`      | Replay data ingestion for EU data residency. |
| US (default) | `https://api-secure.amplitude.com/sessions/config` | Remote configuration (sample rate settings). |
| EU           | `https://api.eu.amplitude.com/sessions/config`     | Remote configuration for EU data residency.  |

#### Example CSP header

For the US region:

```text
Content-Security-Policy: script-src 'self' https://cdn.amplitude.com; connect-src 'self' https://api-secure.amplitude.com; worker-src 'self' blob:;
```

For EU data center:

```text
Content-Security-Policy: script-src 'self' https://cdn.amplitude.com; connect-src 'self' https://api.eu.amplitude.com; worker-src 'self' blob:;
```

{% callout type="tip" heading="" %}
If you use the `configServerUrl` or `trackServerUrl` configuration options to specify custom endpoints, add those domains to your `connect-src` directive instead.
{% /callout %}

### EU data residency

Session Replay is available to Amplitude customers who use the EU data center. Set the `serverZone` configuration option to `EU` during initialization. For example:

```js
// For European users, set the serverZone to "EU"
await sessionReplay.init(AMPLITUDE_API_KEY, {
  serverZone: "EU", // [tl! ~~]
}).promise;
```

### Sampling rate

By default, Session Replay captures 0% of sessions for replay. If you used Amplitude's new account snippet to instrument, sample rate defaults to `1` (100% of sessions) for easier testing. Update the sample rate from the [Session Replay settings page](/docs/admin/account-management/account-settings#session-replay-settings) or use the `sampleRate` configuration option to set the percentage of total sessions that Session Replay captures. For example:

```js
// This configuration samples 1% of all sessions
await sessionReplay.init(AMPLITUDE_API_KEY, {
  sampleRate: 0.01,
}).promise;
```

To set the `sampleRate`, consider the monthly quota on your Session Replay plan. For example, if your monthly quota is 2,500,000 sessions and you average 3,000,000 monthly sessions, your quota is 83% of your average sessions. In this case, to make sampling last through the month, set `sampleRate` to `.83` or lower.

Note the following as you consider your sample rate:

- When you reach your monthly session quota, Amplitude stops capturing sessions for replay.
- Session quotas reset on the first of every month.
- Use sample rate to distribute your session quota over the course of a month, rather than using your full quota at the beginning of the month.
- To find the best sample rate, Amplitude recommends that you start low, for example `.01`. If this value doesn't capture enough replays, raise the rate over a few days. For ways to monitor the number of session replays captured, refer to [View the number of captured sessions](/docs/session-replay).

Session Replay supports remote sampling rate settings. This lets users in your organization configure or update the sampling rate of your project after implementation, without a code change. If a conflict occurs, Session Replay defaults to the remote setting. For more information, refer to [Account Settings](/docs/admin/account-management/account-settings#session-replay-settings).

### Disable replay collection

After you enable Session Replay, it runs on your site until either:

- The user leaves your site.
- You call `amplitude.remove(sessionReplayTracking.name)`.

{% callout type="note" heading="" %}
These examples assume you use the variable `sessionReplayTracking` in your initialization code.
{% /callout %}

Call `amplitude.remove('sessionReplayTracking')` before a user navigates to a restricted area of your site to disable replay collection while the user is in that area.

To restart replay collection, call `amplitude.add(sessionReplayTracking)` to re-add the plugin.

{% callout type="note" %}
`amplitude.add()` takes an object of type `Plugin` as a parameter, and `amplitude.remove()` takes a string as a parameter, which is the name of the plugin you want to remove.
{% /callout %}

{% callout type="note" %}
Always wait for `amplitude.add()` to finish before you call `amplitude.remove()`. If you don't, you may get an error in the console: `TypeError: Cannot read properties of undefined (reading 'teardown')`. Use the `promise` property to do this, as shown in either of these examples:

```js
await amplitude.add(sessionReplayTracking).promise;
await amplitude.remove(sessionReplayTracking.name).promise;
```

```js
const addPromise = amplitude.add(sessionReplayTracking).promise;
addPromise.then(() => {
  amplitude.remove(sessionReplayTracking.name).promise;
});
```

{% /callout %}

You can also use a feature flag product like Amplitude Experiment to create logic that enables or disables replay collection based on criteria like location. For example, create a feature flag that targets a specific user group, and add it to your initialization logic:

```js
import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser";

// Your existing initialization logic with Browser SDK
amplitude.init(API_KEY);

if (nonEUCountryFlagEnabled) {
  // Create and Install Session Replay Plugin
  const sessionReplayTracking = sessionReplayPlugin({
    sampleRate: 0.5,
  });
  amplitude.add(sessionReplayTracking);
}
```

{% partial file="session-replay/sr-retention.md" /%}

### DSAR API

The Amplitude DSAR API returns metadata about session replays, but not the raw replay data.

Amplitude creates the [Amplitude] Replay Captured event automatically when Session Replay captures a replay. This event includes the [Amplitude] Session Replay ID property, which provides information about the replays collected for the user.

The session replay ID has the format `<deviceId>/<sessionId>`. If you use [custom session definitions](/docs/session-replay/session-matching#requirements-for-custom-session-definitions), the custom session ID value can't contain `/` and must use accepted characters: `a-z A-Z 0-9 _ - . | @ : =`. If you need an additional character, contact [Amplitude support](https://gethelp.amplitude.com/hc/en-us/requests/new).

```json
{
 "amplitude_id": 123456789,
 "app": 12345,
 "event_time": "2020-02-15 01:00:00.123456",
 "event_type": "first_event",
 "server_upload_time": "2020-02-18 01:00:00.234567",
 "device_id": "your device id",
 "user_properties": { ... },
 "event_properties": {
 "[Amplitude] Session Replay ID": "cb6ade06-cbdf-4e0c-8156-32c2863379d6/1699922971244"
 },
 "session_id": 1699922971244,
}
```

### Data deletion

Session Replay uses Amplitude's [User Privacy API](/docs/apis/analytics/user-privacy/) to handle deletion requests. Successful deletion requests remove all session replays for the specified user.

When you delete the Amplitude project on which you use Session Replay, Amplitude deletes that replay data.

### Bot filter

Session Replay uses the same [block filter](/docs/data/block-bot-traffic) that the Amplitude app provides. Session Replay doesn't block traffic based on event or user properties.

{% partial file="session-replay/sr-web-storage.md" /%}

### Cookies

Session Replay doesn't use cookies directly, and has no impact on cookie size. [Browser SDK](/docs/sdks/analytics/browser/browser-sdk-2) uses cookies for session management.

## Known limitations

Note the following limitations as you implement Session Replay:

- Session Replay doesn't stitch together replays from a single user across multiple projects. For example:
  - You instrument your marketing site and web application as separate Amplitude projects with Session Replay enabled in each.
  - A known user begins on the marketing site and logs in to the web application.
  - Amplitude captures both sessions.
  - The replay for each session is available to view in the host project.
- Session Replay can't capture the following HTML elements:
  - Canvas.
  - WebGL.
  - `object` tags including plugins like Flash, Silverlight, or Java. Session replay supports `object type="image"`.
  - Lottie animations.
  - Cross-origin `<iframe>` elements that don't load the Session Replay SDK with `crossOriginIframes.enabled: true` (for example, third-party embeds like Stripe or Google Maps). To capture first-party cross-origin iframes, go to [Cross-origin iframe recording](/docs/sdks/session-replay/cross-origin-iframes).
  - Assets that require authentication, like fonts, CSS, or images.
- Session Replay isn't compatible with ad blocking software.

### Multiple Amplitude instances

Session Replay supports attachment to a single instance of the Amplitude SDK. If your application uses more than one instance, make sure to start Session Replay on the instance that most relates to your project.

```html
<script>
 const sessionReplayTracking = window.sessionReplay.plugin();
  const instance = window.amplitude.createInstance();
  instance.add(sessionReplayTracking);
  instance.init(API_KEY);
<script>
```

## Troubleshooting

For more information about individual statuses and errors, go to the [Session Replay Ingestion Monitor](/docs/session-replay/ingestion-monitor).

### CSS styling doesn't appear in a replay

When Amplitude captures a replay, it doesn't download and store CSS files or other static assets that are part of your application or site. Session Replay stores references to these files and uses those references when it reconstructs the replay. In some situations, the styling in the replay may differ from your application for the following reasons:

- Assets on your site move or change name. This can happen when you deploy a new version of your application.
- Assets on your site are behind access controls that prevent Amplitude from fetching them.

To help resolve CSS loading issues:

- Ensure your domain is publicly accessible. If you work in a local environment, Amplitude may not have access to assets stored on `localhost`.
- Your CDN should keep track of old stylesheets for older replays. If the content of the same stylesheet changes over time, try to append a unique string or hash to the asset URL. For example, `stylesheet.css?93f8b89`.
- Add `app.amplitude.com` or `app.eu.amplitude.com` to the list of domains that your server's CORS configuration permits.
- Make external stylesheets accessible to Session Replay. To ensure Session Replay can capture external stylesheets, add the `crossorigin="anonymous"` attribute to the `<link rel="stylesheet">` elements in your code.

  This instructs the browser to load the CSS without sending credentials, which allows cross-origin access to the stylesheet rules. Without this attribute, browsers like Google Chrome block programmatic access to those rules (for example, attempts to read `stylesheet.cssRules` fail).

  Although your site appears correctly to users, these restrictions can prevent session replay tools from capturing the full styling information, which results in incomplete or broken visual playback.

### Capture sessions contain limited information

Amplitude creates the `[Amplitude] Replay Captured` event automatically when Session Replay captures a session. If you don't see this event in your implementation, replays may not appear correctly in Amplitude's analysis tools like Funnel Analysis, Segmentation, or Journeys charts. You can still find session replays on the Session Replay home page or the user profile page. Contact [Amplitude support](https://gethelp.amplitude.com/hc/en-us/requests/new) if you don't see this event.

If you use a method other than the Browser SDK to instrument your events, consider using the [Session Replay Standalone SDK](/docs/sdks/session-replay/session-replay-standalone-sdk/).

{% partial file="session-replay/sr-web-mismatch-plugin.md" /%}

### Session Replay processing errors

In general, replays should be available within minutes of ingestion. Delays or errors may result from one or more of the following:

- Mismatching API keys or Device IDs. This can happen if Session Replay and standard event instrumentation use different API keys or Device IDs.
- Session Replay references the wrong project.
- Short sessions. If a user bounces within a few seconds of initialization, the SDK may not have time to upload replay data.
- Page instrumentation. If Session Replay doesn't run on all pages a user visits, their session may not capture properly.
- Replays older than the set [retention period](#retention-period) (defaults to 30 days, or 90 days if you purchase extra volume).
