JavaScript SDK - Initializing the SDK
Installation
Section titled InstallationThe following line will install the tracker and with it the SDK for you to take advantage of all tracker features.
npm i @openreplay/tracker
Initialization
Section titled InitializationWhen instantiating OpenReplay’s tracker, there are several configuration options you can provide to customize many aspects of the recording and the recording experience.
You must set the projectKey
option in the constructor. You can get this value from your OpenReplay dashboard under ‘Preferences > Projects’.
Single Page Applications (SPA)
Section titled Single Page Applications (SPA)If your website is a Single Page Application (SPA) use the below code:
import OpenReplay from '@openreplay/tracker';
//...
const tracker = new OpenReplay({
projectKey: PROJECT_KEY
});
tracker.start(); // returns a promise with session info (sessionID, sessionHash, userUUID)
Server-side Rendered (SSR)
Section titled Server-side Rendered (SSR)Otherwise, if your web app is Server-Side-Rendered (SSR) (i.e. NextJS, NuxtJS) use the below snippet. Ensure tracker.start()
is called once the app is started (in useEffect
or componentDidMount
).
import OpenReplay from '@openreplay/tracker/cjs';
//...
const tracker = new OpenReplay({
projectKey: PROJECT_KEY,
});
//...
function MyApp() {
useEffect(() => { // use componentDidMount in case of React Class Component
tracker.start(); // returns a promise with session info (sessionID, sessionHash, userUUID)
}, [])
}
Example
Section titled Exampleimport OpenReplay from '@openreplay/tracker/cjs';
//...
const tracker = new OpenReplay({
projectKey: PROJECT_KEY,
ingestPoint: "https://openreplay.mydomain.com/ingest", // when dealing with the self-hosted version of OpenReplay
capturePerformance: true,
__DISABLE_SECURE_MODE: true // for local testing
});
Initialization Options
Section titled Initialization OptionsThere are a set of options you can pass to the constructor. Only projectKey
is required.
General Purpose
Section titled General PurposeprojectKey: string
The ID of the project you’re tracking.sessionHash?: string
The hash of the initial session. This is useful when sessions traverse different subdomains on your web app but you want to stitch them into a single recording. In case it’s not possible to continue the session (doesn’t exist or is finished), the tracker will automatically start a new one. It’s also returned onstop()
. More details on this here.ingestPoint?: string
Your OpenReplay domain (i.e. https://openreplay.mydomain.com/ingest), to which the tracker will be sending events. This is optional for OpenReplay Cloud users. Default:https://api.openreplay.com/ingest
(which points to OpenReplay Cloud).revID?: string
The revision ID of your web app. Useful when searching for issues happening on a specific release version.resourceBaseHref?: string
Refers to the publicly accessible domain where assets (styles, fonts and icons) could be fetched by OpenReplay. Since they’re required for proper session replay, this option is useful to get around the limitation of having your site (and therefore assets) hosted in a private domain. Example:https://mypublicsite.com/assets/
.captureIFrames?: boolean
For capturing all of the same-domain iFrames in your web app. If you wish to track a specific iFrame, then instead simply add thedata-openreplay-capture
HTML attribute to the<iframe>
tag. Default:true
.disableClickmaps?: boolean
For disabling css selector calculation (used in click maps). Default:false
.verbose?: boolean
For enabling logs. Default:false
.autoResetOnWindowOpen?: boolean
Enable this option to reset the sessionID when opening a new tab from your application. This overwrites thewindow.open
method to avoid duplicate sessionIDs due to shared session storage between browser tabs. Default:false
.forceSingleTab: boolean
Disables the multi-tab recording capability which stitches user sessions, conducted across multiple tabs, into a single replay. Instead, by enabling this option, sessions captured in different browser tabs will be recorded in separate recordings. Default:false
.disableStringDict: boolean
Disables the string dictionary logic (for optimizing storage) in recordings. Default:false
.fixedCanvasScaling: boolean
Forces canvas images to be rendered with pixel density of 1 instead of devicePixelRatio. (lowers the potential quality of an image to make end result smaller in size). Default:false
.disableCanvas?: boolean
Disables recording of canvas elements. Default:false
.assistSocketHost?: string
Can be used to set a specific host for assist plugin connection. Defaults to the value ofingestPoint
.nodes?: { maintainer: MaintainerOptions }
The newnodes.maintainer
option helps manage memory and clean up DOM nodes that are no longer in use. It has the following parameters:interval: number
: Time interval (in milliseconds) between cleanup runs. Default: 30 * 1000 (30 seconds).batchSize: number
: Number of nodes to check during each cleanup run. Default: 2500.enabled: boolean
: Enable or disable the node maintainer. Default: true.
Example
Section titled Exampleimport OpenReplay from '@openreplay/tracker/cjs';
const tracker = new OpenReplay({
projectKey: 'your_project_key',
nodes: {
maintainer: {
interval: 60 * 1000, // Run cleanup every minute
batchSize: 2500, // Check nodes in batches of 2500
enabled: true, // Enable the node maintainer
}
}
});
Privacy
Section titled PrivacyrespectDoNotTrack?: boolean
Do not start tracker if the do-not-track flag is enabled in the user’s browser. Default:false
.obscureTextEmails?: boolean
Obscures emails in text elements. Emails will be converted to a random chain of asterisks. Default:true
.obscureTextNumbers?: boolean
Obscures numbers in text elements. Numbers will be converted to a random chain of asterisks. Default:false
.obscureInputEmails?: boolean
Obscures emails in input fields. Email values will be converted to a random chain of asterisks. Default:true
.obscureInputNumbers?: boolean
Obscures numbers in input fields. Number values will be converted to a random chain of asterisks. Default:false
.obscureInputDates?: boolean
Obscure dates in input fields. Date values will be converted to a random chain of asterisks. Default: false.defaultInputMode?: 0 | 1 | 2
Default capture mode for input values. Respectively: plain, obscured or ignored. Default:1
(obscured).
Note that excluded data is obscured or suppressed before sending the data to OpenReplay servers. Changes applied to the above options cannot be retroactive and will only apply to newly collected data. See Sanitize Data for more details.
Console
Section titled ConsoleconsoleMethods?: Array<'log' | 'info' | 'warn' | 'error' 'debug' | 'assert'> | null
Specifies the list of console methods to capture. Default:['log', 'info', 'warn', 'error', 'debug', 'assert']
consoleThrottling?: number
Max number of captured console entries per second. Default:30
.
Exceptions
Section titled ExceptionscaptureExceptions?: boolean
Captures JavaScript exceptions and stacktraces. Default:true
.
Timings
Section titled TimingscaptureResourceTimings?: boolean
Logs resource timings. Default:true
.capturePageLoadTimings?: boolean
Logs page load timings. Default:true
.capturePageRenderTimings?: boolean
Computes page rendering metrics such as Speed Index, Visually Complete or Time To Interactive. RequirescaptureResourceTimings = true
. Default:true
.
Performance
Section titled PerformancecapturePerformance?: boolean
For capturing performance metrics such as framerate, CPU and memory consumption. Default:true
.
Network
Section titled NetworkThe network
option relates to capturing network requests and payloads for fetch
and XHR
.
network?: {
failuresOnly: boolean;
sessionTokenHeader: string;
ignoreHeaders: Array<string> | boolean;
capturePayload: boolean; // make sure you sanitize your data before enabling it
sanitizer: (RequestResponseData) => RequestResponseData | null;
captureInIframes: boolean;
axiosInstances: AxiosInstance[];
useProxy?: boolean;
tokenUrlMatcher?: (url: string) => boolean;
}
See Network Options for examples and more details on how to redact sensitive data.
Canvas
Section titled CanvasThe canvas
option relates to capturing canvas/WebGL elements:
canvas?: {
disableCanvas?: boolean
fixedCanvasScaling?: boolean
useAnimationFrame?: boolean
fileExt?: 'webp' | 'png' | 'jpeg' | 'avif'
}
See Canvas and WebGL for how to enable this capability and more details on the available options.
Cross-domain iFrames
Section titled Cross-domain iFramesThe crossdomain
option relates to capturing iFrames from different domains. It’s used in conjunction with the captureIFrames
option which must be set to true
.
crossdomain?: {
/**
* Enable cross-domain tracking
* @default false
* */
enabled?: boolean
/**
* Used to specify the parent domain, will be '*' by default
* (Check your CSP settings)
* @default '*'
* */
parentDomain?: string
}
As of Tracker version 14.0.10, the data-domain
attribute is no longer required on HTML elements when working with cross-domain iFrames.
See Cross-domain iFrame Tracking for more details on how to capture an iFrame from a different domain.
Mouse pointer
Section titled Mouse pointerThe mouse
option relates to capturing selectors for clicks to build clickmaps.
mouse?:
{
disableClickmaps?: boolean
minSelectorDepth?: number
nthThreshold?: number
maxOptimiseTries?: number
}
disableClickmaps?: boolean
Disables selector calculation entirely. Default:false
.minSelectorDepth?: number
Minimum length of an optimized selector (default 2). Example:body > div > div > p => body > p
nthThreshold?: number
Number of selector tries before falling back to nth-child selectors. This is an expensive operation and may incur a significant overhead, do not set higher than 2000. Default:1000
.maxOptimiseTries?: number
Number of tries to optimize and shorten the selector. Default:10 000
.
Reconnections
Section titled ReconnectionsconnAttemptCount?: number
Max number of retries when tracker’s HTTP requests fail to reach the backend. Default:10
.connAttemptGap?: number
Duration between each retry attempt (expressed in ms). Default:8000
.
Feature Flags
Section titled Feature FlagsonFlagsLoad
callback used to perform an action once feature flags are loaded (every time).
flags?: {
onFlagsLoad?: (flags: IFeatureFlag[]) => void
}
// ...
interface IFeatureFlag {
key: string
is_persist: boolean
value: string | boolean
payload: string
}
Security
Section titled Security__DISABLE_SECURE_MODE?: boolean
For allowing insecure connection between tracker and backend on sites without SSL. This should be used for development purposes only. Default:false
.