Monoscope Browser SDK
The Monoscope Browser SDK is a lightweight JavaScript library for adding session replay, performance tracing, error tracking, and web vitals to your web applications.
When used together with the Monoscope Server SDKs, you gain end-to-end observability — seamlessly connecting user interactions in the browser to backend services, APIs, and databases.
This means you can:
- Replay user sessions to see exactly what happened.
- Trace requests from the frontend, through your backend, and into your database.
- Capture errors and console logs with full context and breadcrumbs for faster debugging.
- Collect Web Vitals (CLS, INP, LCP, FCP, TTFB) automatically.
- Track SPA navigations across pushState, replaceState, and popstate.
Installation
Install via npm/bun:
npm install @monoscopetech/browser
Or include it directly in your HTML using a <script> tag:
<script src="https://unpkg.com/@monoscopetech/browser@latest/dist/monoscope.min.js"></script>
Quick Start
Initialize Monoscope with your API key (found in your project settings):
import Monoscope from "@monoscopetech/browser";
const monoscope = new Monoscope({
apiKey: "YOUR_API_KEY",
});
// Identify the current user
monoscope.setUser({
id: "user-123",
email: "[email protected]",
});
On localhost, debug mode is auto-enabled — you’ll see a status overlay and console diagnostics. Call monoscope.test() to verify your setup:
const result = await monoscope.test();
console.log(result); // { success: true, message: "Test span sent successfully." }
React / Next.js
For React and Next.js apps, the SDK provides idiomatic bindings with context providers, hooks, and an error boundary via the @monoscopetech/browser/react subpath export.
See the dedicated React / Next.js integration guide for setup, hooks API, and component instrumentation examples.
Configuration
The Monoscope constructor accepts the following options:
| Name | Type | Description |
|---|---|---|
apiKey |
string |
Required – Your Monoscope API key (found in project settings). |
serviceName |
string |
Service name. Defaults to location.hostname. |
projectId |
string |
Deprecated alias for apiKey. |
exporterEndpoint |
string |
Endpoint for exporting traces. Defaults to Monoscope’s ingest endpoint. |
propagateTraceHeaderCorsUrls |
RegExp[] |
URL patterns where trace context headers should be propagated. Defaults to same-origin only. |
resourceAttributes |
Record<string, string> |
Additional OpenTelemetry resource attributes. |
instrumentations |
unknown[] |
Additional OpenTelemetry instrumentations to register. |
replayEventsBaseUrl |
string |
Base URL for session replay events. Defaults to Monoscope’s ingest endpoint. |
enableNetworkEvents |
boolean |
Include network timing events in document load spans. |
user |
MonoscopeUser |
Default user information for the session. |
debug |
boolean |
Enable debug logging to the console. |
sampleRate |
number |
Trace sampling rate from 0 to 1. Default 1 (100%). |
replaySampleRate |
number |
Replay sampling rate from 0 to 1. Default 1 (100%). |
enabled |
boolean |
Whether to start collecting data immediately. Default true. |
resourceTimingThresholdMs |
number |
Minimum resource duration (ms) to report. Default 200. |
enableUserInteraction |
boolean |
Trace user clicks and interactions, linking them to downstream network calls. Default false. |
User Object
The MonoscopeUser object can contain:
| Name | Type | Description |
|---|---|---|
email |
string |
User’s email address. |
full_name |
string |
User’s full name. |
name |
string |
User’s preferred name. |
id |
string |
User’s unique identifier. |
roles |
string[] |
User’s roles. |
Additional string-keyed attributes are also accepted and forwarded as custom user attributes.
API
setUser(user: MonoscopeUser)
Associates the given user with the current session. Can be called at any time.
monoscope.setUser({
id: "user-123",
email: "[email protected]",
});
startSpan(name, fn)
Creates a custom OpenTelemetry span. The span is automatically ended when the function returns. Supports async functions.
monoscope.startSpan("checkout", (span) => {
span.setAttribute("cart.items", 3);
// ... your logic
});
recordEvent(name, attributes)
Records a custom event as a span with the given attributes.
monoscope.recordEvent("button_click", {
"button.name": "subscribe",
"button.variant": "primary",
});
getSessionId()
Returns the current session ID — useful for tagging custom spans or correlating with backend logs.
const sessionId = monoscope.getSessionId();
getTabId()
Returns the current tab ID (unique per browser tab).
const tabId = monoscope.getTabId();
test()
Sends a test span and flushes it to verify the connection is working.
const result = await monoscope.test();
console.log(result.success); // true if the span was accepted
enable() / disable()
Dynamically enable or disable all data collection.
monoscope.disable(); // pause collection
monoscope.enable(); // resume collection
isEnabled()
Returns whether the SDK is currently enabled.
destroy()
Stops all collection, flushes pending data, and shuts down the OpenTelemetry provider. Call this when your application is being torn down.
await monoscope.destroy();
Custom Instrumentation
Custom Spans
Use startSpan() to instrument specific operations with timing and attributes. It supports both sync and async functions — the span is automatically ended when the function returns or the promise resolves.
// Sync
monoscope.startSpan("parse-config", (span) => {
span.setAttribute("config.size", rawConfig.length);
return parseConfig(rawConfig);
});
// Async
const data = await monoscope.startSpan("fetch-dashboard", async (span) => {
span.setAttribute("dashboard.id", dashboardId);
const res = await fetch(`/api/dashboards/${dashboardId}`);
span.setAttribute("http.status", res.status);
return res.json();
});
Custom Events
Use recordEvent() to track discrete events without wrapping a code block:
monoscope.recordEvent("feature_flag_evaluated", {
"flag.name": "new-checkout",
"flag.value": true,
});
React Components
For instrumenting React components with custom spans and events, see the React / Next.js guide.
Additional OpenTelemetry Instrumentations
Pass extra OTel instrumentations via the instrumentations config to extend tracing beyond the built-in set:
import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-task";
const monoscope = new Monoscope({
apiKey: "YOUR_API_KEY",
instrumentations: [new LongTaskInstrumentation()],
});