SDKs

Browser

Capture frontend errors, logs, network calls, and analytics, and connect them to your backend traces

The browser SDK reports errors, logs, and fetch and XHR calls from your web application. It can also record page views and custom events. Requests to your own API carry a trace header, so a click in the browser and the backend work it triggered appear in the same trace.

The SDK works with any framework and ships its TypeScript types. It targets browsers with ES2022 support.

Installation

  1. Create the DSN

    In Monocle, open Services, select your frontend service (or add one), and pick Browser under SDK connection. Copy the DSN.

  2. Install the package
    Terminal
    npm install @monocle.sh/browser-sdk
  3. Initialize the SDK

    Call initMonocle() once, in the entry point of your app, and export the client so the rest of your code can use it:

    src/monocle.ts
    import { initMonocle } from '@monocle.sh/browser-sdk'
    
    export const monocle = initMonocle({
      dsn: 'https://mk_live_xxxxxxxx@ingest.monocle.sh/00000000-0000-4000-8000-000000000001',
      environment: 'production',
    })

With no other option, the SDK records uncaught errors and unhandled promise rejections. Add the network() integration to record fetch and XHR calls.

The browser DSN is public: it ends up in your JavaScript bundle. To prevent other websites from using it, set website restrictions on the service. Never put a project token or a legacy API key in browser code.

You can import the SDK in code that also runs during server rendering. Called on the server, initMonocle() returns an inactive client that sends nothing.

Report the version of each build

Monocle records a deployment each time a new service.version shows up. A browser app has no environment variables at runtime, so the version has to come from your build. With Vite, add @monocle.sh/vite-plugin:

Terminal
npm install -D @monocle.sh/vite-plugin
vite.config.ts
import { defineConfig } from 'vite'
import { monocle } from '@monocle.sh/vite-plugin'

export default defineConfig({
  plugins: [monocle()],
})

The plugin detects the version during vite build and vite dev, in the same order as the server agents: MONOCLE_VERSION, platform variables, CI variables, then the commit of the local .git directory. It injects the version into the modules that import the SDK, and initMonocle() reads it. The position of monocle() in plugins doesn't matter. The plugin makes no network calls, unless MONOCLE_API_KEY is set: it then uploads your source maps.

OptionDescription
releaseA version to use instead of detection. false turns detection and injection off.
injectSet to false to keep the detected version out of the bundle. Defaults to true.
enabledSet to false to turn the plugin off. Defaults to true.
verboseSet to true to log the detected version and its source. Defaults to false.

A serviceVersion passed to initMonocle() wins over the injected version, unless it is a placeholder such as 0.0.0 or dev. Without Vite, pass serviceVersion yourself, from a value your bundler replaces at build time.

Upload source maps

Minified stack traces point to positions in your bundle. To see the original files, functions, and lines in your issues, upload the source maps of each build. See source maps.

Options

OptionDescription
dsnRequired. DSN of the service.
environmentRequired. production, staging, or development.
serviceVersionVersion of the deployed code. Defaults to the version injected by the Vite plugin.
integrationsWhat to capture automatically. Defaults to [errors()].
beforeSendLogCalled with each log before it is sent. Return the record, a modified copy, or null to drop it.
ignoreErrorsRules and functions that drop matching exceptions. See ignore errors.
defaultIgnoreErrorsSet to false to report the browser noise dropped by default. See default filters.
normalizeUrlReplaces sensitive segments in every URL the SDK collects. See hide sensitive URLs.

Choose what to capture

Integrations decide what the SDK captures without any code from you:

IntegrationCapturesDefault
network()fetch and XHR calls as spans, with method, URL, and status.Off
errors()Uncaught errors and unhandled promise rejections.On
consoleLogs()console.debug, info, log, warn, and error calls, as logs.Off
analytics()Page views, and custom events sent with track(). See analytics.Off
replay()Session replays after explicit consent. See session replay.Off
TypeScript
import { analytics, consoleLogs, errors, initMonocle, network } from '@monocle.sh/browser-sdk'

export const monocle = initMonocle({
  dsn,
  environment: 'production',
  integrations: [network(), errors(), consoleLogs({ levels: ['warn', 'error'] }), analytics()],
})

A list you pass replaces the default [errors()]. Keep errors() in it to retain automatic error capture, and add network() to capture network calls. Each integration can appear only once. To report only through the client methods, pass integrations: [].

consoleLogs() captures every console level by default. Use levels to keep fewer. The original console methods still run, and the SDK restores them on shutdown.

Record session replays

The optional replay integration is part of @monocle.sh/browser-sdk. Use the latest patched SDK release and import replay from the separate /replay entry point. Add it to your existing initialization, alongside network() and errors():

src/monocle.ts
import { errors, initMonocle, network } from '@monocle.sh/browser-sdk'
import { replay } from '@monocle.sh/browser-sdk/replay'

export const sessionReplay = replay({
  sessionSampleRate: 0.1,
  captureOnError: true,
  maskAllInputs: true,
  maskAllText: false,
  captureUser: false,
})

export const monocle = initMonocle({
  dsn: 'https://mk_live_xxxxxxxx@ingest.monocle.sh/00000000-0000-4000-8000-000000000001',
  environment: 'production',
  integrations: [network(), errors(), sessionReplay],
})

Adding the integration does not start recording. Call grantConsent() only after the visitor agrees to session replay. Analytics consent is separate. Connect these calls to your consent manager:

TypeScript
import { sessionReplay } from './monocle'

export async function onReplayConsentGranted() {
  await sessionReplay.grantConsent()
}

export function onReplayConsentWithdrawn() {
  sessionReplay.revokeConsent()
}

The recorder loads after grantConsent(). On each page load, restore the visitor's choice through your consent manager before calling it again. revokeConsent() stops capture, clears local replay state, and tries to cancel pending uploads. It does not delete recordings already stored in Monocle. Authorized users can delete those from the replay player.

With these defaults, 10% of consenting sessions record in full. The others keep up to 60 seconds locally and upload when an accepted error promotes the recording. Set sessionSampleRate: 1 while you test, or use sessionSampleRate: 0 with captureOnError: true for error-triggered recordings only. sessionReplay.getStatus() reports states such as inactive, buffering, recording, and quota-exceeded.

Review the captured content

Input values are masked by default. Visible text and images are captured by default, because maskAllText and blockAllMedia default to false. Set maskAllText: true to mask page text. Identity from setUser() is excluded unless you set captureUser: true.

Mark sensitive content before capture starts:

<p data-monocle-replay-mask>Private account balance</p>
<section data-monocle-replay-block>Content that must not be recorded</section>

maskTextSelector and blockSelector add your own selectors. Masking does not make every attribute anonymous. Structural values such as element IDs, classes, and input names must not contain secrets. Use subtree blocking for those regions. Review a test recording before enabling capture for customers.

Find the recording in Monocle

Open Replays in the same project and environment as your DSN. Filter by URL, service, browser, user, or errors. From an error marker, Open issue opens its exact occurrence. An occurrence's replay panel opens the full player, and request markers link to the exact trace and span.

Recordings are kept for 30 days. New recordings stop when the organization's allowance is exhausted, without stopping errors, logs, or traces. See replay allowances and budgets. A new usage period does not restart a recorder that already stopped with quota-exceeded.

Report errors

Capture the errors your code handles with captureException(). Add tags to filter on and extra for any other context:

TypeScript
try {
  await checkout()
} catch (error) {
  await monocle.captureException(error, { tags: { step: 'payment' }, extra: { cartId } })
}

Report a problem that is not an Error with captureMessage(). The second argument is either a level or a context object:

TypeScript
await monocle.captureMessage('Payment form abandoned', 'warning')
await monocle.captureMessage('Payment provider unavailable', {
  level: 'error',
  tags: { provider: 'stripe' },
})

Message levels are debug, info, log, warning, error, and fatal.

Both methods return a promise that resolves once the event is queued, not once Monocle receives it. They never throw. The SDK reports a given Error object once, even if you capture it again.

The context object also accepts user, to override the current user for this event, and traceContext: { traceId, spanId }, to attach the event to a trace your code already knows.

Ignore errors

Drop noisy exceptions with ignoreErrors, without removing errors(). It applies to uncaught errors, unhandled rejections, and captureException(), not to captureMessage(). An exception is dropped when any entry matches:

TypeScript
initMonocle({
  dsn,
  environment: 'production',
  ignoreErrors: [
    { type: 'AbortError' },
    { message: /^Loading chunk \d+ failed/ },
    { url: /^https:\/\/widget\.example\.com\// },
    (event, { error }) => error instanceof ExpectedError && event.mechanism !== 'manual',
  ],
})

A rule matches when every field it sets matches:

FieldCompared with
typeThe error name, such as TypeError.
messageThe error message.
urlThe file of the frame that threw.

A string must be equal to the value, a RegExp must match it. Use a RegExp to match part of a message.

A function receives the same fields, plus mechanism (manual for captureException(), onerror or onunhandledrejection for uncaught errors), and the original thrown value as error. Return true to drop the exception. If the function throws, the exception is kept.

Default filters

Some errors are browser noise rather than failures of your application. Monocle drops them by default, after your ignoreErrors:

  • Script error., reported for cross-origin scripts without any detail.
  • ResizeObserver loop completed with undelivered notifications. and ResizeObserver loop limit exceeded.
  • Errors thrown by ad blockers with Google Tag Manager, wallet extensions (window.solana), the Google Search App, the Instagram and Facebook in-app browsers, CefSharp, and the scripts Firefox and Chrome inject on iOS (__firefox__, __gCrWeb).
  • Errors whose innermost frame comes from a browser extension (chrome-extension:, moz-extension:, safari-extension:, safari-web-extension:, ms-browser-extension:). Your code called by an extension is still reported.
  • Exceptions without any detail: type Error, an empty message, no stack frame, and no cause, such as Promise.reject('').

To report them anyway, set defaultIgnoreErrors: false:

TypeScript
initMonocle({
  dsn,
  environment: 'production',
  defaultIgnoreErrors: false,
})

Error bursts

An error thrown in a loop, for example in requestAnimationFrame, setInterval, or a component that keeps re-rendering, cannot use up your quota. For errors that errors() captures, Monocle sends the first ten occurrences of the same type and message, then one every ten seconds while it repeats. Across all of them, at most 100 are sent at once, then one every five seconds. The limits reset when the page reloads.

captureException() and captureMessage() are never limited. Errors dropped by ignoreErrors or the default filters do not count toward the limits.

Send logs

TypeScript
monocle.logger.info('Checkout started', { items: 3 })
monocle.logger.warn('Payment retry', { attempt: 2 })
monocle.logger.error('Payment failed', { provider: 'stripe' })

The levels are trace, debug, info, warn, error, and fatal. Attribute values are strings, numbers, or booleans. logger sends logs to Monocle without writing to the browser console.

beforeSendLog runs on every log, from logger and from consoleLogs(). Use it to drop logs or to redact them:

TypeScript
initMonocle({
  dsn,
  environment: 'production',
  beforeSendLog: (record) => {
    if (record.source === 'console' && record.level === 'debug') return null

    return record
  },
})

beforeSendLog does not apply to captureException() or captureMessage().

Identify the user

TypeScript
monocle.setUser({ id: user.id, email: user.email, name: user.name })

// On logout
monocle.setUser(null)

The user is attached to the errors, logs, and requests captured after the call. Events already queued keep the user they were captured with. The SDK keeps the user in memory only, so call setUser() again after a page reload.

Analytics events never include the user.

Track page views and events

With analytics() installed, the SDK records a page view for the first page and for each path change, including back and forward navigation. The Analytics page explains what Monocle shows from them. Single-page apps need no router hook. A change to the query string alone is not a new page. Hash routes such as /#/cart all count as the same page.

analytics() also measures the Core Web Vitals of each page: LCP, INP, and CLS. Monocle shows them per page, next to the error rate. See errors and Web Vitals. To turn them off, pass webVitals: false to analytics().

Record a custom event with track():

TypeScript
monocle.track({
  name: 'plan_selected',
  properties: { plan: 'pro', seats: 3, annual: true },
})

The SDK drops the whole event, without an error, if it breaks one of these rules:

  • The name is at most 100 bytes. pageview is reserved.
  • There are at most 20 properties.
  • Property keys are at most 64 bytes. Identity keys such as email, userId, ip, or session_id are rejected. So are keys that start with user, trace, span, or monocle followed by ., _, or -.
  • Property values are strings of at most 256 bytes, finite numbers, or booleans.

Keep personal information out of event names and properties.

Record page views from your router

To decide yourself when a page view counts, turn off automatic page views and call pageview() on the first page and after each completed navigation:

TypeScript
integrations: [network(), errors(), analytics({ autoPageviews: false })]
TypeScript
router.afterEach(() => monocle.pageview())

Leave autoPageviews off in this mode, or each page is counted twice.

Group pages by route

Monocle groups page views by route, such as /blog/:slug, and keeps each real URL, so a route unfolds into the pages behind it. Without any setup, Monocle builds the route by replacing segments that look like identifiers: numbers, UUIDs, hashes, and long tokens. Readable slugs stay as they are.

To use your router's own templates, pass route. Return null when a path has none:

TypeScript
// TanStack Router
analytics({ route: (path) => router.getMatchedRoutes(path)[2]?.fullPath ?? null })

// Vue Router
analytics({ route: (path) => router.resolve(path).matched.at(-1)?.path ?? null })

Any parameter syntax works: :id, $id, [id], or {id}.

Exclude pages

Use ignorePaths to leave pages out of analytics. A string must be equal to the path, a RegExp must match it, and a function must return true. Page views and events on an excluded page are not sent:

TypeScript
analytics({
  ignorePaths: ['/login', /^\/admin(\/|$)/, (path) => path.endsWith('/preview')],
})

Paths are checked against the real path, before normalizeUrl. If a function throws, the page is excluded.

Campaigns

The SDK sends the utm_source, utm_medium, utm_campaign, utm_term, and utm_content parameters of the landing URL with every page view and event of that page load. Monocle uses them to attribute the visit to its campaign. The SDK drops a UTM value that is longer than 128 bytes or that looks like an email address, a phone number, or an IP address.

Connect frontend and backend traces

The network() integration adds a traceparent header to requests sent to your own origin. Your backend, if instrumented with OpenTelemetry, continues the same trace.

If your API is on another origin, list it in tracePropagationTargets, and allow the traceparent request header in your API's CORS configuration:

TypeScript
network({ tracePropagationTargets: ['https://api.example.com'] })

tracePropagationTargets replaces the default, so add your own origin to the list if you still need it. To stop sending the header while still recording requests, pass tracePropagationTargets: [].

Exclude requests

Use ignoreUrls to stop recording some requests, such as third-party scripts. A string must be contained in the URL, a RegExp must match it, and a function must return true:

TypeScript
network({
  ignoreUrls: [
    'analytics.example.com',
    /^https:\/\/widget\.example\.net\//,
    (url) => url.endsWith('/health'),
  ],
})

ignoreUrls receives the absolute URL without query string or hash, before normalizeUrl. Excluded requests still run, but they get no traceparent header. If a function throws, the request is excluded.

Hide sensitive URLs

The SDK never sends the query string or hash of a URL, but paths can still contain tokens or identifiers. Use normalizeUrl to replace them:

TypeScript
initMonocle({
  dsn: 'YOUR_SERVICE_DSN',
  environment: 'production',
  normalizeUrl: (url) => url.replace(/\/invitations\/[^/]+/, '/invitations/:token'),
})

It applies to every URL the SDK collects: the URL and span name of network requests, the page URL of errors and messages, and the path and route of analytics page views. It receives an absolute URL without credentials, query string, or hash.

Return null to leave a URL out. The request or page view is then not recorded, but an error is still reported, without its page URL. If the function throws, the SDK does the same as for null.

Stack traces, error messages, and the data you pass to the SDK are not rewritten.

analytics({normalizePath}) and network({normalizeUrl}) are deprecated. They still work and run before normalizeUrl, so you can move your function to initMonocle at any time.

Flush and shut down

The SDK sends events in the background, in batches. When the tab is hidden, it tries to send what is queued. To send pending events right away, or to stop the client in tests or on teardown, call:

TypeScript
await monocle.flush()
await monocle.shutdown()

shutdown() stops capture, removes the SDK's patches on fetch, XHR, and the console, and sends what is left. Shut down a client before you initialize another one.

Delivery is best effort. Events still queued when the tab closes can be lost, and nothing is kept across page reloads.

Write your own integration

An integration is an object with a unique name and a synchronous setup() that returns the collectors to run. The SDK calls start() on each collector when the client starts and stop() when it shuts down. Use client to send logs, errors, and messages:

TypeScript
import type { BrowserIntegration } from '@monocle.sh/browser-sdk/types'

export function visibility(): BrowserIntegration {
  return {
    name: 'visibility',
    setup: ({ client }) => {
      const onChange = () =>
        client.logger.info('Visibility changed', { state: document.visibilityState })

      return {
        instrumentations: [
          {
            start: () => document.addEventListener('visibilitychange', onChange),
            stop: () => document.removeEventListener('visibilitychange', onChange),
          },
        ],
      }
    },
  }
}

Add it to integrations next to the built-in ones.

The public types live in two entry points:

TypeScript
import type {
  BrowserClient,
  BrowserIntegration,
  BrowserOptions,
} from '@monocle.sh/browser-sdk/types'
import type { AnalyticsEvent, AnalyticsProperties } from '@monocle.sh/browser-sdk/analytics/types'

Migrate from an API key

Configurations with endpoint, apiKey, and serviceName still work. To move to a DSN, create one for the service and replace these three options with dsn. Existing keys keep working until you revoke them. See the DSN migration guide.

Privacy

The network, errors, console, and analytics integrations do not record the page DOM. The SDK does not automatically capture request or response bodies, headers, or cookies. Diagnostic URLs are sent without credentials, query string, or hash. analytics() uses no cookies or browser storage and doesn't send the user's identity.

Analytics keeps the landing URL's utm_source, utm_medium, utm_campaign, utm_term, and utm_content for campaign attribution. The collector drops campaign values that look like an email address, phone number, or IP address.

URL paths, error messages, stack traces, and the data you pass to the SDK can still contain personal information. Check what you send, and use normalizeUrl and beforeSendLog to remove it.

Session replay privacy

The optional replay() integration from @monocle.sh/browser-sdk/replay records page content after you call grantConsent(). Visible page text is recorded by default: maskAllText defaults to false. Set maskAllText: true to mask text, or use maskTextSelector to mask selected text. Input masking is enabled by default with maskAllInputs: true.

Text masking does not remove every sensitive value from the DOM. Hidden input values, DOM attributes, and CSS can contain personal information or secrets. Use blockSelector or data-monocle-replay-block to exclude sensitive subtrees, and inspect captures before enabling replay for visitors. Describe the content you record in your consent notice. Call revokeConsent() to stop capture; it does not delete recordings already sent.

Not included

Without the optional replay() integration, the SDK does not record sessions. Custom spans are not included.

Search documentation

Search pages and sections of the Monocle documentation