Instrument and configure Browser Session Replay

このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。

After Session Replay records its first test session, use these tasks to control which sessions it records, mask sensitive content, match replays to events, control uploads, reduce performance cost, and set up single-page apps and server-rendered frameworks. Each task applies to both the plugin (@amplitude/plugin-session-replay-browser) and the standalone SDK (@amplitude/session-replay-browser) unless it says Plugin only or Standalone only. Plugin examples assume you imported Browser SDK 2 as amplitude. Standalone examples assume you imported the SDK as sessionReplay. For signatures and every option, go to the reference. For changes in each release, go to the Session Replay Browser SDK release notes.

Control capture

How the SDK decides what to record

When it starts, and again when the session changes, the SDK fetches its remote configuration: the settings your team manages in Amplitude. Remote settings and code options combine like this:

  • The request fails or times out. The SDK doesn't record, so it never records without the privacy settings your team set in Amplitude. It waits 1.5 seconds for the response.
  • The project has no sampling settings. The SDK records with the sampleRate in your code.
  • The project sets a sample rate. That rate replaces sampleRate in your code.
  • The project uses targeted capture. Targeting conditions decide instead of the sample rate.
  • The project sets privacy settings. They combine with privacyConfig in your code. Where both set the same thing, the project setting wins. Go to How masking works.

The SDK then checks opt-out, and finally the sample rate. To see each decision, go to Check whether the session was selected.

Set the sample rate

sampleRate is the fraction of sessions to record, from 0 to 1. It defaults to 0, which records nothing. 0.01 records about 1% of sessions, and rates as small as 0.000001 work.

ts
amplitude.add(sessionReplayPlugin({ sampleRate: 0.01 }));
amplitude.init("AMPLITUDE_API_KEY");

The SDK selects a session from a hash of its session ID, so every page and tab in the same session gets the same decision. A sample rate set in Session Replay settings replaces the value in code. To plan rates against your replay quota, go to Configure Session Replay sampling.

Capture targeted sessions

To record sessions that match events, user properties, or page URLs instead of a random sample, set up targeted capture in Amplitude. The plugin evaluates targeting on every Browser SDK 2 event. With the standalone SDK, pass the inputs yourself with evaluateTargetingAndCapture():

ts
await sessionReplay.evaluateTargetingAndCapture({
  event: { event_type: "Checkout Started" },
  page: { url: window.location.href },
});

After a session matches, it stays matched until the session ends.

Pause and resume recording

To stop recording in a restricted area of your site, such as an account settings page, pause recording, then resume it when the user leaves that area. Pausing sends what the SDK already recorded.

Keep a reference to the plugin, and call its methods:

ts
const sessionReplayTracking = sessionReplayPlugin({ sampleRate: 1 });
amplitude.add(sessionReplayTracking);
amplitude.init("AMPLITUDE_API_KEY");

// Entering a restricted area
sessionReplayTracking.stop();

// Leaving it
await sessionReplayTracking.start();

To remove Session Replay from the page, remove the plugin by its name. To turn it back on, add the same plugin object again.

ts
await amplitude.remove(sessionReplayTracking.name).promise;
await amplitude.add(sessionReplayTracking).promise;

sessionReplayTracking.name is @amplitude/plugin-session-replay-browser. Passing any other string to remove() does nothing.

start() and stop() require version 1.49.0 or later (plugin 1.34.0). start() still respects the sample rate, targeting, and opt-out.

To record only some users, add the plugin or call the standalone init() only when a condition holds, such as a feature flag:

ts
if (recordReplaysForThisUser) {
  amplitude.add(sessionReplayPlugin({ sampleRate: 0.5 }));
}
amplitude.init("AMPLITUDE_API_KEY");

Opt users out

Plugin: the plugin follows the Browser SDK 2 opt-out setting and has no opt-out setting of its own. When a user opts out with amplitude.setOptOut(true), the plugin stops recording immediately. After the user opts back in with amplitude.setOptOut(false), recording resumes on the next page load.

Standalone: pass optOut: true to init():

ts
await sessionReplay.init("AMPLITUDE_API_KEY", {
  deviceId: "device-abc123",
  sessionId: 1735689600000,
  sampleRate: 0.01,
  optOut: true,
}).promise;

For consent banners and regional rules, go to Best practices for managing user consent.

Track Session Start and Session End events

Plugin only. The plugin doesn't change which events Browser SDK 2 tracks. Browser SDK 2 tracks Session Start and Session End events by default. If you turned them off, for example with autocapture: false, set forceSessionTracking: true to turn session events back on:

ts
amplitude.add(
  sessionReplayPlugin({ sampleRate: 1, forceSessionTracking: true }),
);
amplitude.init("AMPLITUDE_API_KEY", { autocapture: false });

Session events add to your event volume. Plugin versions before 1.12.1 turned them on by default.

Mask data

How masking works

Session Replay masks content in the browser, before it uploads anything. Masked text becomes asterisks: each character except spaces becomes *. Blocked elements become empty placeholders of the same size.

The mask level sets the default for the whole page:

For each element, the first rule that applies wins:

  1. amp-mask class or data-amp-mask attribute on the element or an ancestor, then privacyConfig.maskSelector.
  2. amp-unmask class or data-amp-unmask attribute, then privacyConfig.unmaskSelector.
  3. The mask level for the current page, from privacyConfig.urlMaskLevels, then the default mask level.

Blocking with amp-block, data-amp-block, or privacyConfig.blockSelector removes the element's content in every case.

Session Replay privacy settings in Amplitude combine with privacyConfig. The project's mask level replaces defaultMaskLevel, and when a selector appears in both, the project's rule wins.

Mask, unmask, and block elements in HTML

Add a class or a data attribute to the element. Data attributes are useful when a build step renames your classes.

html
<p class="amp-mask">Jane Doe</p>
<input class="amp-unmask" name="city">
<div data-amp-block>...</div>

Mask elements with CSS selectors

Set privacyConfig to choose elements without changing your HTML. Each selector list accepts any CSS selector: a tag, a class, an ID, or an attribute.

ts
amplitude.add(
  sessionReplayPlugin({
    sampleRate: 1,
    privacyConfig: {
      defaultMaskLevel: "medium",
      maskSelector: [".account-name", "[data-pii]"],
      unmaskSelector: ["#search"],
      blockSelector: [".payment-form", "#ads"],
    },
  }),
);
amplitude.init("AMPLITUDE_API_KEY");

A selector the browser can't parse doesn't stop recording. When the project also has privacy settings in Amplitude, the SDK drops the selector and logs a warning: [session-replay-browser] omitting selector "<selector>" because it is invalid. Test new selectors in the browser console with document.querySelectorAll().

The SDK records attribute values, such as alt, placeholder, or aria-label, as written. To mask an attribute, list its name in privacyConfig.maskAttributes. The SDK then masks that attribute on every element whose text it masks: inputs at the medium level, every element at the conservative level, and elements you mask with amp-mask or maskSelector. Requires version 1.34.0 or later (plugin 1.36.0).

ts
privacyConfig: {
  maskAttributes: ["alt", "aria-label"],
  maskSelector: [".account-avatar"],
},

Set a mask level for specific pages

Standalone only. Use privacyConfig.urlMaskLevels to apply a stricter or looser level on some pages. The SDK uses the first rule whose match pattern matches the page URL, and the default level elsewhere. Requires version 1.37.0 or later.

ts
await sessionReplay.init("AMPLITUDE_API_KEY", {
  deviceId: "device-abc123",
  sessionId: 1735689600000,
  sampleRate: 1,
  privacyConfig: {
    defaultMaskLevel: "medium",
    urlMaskLevels: [
      { match: "https://example.com/account/*", maskLevel: "conservative" },
    ],
  },
}).promise;

Remove sensitive values from URLs

To replace tokens or IDs in recorded page URLs, set up UGC filter rules.

Match sessions

How replays match events

Amplitude links a replay to a user's events by device ID and session ID. The replay ID combines them as <device ID>/<session ID>, so neither ID can contain /. IDs can use letters, digits, and _ - . | @ : =.

The plugin reads both IDs from Browser SDK 2 and follows its session changes. It also adds the [Amplitude] Session Replay ID event property to every Browser SDK 2 event in the session, except Identify events. With the standalone SDK, you pass the IDs. If your project defines sessions another way, go to Choose a session matching option.

Update the session ID

Standalone only. Call setSessionId() whenever your analytics tool starts a new session. The SDK sends what it recorded for the previous session, then records the new one. Calling it with the current session ID does nothing.

ts
await sessionReplay.setSessionId(1735693200000).promise;

To change the device ID at the same time, pass it as the second argument: setSessionId(sessionId, deviceId).

The session ID can be a number, such as a start time in milliseconds, or a string. For the rules on custom session IDs, go to Configure custom session matching.

Use a custom session ID with the plugin

Plugin only. To record replays under your own session ID instead of the Browser SDK 2 session ID, set customSessionId. The plugin calls it for each event and uses the ID it returns.

ts
amplitude.add(
  sessionReplayPlugin({
    sampleRate: 1,
    customSessionId: (event) => event.event_properties?.checkout_id,
  }),
);
amplitude.init("AMPLITUDE_API_KEY");

Add the replay ID to events yourself

Standalone only. Amplitude matches replays by device ID and session ID, so most implementations don't need this. If your project relies on the [Amplitude] Session Replay ID event property, merge the SDK's properties into each event your analytics tool sends:

ts
const replayProperties = sessionReplay.getSessionReplayProperties();
// { "[Amplitude] Session Replay ID": "device-abc123/1735689600000" }

The method returns {} when the session isn't recording.

Use Session Replay with more than one Browser SDK instance

Plugin only. Add the plugin to one instance: the one that sends events to the project where you want replays.

ts
const instance = amplitude.createInstance();
instance.add(sessionReplayPlugin({ sampleRate: 1 }));
instance.init("AMPLITUDE_API_KEY");

Data delivery

How the SDK uploads replays

The SDK records a full snapshot of the page when recording starts, then records each change to the page. It buffers the changes and uploads them in batches:

  • A batch closes when the SDK records new activity after the upload interval. The interval starts at 1 second and grows to 10 seconds. A page with no activity sends nothing until the next interaction.
  • A batch also closes when it reaches about 6 MB, when the session changes, and when the user hides the tab.
  • When the user leaves the page, the SDK sends the last batch with navigator.sendBeacon, limited to 64 KB.

The SDK compresses each upload with gzip. The SDK retries a failed upload up to two times, then drops the batch.

By default, the SDK keeps unsent data in memory, so that data is lost when the page closes. To keep it across page loads, set storeType: "idb". Go to Keep unsent replay data across page loads.

Choose a data region

If your project is in the EU data center, send replays to the EU endpoints.

Set serverZone: "EU" in the Browser SDK 2 init() options. The plugin reads it from there.

ts
amplitude.add(sessionReplayPlugin({ sampleRate: 1 }));
amplitude.init("AMPLITUDE_API_KEY", { serverZone: "EU" });

Allow Session Replay in a Content Security Policy

Session Replay uses these endpoints:

If your site sets a Content Security Policy, allow these endpoints:

For example, for a US project:

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

If you send requests through a proxy, allow the proxy's domain instead.

Send replays through a proxy

To send replay data and remote configuration requests through your own domain, set trackServerUrl and configServerUrl, and forward requests to the endpoints in Allow Session Replay in a Content Security Policy.

ts
amplitude.add(
  sessionReplayPlugin({
    sampleRate: 1,
    trackServerUrl: "https://replay-proxy.example.com/sessions/v2/track",
    configServerUrl: "https://replay-proxy.example.com/config",
  }),
);
amplitude.init("AMPLITUDE_API_KEY");

If you don't set configServerUrl on the plugin, it uses the Browser SDK 2 remote configuration URL. For server setup, go to Proxy Session Replay requests.

To send requests with your own code, for example to add headers, pass handleSendEvents and handleFetchConfig. Each receives a request description and must return a Response. The SDK still decides when to retry. Requires version 1.47.0 or later (plugin 1.33.0).

Keep unsent replay data across page loads

storeType sets where the SDK buffers replay data before upload:

  • memory (default): data the SDK hasn't uploaded is lost when the page closes. Default changed in 1.42.0.
  • idb: the SDK keeps unsent data in IndexedDB and uploads it on the next page load. Use idb when users often navigate between pages or close tabs mid-session. If IndexedDB isn't available, or fails repeatedly, the SDK falls back to memory.
ts
amplitude.add(sessionReplayPlugin({ sampleRate: 1, storeType: "idb" }));
amplitude.init("AMPLITUDE_API_KEY");

Session Replay doesn't set cookies. Browser SDK 2 uses cookies for the session that the plugin reads. IndexedDB works only for the page's own origin.

Performance

How recording affects performance

The SDK records changes to the page as they happen. By default, it serializes recorded changes when the browser is idle and compresses uploads in a web worker, off the main thread. For measurements, go to the Session Replay performance testing blog post. For bundle size, go to the package on npm or BundlePhobia.

To reduce the cost further:

  • Lower sampleRate. The SDK doesn't record sessions it doesn't select.
  • Keep useWebWorker on (the default) so compression stays off the main thread. Default changed in 1.46.0.
  • Keep performanceConfig.enabled on (the default). Set performanceConfig.timeout to cap how long serialization waits for idle time. It defaults to 2,000 milliseconds.

Defer initialization

To keep Session Replay out of page-load metrics such as Largest Contentful Paint, load it after the page loads. The replay starts when Session Replay initializes, so Session Replay doesn't record activity before that.

ts
amplitude.init("AMPLITUDE_API_KEY");

window.addEventListener("load", async () => {
  const { sessionReplayPlugin } =
    await import("@amplitude/plugin-session-replay-browser");
  await amplitude.add(sessionReplayPlugin({ sampleRate: 0.5 })).promise;
});

To wait for a quiet moment instead, replace the load listener with requestIdleCallback.

Frameworks

Single-page apps

Session Replay records the page URL each time it changes, including changes that don't load a new page. It watches history.pushState, history.replaceState, popstate, and hashchange. Shallow routing, such as SvelteKit's pushState or a Next.js shallow route, counts as a URL change.

If your app changes the URL in a way Session Replay misses, set enableUrlChangePolling: true. Session Replay then also checks the URL every urlChangePollingInterval milliseconds (default 1000). Requires version 1.27.0 or later (plugin 1.21.0).

ts
amplitude.add(
  sessionReplayPlugin({ sampleRate: 1, enableUrlChangePolling: true }),
);
amplitude.init("AMPLITUDE_API_KEY");

To also record the page title with each URL change, set captureDocumentTitle: true. Requires version 1.27.0 or later (plugin 1.21.0).

Server-side rendering and hydration

Session Replay runs only in the browser. With Next.js, Nuxt, SvelteKit, Angular SSR, or React Router, add the plugin or call init() in client-only code, such as a client entry file, a useEffect hook, or an onMount callback. The replay starts from the server-rendered page, and Session Replay records the changes hydration makes.

Angular

In an Angular app that uses Zone.js, set up Session Replay outside the Angular zone, so the recorder's event listeners don't trigger change detection. For example, add the plugin and call init() in main.ts before bootstrapApplication:

ts
// main.ts
import { bootstrapApplication } from "@angular/platform-browser";
import * as amplitude from "@amplitude/analytics-browser";
import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser";
import { AppComponent } from "./app/app.component";
import { appConfig } from "./app/app.config";

amplitude.add(sessionReplayPlugin({ sampleRate: 1 }));
amplitude.init("AMPLITUDE_API_KEY");

bootstrapApplication(AppComponent, appConfig);

Iframes

Session Replay records same-origin iframes with the page. To record a cross-origin iframe that you control, load Session Replay inside it too, and set crossOriginIframes: { enabled: true } in both. Go to Cross-origin iframe recording.

Known limitations

  • Session Replay doesn't record <canvas> content, including WebGL.
  • Session Replay doesn't record <object> content, such as plugins, except <object type="image">.
  • Session Replay doesn't record Lottie animations.
  • Session Replay doesn't record cross-origin iframes that don't load Session Replay with crossOriginIframes.enabled, such as third-party payment or map embeds.
  • Replays can't show assets that need authentication, such as fonts, stylesheets, or images behind a login. For missing styles, go to Troubleshoot Session Replay.
  • Ad blockers can block Session Replay. A proxy avoids most blocks.
  • Replays don't join across projects. When a user moves from a site in one project to a site in another, each project shows its own replay.
  • Session Replay doesn't record activity before it initializes.

For retention, deletion, data subject access requests, and bot filtering, go to the Session Replay data lifecycle reference.

これは役に立ちましたか?

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

このページでは