Session Replay isn't enabled by default, and requires setup beyond the standard Amplitude instrumentation.
This article covers the installation of Session Replay using the standalone SDK. If you use a provider other than Amplitude for in-product analytics, choose this option. If your site is already instrumented with Amplitude Browser SDK, use the Session Replay Browser SDK Plugin.
Amplitude built Session Replay to minimize impact on the performance of web pages on which it's installed by:
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. 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.
Use the latest version of the Session Replay standalone SDK above version 1.13.8. For more information, see the change log on GitHub.
Session Replay Standalone SDK requires that:
Session ID
and Device ID
you pass to the Standalone SDK must match those sent as event properties to Amplitude.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
.
Install the plugin with npm or yarn.
1npm install @amplitude/session-replay-browser --save
1yarn add @amplitude/session-replay-browser
Configure your application code.
sessionReplay.init
to begin collecting replays. Pass the API key, session identifier, and device identifier.sessionReplay.setSessionId
.sessionReplay.getSessionReplayProperties
. See Add Session Replay ID to your events for more information. 1import * as sessionReplay from "@amplitude/session-replay-browser"; 2import 3rdPartyAnalytics from 'example' 3 4const AMPLITUDE_API_KEY = "key" 5 6// Configure the SDK and begin collecting replays 7await sessionReplay.init(AMPLITUDE_API_KEY, { 8 deviceId: "<string>", 9 sessionId: "<number>",10 optOut: "<boolean>",11 sampleRate: "<number>"12}).promise;13 14// Call whenever the session id changes15sessionReplay.setSessionId(sessionId);16 17// When you send events to Amplitude, call this event to get18// the most up to date session replay properties for the event19const sessionReplayProperties = sessionReplay.getSessionReplayProperties();203rdPartyAnalytics.track('event', {...eventProperties, ...sessionReplayProperties})
Session Replay instrumentation happens in the context of an Amplitude Project. Your replay quota is defined on the Organization level. As a result, you may have multiple Session Replay implementations, across multiple projects each with their own sample rate, that pull from the same quota.
You can also use script tags to instrument Session Replay:
1<script src="https://cdn.amplitude.com/libs/session-replay-browser-1.10.0-min.js.gz"></script> 2<script> 3window.sessionReplay.init(AMPLITUDE_API_KEY, { 4 deviceId: "<string>", 5 sessionId: "<number>", 6 sampleRate: "<number>" 7 //...other options 8}) 9 10// Call whenever the session id changes11window.sessionReplay.setSessionId(sessionId);12 13// When you send events to Amplitude, call this event to get14// the most up-to-date Session Replay properties for the event15const sessionReplayProperties = window.sessionReplay.getSessionReplayProperties();163rdPartyAnalytics.track('event', {...eventProperties, ...sessionReplayProperties})17</script>
The Session Replay SDK outputs the Session Replay properties that you need to add to your custom event instrumentation. getSessionReplayProperties
returns event properties, namely the [Amplitude] Session Replay ID
event property that you need to add to events before you send them to Amplitude. An example response of getSessionReplayProperties is:
1{2 "[Amplitude] Session Replay ID": "6eb24f81-a106-45b0-879c-65248d7b8911/1710374872575"3}
getSessionReplayProperties
may return an empty object if Session Replay doesn't capture the session (for example, due to sampling or if the page is out of focus).
[Amplitude] Session Replay ID
is a unique identifier for the replay, and is different from [Amplitude] Session ID
, which is the identifier for the user's session.
The Session Replay Browser Plugin handles this by default, since Amplitude manages event instrumentation. With the Standalone SDK, you need to instrument your application to add this property to any events that occur during capture.
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 |
number |
Yes | undefined |
Sets an identifier for the users current session. The value must be in milliseconds since epoch (Unix Timestamp). |
sampleRate |
number |
No | 0 |
Use this option to control how many sessions to select for replay collection. The number should be a decimal between 0 and 1, for example 0.4 , representing the fraction of sessions to have randomly selected for replay collection. Over a large number of sessions, 0.4 would select 40% of those sessions. Sample rates as small as six decimal places (0.000001 ) are supported. |
optOut |
boolean |
No | false |
Sets permission to collect replays for sessions. Setting 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 is only applicable 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 desired destination. |
serverZone |
string |
No | US |
EU or US. Sets the Amplitude server zone. Set this to EU for Amplitude projects created in EU data center. |
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 users 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. |
Session Replay supports setting a masking level on the Session Replay Settings screen in Amplitude. This includes Light, Medium, and Conservative settings.
Session Replay settings also enable remote masking overrides. These enable users in your organization to configure or update masking after implementation.
In the event of a conflict, Session Replay defers to the remote setting. For example:
.selector-1 | .selector-2 | .selector-3 | |
---|---|---|---|
Local setting | mask |
-- | mask |
Remote setting | unmask |
unmask |
-- |
Result | unmask |
unmask |
mask |
In this example, .selector-1
has a local setting and a remote setting. The result follows the remote setting, and overrides the setting in the SDK or plugin implementation.
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]
.
Session Replay provides an option for opt-out configuration. This prevents Amplitude from collecting session replays when passed as part of initialization. For example:
1// Pass a boolean value to indicate a users opt-out status2await sessionReplay.init(AMPLITUDE_API_KEY, {3 optOut: true, 4}).promise;
Session Replay is available to Amplitude Customers who use the EU data center. Set the serverZone
configuration option to EU
during initialization. For example:
1// For European users, set the serverZone to "EU"2await sessionReplay.init(AMPLITUDE_API_KEY, {3 serverZone: "EU", 4}).promise;
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:
1// This configuration samples 1% of all sessions2await sessionReplay.init(AMPLITUDE_API_KEY, {3 sampleRate: 0.01 4}).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 ensure sampling lasts through the month, set sampleRate
to .83
or lower.
Keep the following in mind as you consider your sample rate:
.01
. If this value doesn't capture enough replays, raise the rate over the course of a few days. For ways to monitor the number of session replays captured, see View the number of captured sessions.Session Replay supports remote sampling rate settings. This enables users in your organization to configure or update the sampling rate of your project after implementation, without a code change. In the event of a conflict, Session Replay defaults to the remote setting. For more information, see Account Settings.
Once enabled, Session Replay runs on your site until either:
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 return 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:
1import * as sessionReplay from "@amplitude/session-replay-browser"; 2import 3rdPartyAnalytics from 'example' 3 4const AMPLITUDE_API_KEY = <...> 5sessionReplay.init(AMPLITUDE_API_KEY, { 6 deviceId: <string>, 7 sessionId: <number>, 8 optOut: <boolean>, 9 sampleRate: <number>10})11 12if (nonEUCountryFlagEnabled) {13 const sessionReplayProperties = sessionReplay.getSessionReplayProperties();14 3rdPartyAnalytics.track('event', {...eventProperties, ...sessionReplayProperties})15}
Session replay uses existing Amplitude tools and APIs to handle privacy and deletion requests.
While privacy laws and regulations vary across states and countries, certain constants exist, including the requirements to disclose in a privacy notice the categories of personal information you are collecting, the purposes for its use, and the categories of third parties with which personal information is shared. When implementing a session replay tool, you should review your privacy notice to make sure your disclosures remain accurate and complete. And as a best practice, review your notice with legal counsel to make sure it complies with the constantly evolving privacy laws and requirements applicable to your business and personal information data practices.
If your Amplitude plan includes Session Replay, Amplitude retains raw replay data for 30 days from the date of ingestion.
Purchase extra retention time, up to a maximum of 12 months. For more information, contact Amplitude Support.
If you purchase extra session volume, Amplitude retains raw replay data for up to 12 months from the date of ingestion. If you need a more strict policy, contact Amplitude support to set the value to 30 days.
Changes to the retention period impact replays ingested after the change. Sessions captured and ingested before a retention period change retain the previous retention period.
Replays that are outside of the retention period aren't viewable in Amplitude.
The Amplitude DSAR API returns metadata about session replays, but not the raw replay data. All events that are part of a session replay include a [Amplitude] Session Replay ID
event property. This event provides information about the sessions collected for replay for the user, and includes all metadata collected with each event.
1{ 2 "amplitude_id": 123456789, 3 "app": 12345, 4 "event_time": "2020-02-15 01:00:00.123456", 5 "event_type": "first_event", 6 "server_upload_time": "2020-02-18 01:00:00.234567", 7 "device_id": "your device id", 8 "user_properties": { ... } 9 "event_properties": {10 "[Amplitude] Session Replay ID": "cb6ade06-cbdf-4e0c-8156-32c2863379d6/1699922971244"11 }12 "session_id": 1699922971244,13}
Session Replay uses Amplitude's User Privacy API 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.
Session Replay uses the same block filter available in the Amplitude app. Session Replay doesn't block traffic based on event or user properties.
Session Replay doesn't set cookies on the user's browser. Instead, it relies on a browser storage option called IndexedDB. 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 a user opts out of all cookies on your site, use the optOut
configuration option to disable replay collection for that user.
To ensure that IndexedDB is initialized and working properly:
Review CSP headers to ensure they're not overly restrictive. Ensure default-src
and script-src
directives allow necessary sources.
Perform IndexedDB operations are 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.
Keep the following limitations in mind as you implement Session Replay:
<object>
tags including plugins like Flash, Silverlight, or Java. Session replay supports <object type="image">
<iframe>
elements from a different originSession Replay supports attaching to a single instance of the Amplitude SDK. If you have more than one instance instrumented in your application, make sure to start Session Replay on the instance that most relates to your project.
1<script>2 const sessionReplayTracking = window.sessionReplay.plugin();3 const instance = window.amplitude.createInstance();4 instance.add(sessionReplayTracking);5 instance.init(API_KEY);6<script>
For more information about individual statuses and errors, see the Session Replay Ingestion Monitor.
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 while it reconstructs the replay. In some situations, the styling present in the replay may differ from your application for the following reasons:
To help resolve CSS loading issues:
localhost
, try moving them to a staging environment.stylesheet.css?93f8b89
.app.amplitude.com
or app.eu.amplitude.com
to the list of domains that your server's CORS configuration permits.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:
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.
1const sessionReplayTracking = window.sessionReplay.plugin({2 debugMode: true, 3 sampleRate: 1,4 });
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.
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.
Session Replay requires that at least one event in the user's session has the [Amplitude] Session Replay ID
property. The Browser SDK Session Start
and Session End
events include this property by default. If you instrument your events with any SDK other than the Amplitude Browser SDK 2, use the Session Replay Standalone SDK and ensure you tag your events with the necessary event properties.
For local testing, you can force a Session Start event to ensure that Session Replay functions.
AMP_
.[Amplitude] Session Replay ID
property. After processing, the Play Session button should appear for that session.As mentioned above, the default sampleRate
for Session Replay is 0
. Update the rate to a higher number. For more information see, Sampling rate.
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. Reasons why [Amplitude] Session Replay ID
may not be present in an event include:
getSessionReplayProperties()
doesn't return the [Amplitude] Session Replay ID
property. This is because Session Replay hasn't begun the capture, since the user hasn't interacted with the page. This should lead to a decrease in the amount of inactivity that a replay captures.In general, replays should be available within minutes of ingestion. Delays or errors may be the result of one or more of the following:
Session Replay supports other analytics providers. Follow the information below to add Session Replay to an existing Segment-instrumented site.
To ensure that Session Replay implementations with Segment work as expected, add the Session Replay ID
event property to your Segment tracking plan. Otherwise, Segment may block the property.
Amplitude (Actions) tracks sessions automatically. When a user starts a new session, Amplitude sets an analytics_session_id
cookie on the users browser. Configure your implementation to listen for changes in value to analytics_session_id
, which you can do with Segment's Source Middleware.
This code snippet shows how to configure Session Replay with Segment's Amplitude (Actions) integration, and update the session ID when analytics_session_id
changes.
1import * as sessionReplay from "@amplitude/session-replay-browser"; 2import { AnalyticsBrowser } from "@segment/analytics-next"; 3 4const segmentAnalytics = AnalyticsBrowser.load({ 5 writeKey: "segment-key", 6}); 7 8const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment 9const getStoredSessionId = () => {10 return cookie.get("amp_session_id") || 0;11}12 13const user = await segmentAnalytics.user();14const storedSessionId = getStoredSessionId();15 16await sessionReplay.init(AMPLITUDE_API_KEY, {17 sessionId: storedSessionId,18 deviceId: user.anonymousId()19}).promise;20 21// Add middleware to check if the session id has changed,22// and update the session replay instance23segmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {24 const storedSessionId = getStoredSessionId();25 const nextSessionId = payload.obj.integrations['Actions Amplitude'].session_id || 026 if (storedSessionId < nextSessionId) {27 cookie.set("amp_session_id", nextSessionId);28 sessionReplay.setSessionId(nextSessionId);29 }30 next(payload);31});32 33// Add middleware to always add session replay properties to track calls34SegmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {35 const sessionReplayProperties = sessionReplay.getSessionReplayProperties();36 if (payload.type() === "track") {37 payload.obj.properties = {38 ...payload.obj.properties,39 ...sessionReplayProperties,40 };41 }42 43 next(payload);44});
This version of the Amplitude destination installs the Amplitude JavaScript SDK (5.2.2) on the client, and sends events directly to api.amplitude.com
.
The Device-mode integration tracks sessions by default, since it includes the amplitude-js SDK. The included SDK version (5.2.2) doesn't include an event for session changes. As a result, use Segment's middleware to update Session Replay when the session ID changes.
1import * as sessionReplay from "@amplitude/session-replay-browser"; 2import { AnalyticsBrowser } from "@segment/analytics-next"; 3 4const segmentAnalytics = AnalyticsBrowser.load({ 5 writeKey: "segment-key", 6}); 7 8const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment 9const getAmpSessionId = () => {10 const sessionId = window.amplitude.getInstance().getSessionId();11 cookie.set("amp_session_id", sessionId);12 return sessionId;13};14 15// Wait for the amplitude-js SDK to initialize,16// then initialize session replay with the correct device id and session id17window.amplitude.getInstance().onInit(() => {18 const sessionId = getAmpSessionId();19 sessionReplay.init(AMPLITUDE_API_KEY, {20 deviceId: window.amplitude.getInstance().options.deviceId,21 sessionId: getAmpSessionId(),22 });23});24 25// Add middleware to check if the session id has changed,26// and update the session replay instance27SegmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {28 const nextSessionId = window.amplitude.getInstance().getSessionId();29 const storedSessionId = cookie.get("amp_session_id") || 0;30 if (storedSessionId < nextSessionId) {31 cookie.set("amp_session_id", nextSessionId);32 sessionReplay.setSessionId(nextSessionId);33 }34 next(payload);35});36 37// Add middleware to always add session replay properties to track calls38SegmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {39 const sessionReplayProperties = sessionReplay.getSessionReplayProperties();40 if (payload.type() === "track") {41 payload.obj.properties = {42 ...payload.obj.properties,43 ...sessionReplayProperties,44 };45 }46 47 next(payload);48});
This version of the Amplitude destination sends events to Segment's backend, which forwards them to Amplitude. The Cloud-mode destination doesn't track sessions by default. To overcome this, use the Browser SDK as a shell to manage sessions, and use Session Replay as a plugin, as shown below.
1import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser"; 2import { AnalyticsBrowser } from "@segment/analytics-next"; 3 4const segmentAnalytics = AnalyticsBrowser.load({ 5 writeKey: "segment-key", 6}); 7 8// A plugin must be added so that events sent through Segment will have 9// session replay properties and the correct session id10const segmentPlugin = () => {11 return {12 name: "segment",13 type: "destination",14 execute: async (event) => {15 const properties = event.event_properties || {};16 segmentAnalytics.track(event.event_type, properties, {17 integrations: {18 Amplitude: {19 session_id: amplitude.getSessionId(),20 },21 },22 });23 return {24 code: 200,25 event: event,26 message: "OK",27 };28 },29 };30};31 32const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment33 34// Add the session replay plugin first, then the segment plugin35await amplitude.add(sessionReplayPlugin()).promise;36await amplitude.add(segmentPlugin()).promise;37 38const user = await segmentAnalytics.user();39await amplitude.init(AMPLITUDE_API_KEY, {40 instanceName: 'session-replay',41 sessionTimeout: Number.MAX_SAFE_INTEGER,42 defaultTracking: false,43 deviceId: user.anonymousId()44}).promise;45amplitude.remove('amplitude');46// Events must be tracked through the shell Browser SDK to properly attach47// session replay properties48amplitude.track('event name')
Thanks for your feedback!
November 14th, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.