JavaScript SDK - Initializing the SDK

Configuration options for the tracker's constructor method

JavaScript SDK ⁠-⁠ Initializing the SDK

The following line will install the tracker and with it the SDK for you to take advantage of all tracker features.

npm i @openreplay/tracker

When 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) you can use tracker as singleton:

import { tracker } from '@openreplay/tracker'

tracker.configure({
	projectKey: PROJECT_KEY,
  ingestPoint: "https://openreplay.mydomain.com/ingest", // when dealing with the self-hosted version of OpenReplay
})

tracker.start() // returns a promise with session info (sessionID, sessionToken, userUUID)

Alternatively, you can create a new class instance:

import OpenReplay from '@openreplay/tracker';
//...
const tracker = new OpenReplay({
  projectKey: PROJECT_KEY
});
tracker.start(); // returns a promise with session info (sessionID, sessionToken, userUUID)

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,
      ingestPoint: "https://openreplay.mydomain.com/ingest", // when dealing with the self-hosted version of OpenReplay
});
//...
function MyApp() {
  useEffect(() => { // use componentDidMount in case of React Class Component
    tracker.start(); // returns a promise with session info (sessionID, sessionToken, userUUID)
  }, [])
}
import 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
});

There are a set of options you can pass to the constructor. Only projectKey is required.

  • projectKey: string The ID of the project you’re tracking.
  • 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 the data-openreplay-capture HTML attribute to the <iframe> tag. Default: true.
  • __debug__: number For enabling debug logs. Default: 0 (disabled).
    • 2: Errors.
    • 3: Errors and Warnings.
    • 4: Errors, Warnings and Logs.
    • 5: Verbose.
  • autoResetOnWindowOpen?: boolean Enable this option to reset the sessionID when opening a new tab from your application. This overwrites the window.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.
  • assistSocketHost?: string Can be used to set a specific host for assist plugin connection. Defaults to the value of ingestPoint.
  • analytics?: { active: boolean, ingestPoint?: string } Enables the Analytics SDK, which exposes tracker.analytics (events, super properties and user profiles) plus the top-level tracker.track() shorthand. The SDK is not instantiated unless active is true, and tracker.analytics stays null until then. ingestPoint lets self-hosted deployments send analytics to a different endpoint than the replay ingest; it is ignored on OpenReplay Cloud. Default: { active: false }.
  • nextObserver?: boolean Uses the new DOM core: one MutationObserver for the page, iframes and shadow roots, with node liveness tracked structurally (no node maintainer). The recording format is the same. Requires WeakRef; browsers without it use the previous core. Set to false to switch back to the previous core. Leaving it unset logs a one-time console warning about the new default. Default: true.
  • bfcacheRestartThreshold?: number When a page is restored from the browser’s back-forward cache, the tracker resumes the existing session if the page was frozen for less than this many milliseconds, and starts a new session otherwise. Set to 0 to always start a new session on restore. Default: 1800000 (30 minutes).
  • localStorage?: Storage / sessionStorage?: Storage Custom Storage implementations used by the tracker instead of window.localStorage / window.sessionStorage.
  • customAttributes?: string[] Attributes (e.g. 'data-testid') to prefer when building click selectors and input labels.
  • disableScrollmaps?: boolean Don’t send page scroll depth (used for scroll maps). Default: false.
  • nodes?: { maintainer: MaintainerOptions } The nodes.maintainer option helps manage memory and clean up DOM nodes that are no longer in use. It only applies to the previous DOM core (nextObserver: false); the default core doesn’t use a node maintainer. 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.
  • inlineCss?: number: Forces the tracker to record and send remote stylesheets as regular messages instead of caching them on backend. This is useful when CSS files are private, and therefore cannot be cached by OpenReplay backend. When unset, the tracker uses 3 on localhost / 127.0.0.1 and 0 everywhere else. Values can be:
    • 0: The CSS file is cached by the backend (it must be publicly reachable). Default behavior outside localhost.
    • 1: Will attempt to record the linked css file as AdoptedStyleSheet object, reading the stylesheet the page already loaded and falling back to fetching it. Use this for CSS behind a VPN or login. Cross-origin stylesheets need CORS headers.
    • 2: Fetch the file, then simulate AdoptedStyleSheets behavior for the replay.
    • 3: Fetch the file, then save it as plain css inside <style> node — use this option if you have a lot of shorthand properties in your CSS files (covers CSSOM spec bug).
  • css: CssRulesOptions: Provides better support for applications built with emotion-js library (i.e MUI components). It comes with the below parameters:
    • scanInMemoryCSS: boolean: Turn this on if you have issues with emotionjs-created styles. Default: false.
    • checkCssInterval: number: How often to scan tracked stylesheets that have empty rules. Default: 200 (ms).
    • checkLimit: number: Useful for cases with limited number of mutations and/or when stylesheets are hydrated on client after initial render. Applied to each stylesheet individually. The value should = X/checkCssInterval where X is the observation duration in ms. Default: 0 (disabled).
  • respectDoNotTrack?: boolean Do not start tracker if the do-not-track flag is enabled in the user’s browser. Default: false.
  • privateMode?: boolean Masks everything by default: page text, inputs, URLs and titles, console logs, and network URLs, headers and bodies. Opt subtrees back in with the data-openreplay-unmask attribute. See Private Mode. 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. If disabled, make sure to sanitize input fields that may contain sensitive data such as zip codes or credit card details. Default: true.
  • 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).
  • domSanitizer?: (node: Element) => SanitizeLevel Per-element masking rule. See Sanitize Data.
  • captureSanitizer?: (data: CaptureData) => string | null Rewrites or drops attributes, resource URLs, CSS, fonts and inlined SVG sprites after the built-in masking. Canvas and cross-domain iFrame capture are turned off while it is set. See Sanitize Data.
  • urls: Lets you customize how page location events are recorded via following options:
    • urlSanitizer?: (url: string) => string Lets you sanitize page url (to remove usage tokens for example).
    • titleSanitizer?: (title: string) => string Lets you sanitize page title.
    • replaceHashSymbol?: boolean Removes the hash symbol from hash-router URLs so they replay as regular paths (e.g. site.com/#/path becomes site.com/path). Applied before the sanitizers.
  • resourceNameSanitizer?: (url: string) => string Lets you sanitize URLs for recorded network resources.
  • excludedResourceUrls?: string[] Resource timings for these URLs are not recorded.

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.

  • consoleMethods?: Array<'log' | 'info' | 'warn' | 'error' | 'debug' | 'assert'> | null Specifies the list of console methods to capture. Pass [] or null to disable console capture. Default: ['log', 'info', 'warn', 'error', 'debug', 'assert']
  • consoleThrottling?: number Max number of captured console entries per second. Default: 30.
  • captureExceptions?: boolean Captures JavaScript exceptions and stacktraces. Default: true.
  • captureResourceTimings?: 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. Requires captureResourceTimings = true. Default: true.
  • capturePerformance?: boolean For capturing performance metrics such as framerate, CPU and memory consumption. Default: true.
  • longTasks?: boolean For capturing long-animation-frame events. Default false.

The network option relates to capturing network requests and payloads for fetch and XHR.

network?: {
    failuresOnly: boolean;
    sessionTokenHeader: string | boolean;
    ignoreHeaders: Array<string> | boolean;
    capturePayload: boolean; // make sure you sanitize your data before enabling it
    sanitizer: (RequestResponseData) => RequestResponseData | null;
    captureInIframes: boolean;
    axiosInstances: AxiosInstance[];
    tokenUrlMatcher?: (url: string) => boolean;
    disabled?: boolean;
  }

See Network Options for examples and more details on how to redact sensitive data.

The canvas option relates to capturing canvas/WebGL elements:

canvas?: {
  disableCanvas?: boolean
  fixedCanvasScaling?: boolean
  useAnimationFrame?: boolean
  fileExt?: 'webp' | 'png' | 'jpeg' | 'avif'
}
  • disableCanvas?: boolean Disables recording of canvas elements. 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.

Canvas capture is turned off while the captureSanitizer option is set.

See Canvas and WebGL for how to enable this capability and more details on the available options.

The crossdomain option relates to capturing iFrames from different domains. It’s used in conjunction with the captureIFrames option which must be set to true. Set enabled both in the parent page tracker and in the tracker running inside the iFrame.

	crossdomain?: {
		/**
		 * Enable cross-domain tracking
		 * @default false
		 * */
		enabled?: boolean
		/**
		 * iFrame only: origin of the page embedding this one, or a list of them.
		 * The iFrame posts only to that origin and takes commands only from it.
		 * (Check your CSP settings)
		 * @default '*'
		 * */
		parentDomain?: string | string[]
		/**
		 * Parent page only: origins of the child iFrames allowed to join this session,
		 * e.g. ['https://widget.example.com']. Any child iFrame on the page when omitted.
		 * */
		childDomains?: string[]
	}

Cross-domain iFrame capture is turned off while the captureSanitizer option is set. 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.

The mouse option relates to capturing clicks (including selectors used to build clickmaps) and mouse movement.

mouse?: 
  {
  disableClickmaps?: boolean
  trackingOffset?: number
  }
  • disableClickmaps?: boolean Disables selector calculation entirely. Default: false.
  • trackingOffset?: number How many ticks (1 tick = 30ms) to wait between mouse position captures. Lower values can affect performance. Default: 7 (210ms).
  • connAttemptCount?: number Max number of retries when tracker’s HTTP requests fail to reach the backend. Default: 10.
  • connAttemptGap?: number Delay between retry attempts (expressed in ms). The delay grows by this amount with each attempt. Default: 250.
  • flushInterval?: number How often (in ms) buffered messages are uploaded. Default: 30000.
  • __DISABLE_SECURE_MODE?: boolean For allowing insecure connection between tracker and backend on sites without SSL. This should be used for development purposes only: set it from your dev-build flag (e.g. import.meta.env.DEV in Vite, process.env.NODE_ENV === 'development' in Next.js/webpack) so it’s never true in production. Default: false.

Get to know the methods