npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@spotify-confidence/session-recording

v0.18.17

Published

![](https://img.shields.io/badge/lifecycle-beta-a0c3d2.svg)

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-recording

Quick 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 a WORKER MISMATCH warning via debugLogger.

Troubleshooting

If recording silently fails, open DevTools and look for:

  • A SecurityError mentioning worker-src — your CSP blocks the worker. Use one of the options above.
  • A blocked connect-src request to recording.confidence.dev — add the hosts to your CSP.
  • A WORKER MISMATCH log — your self-hosted confidence-worker.js is outdated. Re-copy it from node_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.