Documentation

The Webrec SDK is a lightweight JavaScript library that captures session recordings, errors, and analytics data from your web application. This guide covers installation, configuration, and the full API reference.

Installation

NPM / Yarn / pnpm

Install the SDK from npm (available once published):

Terminal
npm install @webrec/sdk

# or with yarn
yarn add @webrec/sdk

# or with pnpm
pnpm add @webrec/sdk

Note: The npm package will be available once published. In the meantime, use the script tag method below.

Then import and initialize in your application entry point:

app.ts
import { WebRec } from '@webrec/sdk';

WebRec.init({
  apiKey: 'your-project-api-key',
});

Script Tag

Include the SDK via a script tag. This is the recommended method until the npm package is published, and is useful for sites that don't use a JavaScript bundler.

HTML
<script src="https://api.webrec.app/v1/webrec.min.js"></script>

<script>
  WebRec.init({
    apiKey: 'your-project-api-key',
  });
</script>

After the SDK is published to npm, you can also use CDN links:

HTML (after npm publish)
<!-- Via unpkg -->
<script src="https://unpkg.com/@webrec/sdk@latest/dist/webrec.umd.js"></script>

<!-- Or via jsdelivr -->
<script src="https://cdn.jsdelivr.net/npm/@webrec/sdk/dist/webrec.umd.js"></script>

The script tag version loads asynchronously to avoid blocking page rendering.

Configuration

Pass a configuration object to WebRec.init(). All options except apiKey are optional.

OptionTypeDefaultDescription
apiKeystring(required)Your project API key from the Webrec dashboard.
endpointstring"https://api.webrec.app/v1"Custom API endpoint for self-hosted or proxy setups.
sampleRatenumber100Percentage of traffic to record (0-100).
maskAllInputsbooleantrueMask all input field values in recordings.
blockClassstring"wr-block"CSS class to exclude elements from recording.
blockSelectorstring"[data-wr-block]"CSS selector for elements to exclude from recording.
ignoreClassstring"wr-ignore"CSS class to ignore interactions on elements.
ignoreSelectorstring"[data-wr-ignore]"CSS selector for elements to ignore interactions on.
captureConsolebooleantrueCapture console.log, warn, error output.
captureNetworkbooleantrueCapture network requests and responses.
captureErrorsbooleantrueCapture JavaScript errors and stack traces.
recordCanvasbooleanfalseRecord canvas/WebGL elements. Increases CPU usage.
collectFontsbooleantrueCollect fonts used on the page for accurate replay.
respectDoNotTrackbooleantrueRespect the browser Do Not Track setting.
sessionTimeoutnumber1800000Session timeout in milliseconds (default 30 minutes).
batchSizenumber50Number of events to batch before sending.
flushIntervalnumber5000Interval in milliseconds between flushes.
maxQueueSizenumber2000Max events to hold in memory before evicting oldest.
maxRetriesnumber3Max retry attempts for failed flushes.
minTimeOnPagenumber0Minimum time in ms on page before recording starts.
minSessionDurationnumber0Minimum session duration in seconds before data is sent.
startDelaynumber0Delay in ms before recording starts after init.
debugbooleanfalseEnable verbose debug logging to console.

Privacy sub-config

You can also pass a privacy object for granular control:

Privacy options
WebRec.init({
  apiKey: 'wr_proj_abc123',
  privacy: {
    maskInputs: true,          // Mask form input values (default true)
    maskTextContent: false,    // Mask all text content (default false)
    blockSelectors: ['.secret-panel'],
    ignoreSelectors: ['.analytics-only'],
  },
});

Sampling sub-config

Control the sampling of high-frequency events:

Sampling options
WebRec.init({
  apiKey: 'wr_proj_abc123',
  sampling: {
    mousemove: 50,     // Sample mousemove every 50ms (or true/false)
    scroll: 150,       // Sample scroll every 150ms
    input: 'last',     // Capture 'last' input value or 'all' keystrokes
  },
});

URL Filtering

Control which pages are recorded using URL patterns:

URL filtering
WebRec.init({
  apiKey: 'wr_proj_abc123',
  ignoreUrls: ['/admin.*', '/internal.*'],  // Skip these URLs
  allowUrls: ['/app.*', '/checkout.*'],     // Only record these URLs
});
Full example
WebRec.init({
  apiKey: 'wr_proj_abc123',
  sampleRate: 50,               // Record 50% of traffic
  maskAllInputs: true,
  captureConsole: true,
  captureNetwork: true,
  captureErrors: true,
  respectDoNotTrack: true,
  blockClass: 'wr-block',
  sessionTimeout: 1800000,       // 30 minutes
  debug: false,
});

API Reference

WebRec.init(config)

Initialize the SDK with the given configuration. Must be called once before any other API methods.

WebRec.init({
  apiKey: 'wr_proj_abc123',
});

WebRec.identify(userId, traits?)

Associate the current session with a known user. Call this after the user logs in. Traits are optional metadata attached to the user profile.

WebRec.identify('user_42', {
  name: 'Jane Doe',
  email: 'jane@example.com',
  plan: 'pro',
});

WebRec.track(event, properties?)

Track a custom event with optional properties. Events appear as markers in the session timeline and can be used for funnel analysis.

WebRec.track('purchase_completed', {
  orderId: 'ORD-1234',
  total: 59.99,
  currency: 'USD',
});

WebRec.start()

Manually start recording. Only needed if you set autoStart: false in the configuration or have called stop(). Useful for starting recording only after user consent.

// Start recording after consent
document.getElementById('consent-btn')
  .addEventListener('click', () => {
    WebRec.start();
  });

WebRec.stop()

Stop the current recording. The session data collected so far will still be uploaded. You can call start() again to resume recording.

// Stop recording when user navigates to sensitive page
WebRec.stop();

WebRec.destroy()

Completely tear down the SDK, remove all event listeners, and stop recording. Use this for cleanup in single-page applications when unmounting. After calling destroy(), you must call init() again to use the SDK.

// Cleanup on app unmount
WebRec.destroy();

WebRec.getSessionId()

Returns the current session ID, or null if the SDK is not initialized. Useful for correlating session recordings with your own backend logs.

const sessionId = WebRec.getSessionId();
console.log('Webrec session:', sessionId);

// Attach to support tickets, bug reports, etc.
fetch('/api/support', {
  method: 'POST',
  body: JSON.stringify({
    message: 'Help!',
    webrecSession: sessionId,
  }),
});

WebRec.getSessionUrl()

Returns a direct URL to the current session replay in the Webrec dashboard. Useful for linking from internal tools or error trackers.

const url = WebRec.getSessionUrl();
// e.g. "https://app.webrec.app/projects/xxx/sessions/yyy"

WebRec.isRecording()

Returns true if the SDK is currently recording, false otherwise.

if (WebRec.isRecording()) {
  console.log('Recording is active');
}

In-App Surveys

Webrec includes an in-app survey widget that lets you collect feedback directly from your users. Surveys are configured in the dashboard and delivered automatically via the SDK.

Enabling Surveys

Surveys are enabled by default when you install the SDK. The widget loads asynchronously and will not affect page performance. You can disable surveys via configuration:

Disable surveys
WebRec.init({
  apiKey: 'wr_proj_abc123',
  surveys: false,  // Disable the survey widget
});

Survey Types

Create surveys in the Webrec dashboard under Surveys. Supported question types:

  • - NPS: Net Promoter Score (0-10 scale) with optional follow-up question
  • - Rating: Star ratings (1-5) for quick satisfaction feedback
  • - Choice: Single-select or multi-select from pre-defined options
  • - Open text: Free-form text responses for detailed feedback

Survey Targeting

Target surveys by URL, user properties, or behaviour. Configure targeting rules in the dashboard:

  • - URL rules: Exact match, contains, or regex patterns
  • - User properties: Target by plan, role, signup date, or any trait passed to identify()
  • - Behaviour: Show after a custom event is tracked or after N sessions

Survey Events

The SDK emits events you can listen to for custom integrations:

Survey events
WebRec.on('survey:shown', (survey) => {
  console.log('Survey shown:', survey.id);
});

WebRec.on('survey:completed', (survey, response) => {
  console.log('Survey completed:', survey.id, response);
});

WebRec.on('survey:dismissed', (survey) => {
  console.log('Survey dismissed:', survey.id);
});

Frustration Detection

Webrec automatically detects user frustration signals and surfaces them in the dashboard. Frustration detection requires no additional configuration -- it works out of the box.

Dead Click Detection

A dead click is a click on an element that produces no visible response -- no navigation, no DOM change, no network request. Dead clicks often indicate broken buttons, missing links, or elements that look interactive but are not.

Dead clicks are detected automatically and appear in the session timeline, session list filters, and heatmaps. You can filter sessions by dead click count in the dashboard.

Error Click Correlation

When a click triggers a JavaScript error within a short time window, Webrec correlates the click with the error. Error clicks are highlighted in the session timeline and can be used as a filter in the session list.

Frustration Score

Each session receives a frustration score -- a composite value calculated from dead clicks, rage clicks, error clicks, and other frustration signals. Use the frustration score to prioritise which sessions to review:

  • - 0-25: Low frustration -- normal usage
  • - 25-50: Moderate -- some friction detected
  • - 50-75: High -- significant frustration signals
  • - 75-100: Critical -- the user had a very poor experience

Configuration

Frustration detection is enabled by default. You can customise thresholds:

Frustration config
WebRec.init({
  apiKey: 'wr_proj_abc123',
  frustration: {
    deadClickTimeout: 1000,    // ms to wait for response (default 1000)
    rageClickThreshold: 3,     // clicks in rapid succession (default 3)
    rageClickWindow: 800,      // ms window for rage clicks (default 800)
  },
});

Privacy Controls

Webrec is built with privacy as a core consideration. The SDK provides multiple mechanisms to control what data is captured.

Input Masking

By default, all input values (<input>, <textarea>, <select>) are masked in recordings and replaced with asterisks. This prevents accidental capture of passwords, personal data, and other sensitive information.

// Default behavior: all inputs masked
WebRec.init({ apiKey: '...', maskAllInputs: true });

// To unmask specific inputs, add the wr-unmask class:
// <input class="wr-unmask" type="text" placeholder="Search..." />

Element Blocking

Add the wr-block CSS class or data-wr-block attribute to any element to completely exclude it from recordings. Blocked elements are replaced with a placeholder in the replay.

HTML
<!-- Using CSS class -->
<div class="wr-block">
  This content will not appear in recordings.
</div>

<!-- Using data attribute -->
<div data-wr-block>
  <p>Sensitive information here</p>
</div>

<!-- Block specific sections -->
<section class="wr-block" id="payment-form">
  <input type="text" name="card-number" />
  <input type="text" name="cvv" />
</section>

Text Content Masking

For maximum privacy, enable maskTextContent via the privacy config to replace all visible text with generic characters. This is useful for applications handling highly sensitive data.

WebRec.init({
  apiKey: '...',
  privacy: {
    maskTextContent: true,
    // You can still see page structure and user behavior,
    // but all text content is masked.
  },
});

Network Privacy

Network capture records request URLs and status codes by default. Request and response bodies are not captured unless you explicitly use the captureNetwork option. You can also use ignoreUrls to filter which endpoints are captured.

WebRec.init({
  apiKey: '...',
  captureNetwork: true,
  ignoreUrls: [
    '/api/auth.*',        // Exclude auth endpoints
    'stripe\.com',       // Exclude payment URLs
  ],
});

Do Not Track

The SDK respects the browser's Do Not Track setting by default. If a user has enabled DNT, the SDK will not record. You can override this behavior:

WebRec.init({
  apiKey: '...',
  respectDoNotTrack: false,  // Record even if DNT is enabled
});

GDPR Compliance

This section covers how to use Webrec in compliance with the General Data Protection Regulation (GDPR). As a Webrec customer, you are the data controller for end-user data collected via the SDK. Webrec acts as a data processor on your behalf.

Masking Sensitive Data

To comply with data minimisation principles, use the SDK's masking features to avoid capturing personal data unnecessarily:

GDPR-focused configuration
WebRec.init({
  apiKey: 'wr_proj_abc123',
  maskAllInputs: true,            // Mask all form inputs
  respectDoNotTrack: true,         // Respect browser DNT
  captureNetwork: true,
  ignoreUrls: ['/api/auth.*'],     // Don't capture auth requests
  privacy: {
    maskInputs: true,
    maskTextContent: false,
    blockSelectors: [
      '.personal-data',           // Block PII sections
      '#payment-form',            // Block payment forms
      '[data-gdpr-sensitive]',    // Block custom-marked elements
    ],
  },
});

Data Retention

Session recordings are retained according to your plan's retention period:

  • Free plan: 7 days
  • Pro plan: 90 days
  • Business plan: 365 days (configurable)

Recordings are automatically and permanently deleted after the retention period. You can also manually delete sessions from the dashboard or via the API.

End User Rights

As data controller, you are responsible for handling data subject requests from your end users. Webrec provides tools in the dashboard to:

  • - Search for sessions by user ID (to fulfil access requests)
  • - Delete all sessions for a specific user ID (right to erasure)
  • - Export session data in a portable format (right to portability)

Contact privacy@webrec.app if you need assistance processing data subject requests.

Data Processing Agreement

For GDPR compliance, you may need a Data Processing Agreement (DPA) with Webrec. Our DPA is included in the Terms of Service. It covers the obligations of both parties, sub-processors, data security measures, and breach notification procedures.

Data Hosting Location

Webrec Cloud stores data in Google Cloud Platform's europe-west2 region (London, UK). For self-hosted deployments, you control exactly where data is stored.

Framework Guides

React / Next.js

In React applications, initialize the SDK in a top-level component or layout. Use an effect to ensure it runs only on the client.

app/layout.tsx (Next.js App Router)
'use client';

import { useEffect } from 'react';
import { WebRec } from '@webrec/sdk';

export default function RootLayout({ children }) {
  useEffect(() => {
    WebRec.init({
      apiKey: process.env.NEXT_PUBLIC_WEBREC_KEY,
    });

    return () => {
      WebRec.destroy();
    };
  }, []);

  return <html><body>{children}</body></html>;
}

Vue.js / Nuxt

In Vue applications, initialize in a plugin or in your main app file.

plugins/webrec.client.ts (Nuxt)
import { WebRec } from '@webrec/sdk';

export default defineNuxtPlugin(() => {
  WebRec.init({
    apiKey: useRuntimeConfig().public.webrecKey,
  });
});

Vanilla JavaScript

For vanilla JavaScript applications, initialize the SDK after the DOM is ready.

main.js
import { WebRec } from '@webrec/sdk';

document.addEventListener('DOMContentLoaded', () => {
  WebRec.init({
    apiKey: 'wr_proj_abc123',
  });
});

Dashboards & Export API

Webrec provides APIs for managing custom dashboards, exporting data, and interacting with surveys programmatically.

Custom Dashboards

Custom dashboards are created and managed in the Webrec web application. Drag and drop widgets to build analytics views tailored to your team. Available widget types:

  • - Metric: Single value with trend indicator (sessions, errors, frustration score, etc.)
  • - Time series: Line or bar chart showing a metric over time
  • - Funnel: Conversion funnel visualisation
  • - Table: Tabular data with sorting and filtering
  • - Retention: Cohort retention heatmap
  • - Journey: Sankey flow diagram of user paths

CSV Data Export

Export session, error, and analytics data as CSV files from the dashboard. You can also trigger exports programmatically via the REST API:

Export API
// Export sessions as CSV
GET /v1/projects/:projectId/export/sessions?format=csv
  &from=2026-01-01&to=2026-03-01

// Export errors as CSV
GET /v1/projects/:projectId/export/errors?format=csv
  &from=2026-01-01&to=2026-03-01

// Export analytics data as CSV
GET /v1/projects/:projectId/export/analytics?format=csv
  &metric=pageviews&from=2026-01-01&to=2026-03-01

// Headers
Authorization: Bearer <your-api-key>

Surveys REST API

Create and manage surveys via the REST API. Useful for automating survey creation or integrating with your CI/CD pipeline:

Surveys API
// List surveys
GET /v1/projects/:projectId/surveys

// Create a survey
POST /v1/projects/:projectId/surveys
{
  "name": "Feature satisfaction",
  "type": "rating",
  "question": "How satisfied are you with this feature?",
  "targeting": {
    "url_contains": "/dashboard"
  }
}

// Get survey responses
GET /v1/projects/:projectId/surveys/:surveyId/responses

// Headers
Authorization: Bearer <your-api-key>

Session Tags & Collections

Tag sessions and organise them into collections for team review:

Tags & Collections
// Add tags to a session
POST /v1/projects/:projectId/sessions/:sessionId/tags
{
  "tags": ["bug", "checkout-flow"]
}

// Create a collection
POST /v1/projects/:projectId/collections
{
  "name": "Sprint 42 Review",
  "session_ids": ["sess_abc", "sess_def", "sess_ghi"]
}

// List saved search views
GET /v1/projects/:projectId/views

// Headers
Authorization: Bearer <your-api-key>

Examples

Identifying Users After Login

// After successful authentication
async function onLogin(user) {
  WebRec.identify(user.id, {
    name: user.name,
    email: user.email,
    plan: user.subscription.plan,
    company: user.company?.name,
  });
}

Tracking Conversion Funnels

// Track each step of a checkout funnel
WebRec.track('checkout_started');

// ... user fills in shipping
WebRec.track('shipping_completed', { method: 'express' });

// ... user enters payment
WebRec.track('payment_entered');

// ... order confirmed
WebRec.track('order_completed', {
  orderId: order.id,
  total: order.total,
  items: order.items.length,
});

Linking Error Reports to Sessions

// Errors are captured automatically, but you can
// attach the session ID to your own error reports:
window.addEventListener('error', (event) => {
  myErrorTracker.report({
    message: event.message,
    stack: event.error?.stack,
    webrecSessionId: WebRec.getSessionId(),
    webrecSessionUrl: WebRec.getSessionUrl(),
  });
});

Single-Page Application Cleanup

// React example with cleanup
import { useEffect } from 'react';
import { WebRec } from '@webrec/sdk';

function App() {
  useEffect(() => {
    WebRec.init({ apiKey: 'wr_proj_abc123' });
    return () => WebRec.destroy();
  }, []);

  return <div>...</div>;
}

Need help?

If you have questions or run into issues, reach out to us at support@webrec.app or open an issue on GitHub.