@spotify-confidence/session-recording
v0.18.17
Published

Keywords
Readme
@spotify-confidence/session-recording
Browser SDK for recording user sessions with Confidence. Captures DOM events in real time and streams them to the Confidence backend for analysis.
Installation
npm install @spotify-confidence/session-recordingQuick start
import { initSessionRecorder } from '@spotify-confidence/session-recording';
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
});That's it. In automatic mode (the default), recording begins as soon as a session is established with the backend. The SDK handles sampling, transport, and reconnection automatically.
Privacy: masking and blocking
The SDK provides two mechanisms to prevent sensitive content from being captured:
Masking replaces text content with • characters while preserving the layout. The element is still visible in the replay, but the actual text is never sent to the backend.
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
maskSelectors: ['.pii', '[data-sensitive]'],
maskInputs: true, // mask all <input>, <textarea>, and contenteditable values (default: true)
});Blocking replaces entire subtrees with an empty placeholder. The blocked element's dimensions are preserved, but nothing inside it — text, images, child nodes — is serialized or sent.
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
blockSelectors: ['video', '.third-party-widget', '[data-block]'],
});maskInputs defaults to true — all input values are masked unless you explicitly opt out.
Context
Context lets you attach custom dimensions to the recording session. These are sent alongside the auto-collected browser metadata (user agent, OS, viewport, language, timezone) in the session init request. Context serves two purposes: it helps you find and filter recordings later, and the backend uses it to target recordings to specific cohorts of your user population (e.g. only record premium users, or users on a specific build version).
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
context: {
visitor_id: 'user-42',
buildVersion: '2.3.1',
environment: 'production',
plan: 'premium',
featureFlags: 'new-checkout-enabled',
},
});Configuration
const recorder = initSessionRecorder({
// Required
clientSecret: '<your-client-secret>',
// Context
context: { visitor_id: 'user-42', buildVersion: '2.3.1' },
// Privacy
maskSelectors: ['.pii'],
blockSelectors: ['video'],
maskInputs: true, // default: true
// Capture options
captureConsoleLogs: true, // capture raw browser console output (default: false)
captureNetworkRequests: false, // capture raw fetch/XHR metadata (default: false)
captureRouteChanges: true, // capture client-side route changes (default: true)
// Recording mode
mode: 'automatic', // 'automatic' (default) or 'manual'
// CSP: self-hosted worker (only needed when data: and blob: are blocked)
// workerUrl: '/confidence-worker.js',
// Debug
debugLogger: msg => console.log(msg), // lifecycle/transport messages (default: off, or console.log when CSR_DEBUG is set in sessionStorage)
});Sanitizing console and network capture
Raw URLs and console output can contain sensitive data from first-party or third-party code. Existing capture settings preserve their current behavior and record raw values, so select a sanitization policy before you enable these channels in production.
Set sanitize: true to remove query strings and fragments from captured network URLs and from URLs in console payloads
and stack traces:
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
captureNetworkRequests: { sanitize: true },
captureConsoleLogs: { levels: ['warn', 'error'], sanitize: true },
});For application-specific data, provide a function. Network sanitizers receive the request URL. Console sanitizers run once for each captured payload and trace string. The built-in sanitizer changes only URL-like text. Use a function to remove secrets stored in other console data.
const redactSecrets = (value: string) => value.replace(/client_secret=[^&\s]+/g, 'client_secret=[REDACTED]');
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
captureNetworkRequests: { sanitize: redactSecrets },
captureConsoleLogs: { levels: ['warn', 'error'], sanitize: redactSecrets },
});Sanitizers run before captured data leaves the recorder. If a sanitizer throws or returns a non-string value, the
affected capture event is dropped. The application request or console call continues unchanged. When CSR_DEBUG is set
in sessionStorage, the SDK logs a prominent SECURITY warning without logging the unsanitized value.
Using with the Confidence flags SDK
If you use both session recording and the Confidence SDK (or an OpenFeature provider) for feature flags, try your best to keep the contexts aligned. Aligning the contexts will make sense when using the Confidence app to set up targeting on recording rules and flag rules. Matching contexts will let you set up policies like "record sessions for users in the beta environment" or "only record premium users" without surprises.
Route parameterization
Routes containing dynamic segments (such as IDs in the URL) are automatically normalized into patterns — for example, /users/123/profile becomes /users/:id/profile. This ensures that per-page metrics are grouped by route rather than by individual page visit, keeping dashboards meaningful and query performance fast.
If your app uses URL patterns that aren't automatically detected, you can provide a custom parameterizeRoute function to control how routes are grouped:
import { defaultParameterizeRoute } from '@spotify-confidence/csr-recorder';
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
parameterizeRoute: route => {
return defaultParameterizeRoute(route).replace(/\/teams\/[^/]+/, '/teams/:slug');
},
});See the @spotify-confidence/csr-recorder README for the full list of default patterns.
Debug logging
The SDK can emit one-line lifecycle and transport messages to help you verify your setup and diagnose issues.
Option 1: pass a logger
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
debugLogger: msg => console.log(msg),
});All messages are prefixed with [CSR] — you can filter your browser console to quickly find them.
Option 2: sessionStorage flag
If you can't (or don't want to) change code, open your browser DevTools console and run:
sessionStorage.setItem('CSR_DEBUG', 'true');Then reload the page. The SDK will detect the flag and log to console.log automatically. Remove it with sessionStorage.removeItem('CSR_DEBUG') when you're done.
Tip: We recommend enabling debug logging when first integrating the SDK. It lets you confirm that a session is established, events are flowing, and the backend is reachable — all before you open the Confidence dashboard.
Content Security Policy (CSP)
The SDK runs its upload logic in a Web Worker. By default it loads the worker from a data: URL, which requires no setup but may be blocked by strict Content Security Policies.
Required directives
| Directive | Value |
| ------------- | --------------------------------------------------------------------------- |
| worker-src | data: (default), or blob: (automatic fallback), or 'self' (see below) |
| connect-src | https://recording.confidence.dev wss://recording-ws.confidence.dev |
If data: is blocked
The SDK automatically falls back to a blob: URL. Most CSPs already allow blob: in worker-src — if yours does, no action is needed.
If both data: and blob: are blocked
Self-host the worker script. The package ships a standalone file you can copy to your static assets:
Option A: copy from node_modules
# After install, copy the worker to your public directory
cp node_modules/@spotify-confidence/session-recording/dist/confidence-worker.js public/Option B: build-tool integration (Vite, webpack, etc.)
import { workerScript } from '@spotify-confidence/session-recording/worker';
import { writeFileSync } from 'fs';
// In a build plugin or script — write the worker to your output directory
writeFileSync('dist/confidence-worker.js', workerScript);Option C: serve via a route (Express, Next.js API route, etc.)
import { workerScript } from '@spotify-confidence/session-recording/worker';
app.get('/confidence-worker.js', (req, res) => {
res.type('application/javascript').send(workerScript);
});Then pass the URL:
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
workerUrl: '/confidence-worker.js',
});Your CSP only needs worker-src 'self' with this setup.
Note: The worker file must stay in sync with the SDK. After upgrading
@spotify-confidence/session-recording, re-copy or re-deploy the worker file. If they're out of sync, the SDK logs aWORKER MISMATCHwarning viadebugLogger.
Troubleshooting
If recording silently fails, open DevTools and look for:
- A
SecurityErrormentioningworker-src— your CSP blocks the worker. Use one of the options above. - A blocked
connect-srcrequest torecording.confidence.dev— add the hosts to your CSP. - A
WORKER MISMATCHlog — your self-hostedconfidence-worker.jsis outdated. Re-copy it fromnode_modules/@spotify-confidence/session-recording/dist/.
Enable debug logging to see the full lifecycle and pinpoint where it fails.
Manual mode
Use manual mode to control when recording starts — useful for gating on user consent or feature flags.
Calling start() uses the same backend eligibility, targeting, allocation, sampling, and admission checks as automatic mode, so the backend may still decide not to record.
const recorder = initSessionRecorder({
clientSecret: '<your-client-secret>',
mode: 'manual',
});
// Later, when ready:
recorder.start();Custom tags and measurements
Attach metadata to a recording for filtering and analysis.
recorder.tag('plan', 'premium');
recorder.measure('checkout_items', 3);API
initSessionRecorder(options): SessionRecorder
Creates a session recorder. Always returns a SessionRecorder — safe to call, never throws.
SessionRecorder
| Method | Description |
| ---------------------- | -------------------------------------------------------------- |
| start() | Start recording. No-op in automatic mode. |
| stop() | Stop recording permanently. Idempotent. |
| tag(key, value?) | Attach a string tag. Tags with the same key accumulate values. |
| measure(key, value?) | Record a numeric measurement. Same key = summed. |
| isRecording | Whether the recorder is actively capturing events. |
License
Apache 2.0 — see LICENSE.
