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.
Session Replay Standalone SDK
Session Replay instrumentation
Session Replay isn't enabled by default, and requires setup beyond the standard Amplitude instrumentation.
The Session Replay standalone SDK adds session recording to your site independently of the Amplitude Browser SDK. If you use a provider other than Amplitude for in-product analytics, choose this option. If your site already uses the Amplitude Browser SDK, use the Session Replay Browser SDK Plugin.
Session Replay and performance
Amplitude built Session Replay to minimize impact on web page performance by:
- Processing asynchronously through webhooks (if enabled) for efficient compression and optimized bundle sizes.
- Using batching and lightweight compression to reduce network connections and bandwidth.
- Optimizing DOM processing.
Bundle size
The Session Replay standalone SDK adds to your application's bundle size.
For current bundle size information, check the npm package page or BundlePhobia.
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 takes 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. Amplitude defers compression operations to browser idle periods when
performanceConfig.enabledistrue(default). - Network bandwidth: Amplitude compresses replay data before upload, typically reducing payload size by 60-80%. Amplitude batches network requests and sends them asynchronously.
Performance optimization
To optimize Session Replay performance:
- Enable
useWebWorkerto move compression off the main thread, reducing CPU impact on the main thread. - Configure
performanceConfig.timeoutto control when deferred compression occurs. - Use
sampleRateto reduce the number of sessions captured, which directly reduces CPU and memory usage. - Set
storeTypetomemoryif you don't need persistence across page reloads, reducing IndexedDB overhead.
For detailed performance testing results, refer to the Session Replay performance testing blog post.
Session Replay captures changes to a page's Document Object Model (DOM), including elements in the shadow DOM, then replays these changes to build a video-like replay. 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.
Defer SDK initialization
Deferring Session Replay initialization until after the page loads eliminates the SDK's contribution to page load metrics. Use this approach when you're measuring load-time metrics like Time to Interactive or Largest Contentful Paint and need zero Session Replay impact. If reducing impact while keeping early initialization is your goal, use the configuration options in Performance optimization instead.
Use a load event listener to defer initialization:
import 3rdPartyAnalytics from 'example';
window.addEventListener('load', async () => {
const sessionReplay = await import('@amplitude/session-replay-browser');
await sessionReplay.init(AMPLITUDE_API_KEY, {
deviceId: '<string>',
sessionId: '<string | number>',
sampleRate: 0.5,
}).promise;
});
Alternatively, defer until the browser is idle using requestIdleCallback. This approach waits for a low-activity moment, reducing contention with other post-load work:
import 3rdPartyAnalytics from 'example';
requestIdleCallback(async () => {
const sessionReplay = await import('@amplitude/session-replay-browser');
await sessionReplay.init(AMPLITUDE_API_KEY, {
deviceId: '<string>',
sessionId: '<string | number>',
sampleRate: 0.5,
}).promise;
});
Session Replay captures a full DOM snapshot when it initializes. Interactions that occur before initialization don't appear in the replay.
Prerequisites
Session Replay Standalone SDK requires that:
- Your application is web-based.
- You provide a session identifier to the SDK at initialization and call
setSessionIdwhen it changes. The SDK uses this ID to bucket replay data. For session ID matching, use the same session identifier on analytics events and in the SDK. With time-based event matching only, the Session ReplaysessionIdcan be a frontend-generated time bucket (for example, an hour-aligned Unix timestamp in milliseconds) that doesn't appear on analytics events. - You can provide a device ID to the SDK.
- The
Device IDyou pass to the Standalone SDK must match the device ID on your analytics events.
The Standalone SDK doesn't provide session management capabilities. Your application or a third-party integration must update the SDK with changes to Session ID and Device ID.
Quickstart
Install the plugin with npm or yarn.
Unified SDK
Install the Browser Unified SDK to access the Experiment SDK along with other Amplitude products (Analytics, Session Replay). The Unified SDK provides a single entry point for all Amplitude features and handles the initialization and configuration of all components.
# Install Session Replay SDK only
npm install @amplitude/session-replay-browser --save
# Or install Unified SDK to get access to all Amplitude products
npm install @amplitude/unified
Configure your application code.
- Call
sessionReplay.initto begin collecting replays. Pass the API key, session identifier, and device identifier. - When the session identifier changes, pass the new value to Amplitude with
sessionReplay.setSessionId. - Amplitude automatically creates the
[Amplitude] Replay Capturedevent to link replays with your analytics data. Refer to Session Replay ID for more information.
import * as sessionReplay from "@amplitude/session-replay-browser";
import 3rdPartyAnalytics from 'example'
const AMPLITUDE_API_KEY = "key"
// Configure the SDK and begin collecting replays
await sessionReplay.init(AMPLITUDE_API_KEY, {
deviceId: "<string>",
sessionId: "<string | number>",
optOut: false,
sampleRate: 1, // Records 100% of sessions for initial testing. Lower this for production; the SDK default (0) records nothing.
}).promise;
// Call whenever the session id changes
await sessionReplay.setSessionId(sessionId).promise;
Session Replay instrumentation happens in the context of an Amplitude project. Amplitude defines your replay quota at the organization level. You may have multiple Session Replay implementations across multiple projects, each with its own sample rate, that pull from the same quota.
You can also use script tags to instrument Session Replay:
<script src="https://cdn.amplitude.com/libs/session-replay-browser-1.51.2-min.js.gz"></script>
<script>
window.sessionReplay.init(AMPLITUDE_API_KEY, {
deviceId: "<string>",
sessionId: "<string | number>",
sampleRate: 1, // Records 100% of sessions for initial testing. Lower this for production; the SDK default (0) records nothing.
//...other options
})
// Call whenever the session id changes
window.sessionReplay.setSessionId(sessionId);
</script>
Session Replay ID
Amplitude automatically creates the [Amplitude] Replay Captured event when Session Replay captures a session. This event includes the [Amplitude] Session Replay ID property, which links the replay to your analytics data. Manual instrumentation isn't required.
[Amplitude] Session Replay ID is a unique identifier for the replay, and differs from [Amplitude] Session ID, which identifies the user's session by default.
The session replay ID has the format <deviceId>/<sessionId>. Because Session Replay uses / as a delimiter, deviceId and custom session ID string values can't contain /. Accepted characters: a-z A-Z 0-9 _ - . | @ : =. If you need an additional character, contact Amplitude support.
Amplitude links replays with a session replay ID. To combine multiple sessions into a single replay, ensure each session references the same device ID and session ID.
Legacy implementations
If you have a legacy implementation that manually adds the [Amplitude] Session Replay ID property to events using getSessionReplayProperties(), this continues to work. However, Amplitude recommends the automatic [Amplitude] Replay Captured event.
Not seeing replays?
If replays don't appear in the Amplitude UI, check that the [Amplitude] Replay Captured event appears in your project. If you don't see this event, contact Amplitude support.
Configuration
Pass the following configuration options when you initialize the Session Replay SDK.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
deviceId | string | Yes | undefined | Sets an identifier for the device running your application. |
sessionId | string | number | Yes | undefined | Sets an identifier for the user's current session. Use a Unix timestamp in milliseconds (number) for standard session tracking, or a custom string for custom session definitions. Custom string values must follow the accepted character set. |
sampleRate | number | No | 0 | Controls how many sessions Amplitude selects 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. Sample rates as small as six decimal places (0.000001) work. |
optOut | boolean | No | false | Sets permission to collect replays for sessions. A value of true prevents Amplitude from collecting session replays. |
flushMaxRetries | number | No | 5 | Sets the maximum number of retries for failed upload attempts. This applies only to errors that Amplitude can retry. |
logLevel | number | No | LogLevel.Warn | LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug. Sets the log level. |
loggerProvider | Logger | No | Logger | Sets a custom loggerProvider class from the Logger to emit log messages to your destination. |
serverZone | string | No | US | EU or US. Sets the Amplitude server zone. Set this to EU for Amplitude projects created in the EU data center. |
privacyConfig | object | No | undefined | Supports advanced masking configurations with CSS selectors. Refer to Mask on-screen data for more information. |
applyBackgroundColorToBlockedElements | boolean | No | false | If true, applies a background color to blocked elements for visual masking. This helps visualize which elements Amplitude blocks from capture in the replay. |
debugMode | boolean | No | false | Adds an additional debug event property to help debug instrumentation issues (such as mismatching apps). Amplitude recommends this only for debugging initial setup, not for production. |
configServerUrl | string | No | undefined | Specifies the endpoint URL to fetch remote configuration. If provided, it overrides the default server zone configuration. |
trackServerUrl | string | No | undefined | Specifies the endpoint URL to send session replay data. If provided, the SDK forwards requests there instead of to the default SR endpoint. |
shouldInlineStylesheet | boolean | No | true | If Amplitude inlines stylesheets, it stores the contents of the stylesheet. During replay, Amplitude 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 this is undefined, Amplitude inlines stylesheets. |
storeType | string | No | idb | Specifies how Amplitude stores replay events. idb uses IndexedDB to persist replay events when the SDK 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, Amplitude 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 executing 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
The browser SDK and plugin use the following endpoints. Select the region that matches your Amplitude project.
| Purpose | US | EU |
|---|---|---|
| Replay data ingestion | https://api-sr.amplitude.com/sessions/v2/track | https://api-sr.eu.amplitude.com/sessions/v2/track |
| Remote configuration | https://sr-client-cfg.amplitude.com/config | https://sr-client-cfg.eu.amplitude.com/config |
If you set up a domain proxy, forward requests to these endpoints. Override the defaults with trackServerUrl and configServerUrl.
Alternative API endpoints
The browser SDK network guidance also includes the following endpoint family. For an implementation that sends requests to these addresses, include the corresponding domains in your proxy and CSP configuration.
| Purpose | US | EU |
|---|---|---|
| Replay data ingestion | https://api-secure.amplitude.com/sessions/track | https://api.eu.amplitude.com/sessions/track |
| Remote configuration | https://api-secure.amplitude.com/sessions/config | https://api.eu.amplitude.com/sessions/config |
Mask on-screen data
The Session Replay SDK offers three ways to mask user input, text, and other HTML elements.
| Element | Description |
|---|---|
<input> | Session Replay masks all text input fields by default. When a user enters text into an input field, Session Replay captures asterisks in place of text. To unmask a text input, add the class .amp-unmask. For example: <input class="amp-unmask">. |
| text | To mask text within non-input elements, add the class .amp-mask. For example, <p class="amp-mask">Text</p>. When masked, Session Replay captures masked text as a series of asterisks. |
| non-text elements | To block a non-text element, add the class .amp-block. For example, <div class="amp-block"></div>. Session Replay replaces blocked elements with a placeholder of the same dimensions. |
Configure Light, Medium, or Conservative masking and remote overrides in Session Replay privacy settings. Remote settings take precedence when they conflict with SDK settings.
Specify elements to block or mask in the privacyConfig object during configuration.
// This configuration blocks .no-track and #ads, sets the default mask level,
// and defines the mask and unmask selectors.
await sessionReplay.init(AMPLITUDE_API_KEY, {
privacyConfig: {
blockSelector: ['.no-track', '#ads'],
defaultMaskLevel: 'medium',
maskSelector: ['.sensitive-data', '.user-email'],
unmaskSelector: ['.public-info', '#main-content']
}
}).promise;
CSS selectors
Session Replay's configuration supports many types of CSS Selector. Specify an element tag (h1 or textarea), a class name (.hidden) or a data attribute.
Data attributes may be useful if your class names change often due to hashing. To use data attributes, add a custom attribute like data-amp-unmask or data-amp-mask to any HTML element. For example, <textarea data-amp-unmask></textarea>, then enclose the attribute in square brackets when you specify the selector, [data-amp-unmask].
Remote configuration
If you enable remote configuration and it fails to load, Session Replay doesn't capture any sessions. This prevents capture without the privacy settings you define in the Admin interface.
User opt-out
Session Replay provides an opt-out configuration option. When passed as part of initialization, this prevents Amplitude from collecting session replays. For example:
// Pass a boolean value to indicate a users opt-out status
await sessionReplay.init(AMPLITUDE_API_KEY, {
optOut: true,
}).promise;
Content Security Policy (CSP)
If your web application uses a strict Content Security Policy, allow the domains your implementation uses in API endpoints.
Required CSP directives
Add script-src for CDN loading, connect-src for ingestion and remote configuration, and worker-src if you enable useWebWorker.
CSP directives reference
| Directive | Domain | Requirement |
|---|---|---|
script-src | https://cdn.amplitude.com | Required when loading the browser SDK or plugin from Amplitude's CDN. |
connect-src | https://api-sr.amplitude.com and https://sr-client-cfg.amplitude.com | US replay ingestion and remote configuration. |
connect-src | https://api-sr.eu.amplitude.com and https://sr-client-cfg.eu.amplitude.com | EU replay ingestion and remote configuration when serverZone: "EU". |
connect-src | https://api-secure.amplitude.com | Required for implementations that use the alternative US API endpoints. |
connect-src | https://api.eu.amplitude.com | Required for implementations that use the alternative EU API endpoints. |
worker-src | blob: | Required if you enable useWebWorker for replay event compression. |
Example CSP header
For US ingestion and remote configuration:
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:;
For EU ingestion and remote configuration:
Content-Security-Policy: script-src 'self' https://cdn.amplitude.com; connect-src 'self' https://api-sr.eu.amplitude.com https://sr-client-cfg.eu.amplitude.com; worker-src 'self' blob:;
For an implementation using the alternative US endpoints:
Content-Security-Policy: script-src 'self' https://cdn.amplitude.com; connect-src 'self' https://api-secure.amplitude.com; worker-src 'self' blob:;
For an implementation using the alternative EU endpoints:
Content-Security-Policy: script-src 'self' https://cdn.amplitude.com; connect-src 'self' https://api.eu.amplitude.com; worker-src 'self' blob:;
If you specify custom endpoints with configServerUrl or trackServerUrl, add those domains to connect-src instead of the corresponding default domains.
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:
// For European users, set the serverZone to "EU"
await sessionReplay.init(AMPLITUDE_API_KEY, {
serverZone: "EU",
}).promise;
Sampling rate
By default, Session Replay captures 0% of sessions for replay. Use the sampleRate configuration option to set the percentage of total sessions that Session Replay captures. For example:
// This configuration samples 1% of all sessions
await sessionReplay.init(AMPLITUDE_API_KEY, {
sampleRate: 0.01,
}).promise;
For manual and dynamic sampling, quota planning, and remote-setting precedence, go to Configure Session Replay sampling.
Disable replay collection
After you enable Session Replay, it runs on your site until either:
- The user leaves your site.
- You call
sessionReplay.shutdown().
Call sessionReplay.shutdown() before a user navigates to a restricted area of your site to disable replay collection while the user is in that area.
Call sessionReplay.init(API_KEY, {...options}) to re-enable replay collection when the user returns to an unrestricted area of your site.
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, you can create a feature flag that targets a specific user group, and add that to your initialization logic:
import * as sessionReplay from "@amplitude/session-replay-browser";
import 3rdPartyAnalytics from 'example'
const AMPLITUDE_API_KEY = <...>
await sessionReplay.init(AMPLITUDE_API_KEY, {
deviceId: <string>,
sessionId: <string | number>,
optOut: <boolean>,
sampleRate: <number>
}).promise;
Data retention
Session Replay uses Amplitude tools and APIs for privacy and deletion requests. Review consent guidance when you implement capture.
Retention period
For default retention, extended retention, and the effective date of retention changes, go to the Session Replay data lifecycle reference.
DSAR API
The Session Replay data lifecycle reference describes the metadata the DSAR API returns.
Data deletion
For user and project deletion behavior, go to Session Replay data deletion.
Bot filter
For bot filtering and property-filter restrictions, go to Session Replay bot filtering.
Session Replay storage
Session Replay doesn't set cookies on the user's browser. Instead, it relies on a browser storage option called IndexedDB by default. This option enables continuous replay collection during a session in which the user navigates browser tabs or closes and reopens a tab. The SDK cleans up the data it stores in IndexedDB and shouldn't impact the user's disk space.
If the environment doesn't support IndexedDB, Session Replay falls back to an in-memory storage option. In-memory storage is less durable and data is lost when the user closes their browser window. Set the config option storeType to 'memory' to force in-memory storage.
If a user opts out of all cookies on your site, use the optOut configuration option to disable replay collection for that user.
IndexedDB best practices
To ensure that IndexedDB is initialized and working properly:
Review CSP headers to ensure they're not overly restrictive. Ensure
default-srcandscript-srcdirectives allow necessary sources.Perform IndexedDB operations within the same origin. Cross-origin restrictions can block IndexedDB operations.
Confirm that users use a modern browser that supports IndexedDB. Amplitude recommends the latest versions of Chrome, Firefox, Safari, Edge, or Opera.
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 appears in the host project.
- Session Replay can't capture the following HTML elements:
- Canvas.
- WebGL.
objecttags including plugins like Flash, Silverlight, or Java. Session Replay supportsobject type="image".- Lottie animations.
- Cross-origin
<iframe>elements that don't load the Session Replay SDK withcrossOriginIframes.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. - Assets that require authentication, like fonts, CSS, or images.
- Session Replay isn't compatible with ad blocking software.
Troubleshooting
For missing, incomplete, or unavailable replays, go to Troubleshoot Session Replay. For ingestion statuses, use the Session Replay Ingestion Monitor.
CSS styling doesn't appear in replay
Session Replay stores references to CSS files and other static assets on your site and uses those references to reconstruct a replay. If the files move or require authentication, Amplitude may be unable to load them during playback:
- 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.comorapp.eu.amplitude.comto 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.cssRulesfail).These restrictions can prevent Session Replay from capturing styling information, which results in incomplete or broken visual playback.
Replay length and session length don't match
In some scenarios, the length of a replay may exceed the time between the [Amplitude] Start Session and [Amplitude] End Session events. This happens when a user closes their browser or browser tab and [Amplitude] End Session occurs, but the Browser SDK and Session Replay plugin haven't yet processed it. When the user visits that page again, the SDK and plugin process the event and send it to Amplitude, along with the replay. You can verify this scenario occurs if you see a discrepancy between the End Session Client Event Time and the Client Upload Time.
Session replays may not appear in Amplitude due to:
- Content security policy
- Blocked JavaScript
- No events triggered through the browser SDK in the current session
- Sampling
Local development and focus state
The Session Replay SDK and plugin capture only the page that's in focus. When you develop locally with the browser console open, focus states may not work as expected. If you don't see replays in Amplitude, try to enable debugMode. In this mode, Session Replay ignores the focus handle and enables extra debugging information.
const sessionReplayTracking = window.sessionReplay.plugin({
debugMode: true,
sampleRate: 1,
});
Content security policy
When you add the Session Replay script to your site, visit a page on which the Session Replay SDK is running, and open your browser's developer tools.
Check for any error messages in the JavaScript console that contain the text Content Security Policy. For example, Refused to connect to 'https://api-secure.amplitude.com/sessions/track' because it violates the document's Content Security Policy.
To resolve this error, update your site's content security policy to allow connection to Amplitude's APIs.
Blocked JavaScript
Browser extensions or network security policy may block the Session Replay SDK. Check your browser's developer tools to see if requests fail, and if so, add an exception for the blocked domains.
Sampling
The default sampleRate for Session Replay is 0. Update the rate to a higher number. For more information, go to Sampling rate.
Some sessions don't include the Session Replay ID property
Session Replay doesn't require that all events in a session have the [Amplitude] Session Replay ID property, only that one event in the session has it. The property may be absent when you instrument an event with a source different from the source you connect to Session Replay. For example, your application may send events from a backend source, rather than the Browser SDK.
Session Replay processing errors
For processing delays, mismatched identifiers, short sessions, incomplete page instrumentation, and expired replays, go to Troubleshoot Session Replay. For retention rules, go to the Session Replay data lifecycle reference.
Was this helpful?