NestJS Observe · Documentation

Frontend monitoring

Web Vitals, JavaScript errors and API calls from your web frontend, joined to your Nest traces.

@nestjs/observe-browser is the browser SDK for your web frontend. It records every page view with its Web Vitals and what caused them, the page's fetch and XHR calls, the JavaScript errors it throws with what happened before each and what caused them, the scripts, styles and images it loaded, and the spans your own code times. Its calls to your Nest API carry the page view's trace id, so the page view and the requests it caused are one trace: the browser half first, and the Nest half under the call that made it.

It works on its own, or beside the OpenTelemetry you already have in the browser - see Beside OpenTelemetry in the browser.

Setting up

A frontend needs a browser application to report into, the SDK in its bundle, and - when it calls an API on another origin - two headers let through that API's CORS.

A browser application

A frontend reports into a browser application: an application of type Browser. Create it on the Applications page of the project its Nest services report into - a trace is read per project, so that's where its two halves meet - with the origins its pages are served from. It comes with two credentials:

  • Public key (pk_...) - goes in observe.init(). It can only send page views and errors, so it's safe in a bundle, and it stays readable on the application.
  • Upload token (ut_...) - for uploading source maps from CI, and nothing else. It's shown once, when it's issued: store it as a secret.

Allowed origins are where the key may send from, 1 to 20 of them: exact origins, scheme and port included (https://app.example.com, http://localhost:4200), or a wildcard on one leading label - https://*.example.com covers https://eu.example.com, but not https://example.com or https://a.b.example.com. Anything else is refused - see When the key is refused.

www counts. https://example.com and https://www.example.com are two origins, and a site that answers on one usually redirects from the other: list the one your pages end up on, or both. With only the other, every page view is refused. The dashboard points out the one a list leaves out, and adds it on a click.

Rotating the key issues a new public key and a new upload token, revokes the old pair, and keeps the origins. An edit to the origins, or a rotation, takes effect within 30 seconds. Both need write access to the project: a read-only member sees the key and its origins, and changes neither. How browser applications count against your plan is under Applications → Browser applications.

Installing the SDK

npm install @nestjs/observe-browser

On a page without a framework adapter, start it once, as early as the page's own code allows:

import { observe } from "@nestjs/observe-browser";

observe.init({
  publicKey: "pk_...",
  release: "2f1c9e7", // the build this page runs, e.g. its git SHA
  environment: "production",
});

init() takes effect once - later calls are ignored - and does nothing where there is no window, so calling it during server-side rendering is harmless. It never throws: if starting fails, it undoes what it began and warns in the console. Errors you pass to observe.captureError() before it runs - up to 10 - are kept, and reported once it does.

Option Default Description
publicKey - required The browser application's public key.
enabled true false: init() does nothing - for a build or an environment that shouldn't report.
endpoint https://observe-api.nestjs.com Where beacons go. Point it at a first-party proxy, on a path of its own, to get past ad blockers - see Nothing arrives.
release - The build the page runs, up to 64 characters. Source maps are matched within it.
environment - production, staging and so on, up to 32 characters.
sampleRate 1 The share of sessions recorded - see Sampling.
viewSampleRate 1 The share of page views recorded within a recorded session: a number, or a function of the view - see Sampling.
errorSampleRate 1 The share of errors kept within a recorded session.
tracePropagationTargets Same origin only Requests that get the trace headers: a string matches as a substring of the absolute URL, a RegExp is tested against it. Setting it replaces the default.
openTelemetry "auto" "auto": a view that starts inside an active OpenTelemetry span takes its trace id. "off": never.
consent "granted" "pending" holds everything in memory until observe.consent(true) - see Consent.
viewOnReturn true A new page view when the visitor comes back to a tab whose view was sent, and the page does something - see Page views. false: none.
beforeSend - (event) => event | null: a last look at each view and error before it's queued. null drops it.
ignoreErrors - Errors to drop, matched against "Class: message" and against the message.
ignoreUrls - URLs to leave alone: requests to them get no span, breadcrumb or asset timing, and an error whose top frame is in a script from one is dropped. For extensions and third parties.
allowUrls - Keeps only the errors whose top frame is in a script from a matching URL - and those with no frames - a string or a RegExp. Your own bundles, when the page loads others'.
ignoreSpans - Spans to drop by name - fetch and XHR spans, custom spans and the add-ons' - a string or a RegExp.
beforeSendSpan - (span) => span | null: edits or drops each custom span before it's queued - see Hooks.
beforeBreadcrumb - (crumb) => crumb | null: edits or drops each breadcrumb as it's recorded - see Hooks.
integrations - The add-ons to run: failedRequests(), clickSpans(), longFrames() and errorData().
breadcrumbs On false, or { console, clicks, navigation, fetch, max } - see Errors and breadcrumbs.
attribution true Which element, script or resource made each vital what it was - see What made a vital slow.
assets On false, or { max, minDurationMs } - see Calls and assets.
debug false Logs what is queued, sent and dropped to the console, and when an hourly limit is reached.

A sample rate that isn't a number counts as 1, with a warning in the console.

The rest of the API is on observe, whichever entry point started it:

Call What it does
observe.setUser({ id }) Reports a user id, up to 128 characters, with everything sent after the call; null clears it.
observe.captureError(error, { tags, handled }) Reports an error you caught. handled is true unless you say otherwise; up to 10 tags, values cut to 128 characters.
observe.addBreadcrumb({ message, level }) Adds a custom entry to the trail the next errors carry. level is "info" by default.
observe.setRoute("/orders/:id") Names the current view by its route template - for a router without an adapter.
observe.span(name, fn, options) Times fn, sync or async, as a custom span of the current view, and returns what it returns.
observe.startSpan(name, options) Starts a custom span and returns it, to end when the work does.
observe.currentTraceId() The current view's trace id, as Observe shows it: a UUID. A call's traceparent carries it as 32 hex digits.
observe.consent(granted) Grants or refuses consent - see Consent.
observe.flush() Sends what's ready now - the views that have ended, the errors and spans held - and resolves once it's sent. Never rejects.
observe.close() Stops the SDK: sends what it holds, as when the page is left, and puts fetch, XHR, history and the console back.

Angular

@nestjs/observe-browser/angular is one provider in the application's config:

// app.config.ts
import { provideObserve } from "@nestjs/observe-browser/angular";

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideObserve({ publicKey: "pk_..." })],
};

provideObserve() takes the options init() takes and starts the SDK as the app initializes. It reports what reaches the app's ErrorHandler as unhandled - your own handler, if you provide one, still runs, whichever order the providers are in - and after every NavigationEnd names the view by its route template: orders/:id under shop is /shop/orders/:id, and the wildcard ** is :splat*. With zone.js, the SDK runs outside Angular's zone, so it starts no change detection and the app becomes stable as it would without it. It needs Angular 19 or later.

To start the SDK yourself, call observe.init() before bootstrapping and provide only its error handler - views are then named without an adapter:

import { ErrorHandler } from "@angular/core";
import { ObserveErrorHandler } from "@nestjs/observe-browser/angular";

// in the application's providers
{ provide: ErrorHandler, useClass: ObserveErrorHandler }

React

@nestjs/observe-browser/react names views by React Router's route templates and reports what React's error handling catches:

// main.tsx
import { observe } from "@nestjs/observe-browser";
import {
  ObserveErrorBoundary,
  observeRootErrorHandlers,
  withObserveRouter,
} from "@nestjs/observe-browser/react";

observe.init({ publicKey: "pk_..." });
const router = withObserveRouter(createBrowserRouter(routes));

createRoot(container, observeRootErrorHandlers()).render(
  <ObserveErrorBoundary fallback={<p>Something went wrong.</p>}>
    <RouterProvider router={router} />
  </ObserveErrorBoundary>
);
  • withObserveRouter(router) names each view by the matched route template of a React Router data router - createBrowserRouter, React Router 6.4 or later - once its navigation has settled, and returns the router it was given.
  • ObserveErrorBoundary reports what it catches as unhandled - the UI under it crashed - and renders fallback: a node, or a function of { error, reset }. It also takes tags for the reported error, and onError.
  • observeRootErrorHandlers() gives React 19's createRoot its error callbacks. Errors no boundary caught, and errors a boundary caught, are reported as unhandled; errors React recovered from, as handled. Each is then logged as React logs it, or handed to the callback you pass in its place. What an ObserveErrorBoundary caught is left to the boundary, which reports it with its own tags.

React Router's framework mode and declarative routes have an entry of their own: React Router.

React Router

@nestjs/observe-browser/react-router names views by React Router's route templates in each of its modes - framework mode, data routers and declarative routes, from React Router 6.4 - and reports what a route's error boundary shows. Start the SDK first, in framework mode before hydrating:

// app/entry.client.tsx
import { observe } from "@nestjs/observe-browser/react-router";
import { observeRootErrorHandlers } from "@nestjs/observe-browser/react";

observe.init({ publicKey: "pk_..." });
hydrateRoot(document, <HydratedRouter />, observeRootErrorHandlers());

In framework mode, or with any data router, render <ObserveRoutes /> once, ahead of the routes, and report from the error boundary:

// app/root.tsx
import {
  ObserveRoutes,
  useObserveRouteError,
} from "@nestjs/observe-browser/react-router";

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ObserveRoutes />
        {children}
        <Scripts />
      </body>
    </html>
  );
}

export function ErrorBoundary() {
  useObserveRouteError();
  const error = useRouteError();
  // ...
}

With declarative routes, use this entry's Routes - or its useRoutes - in place of React Router's:

import { BrowserRouter, Route } from "react-router";
import { Routes } from "@nestjs/observe-browser/react-router";

<BrowserRouter>
  <Routes>
    <Route path="orders/:orderId" element={<Order />} />
  </Routes>
</BrowserRouter>;
  • <ObserveRoutes /> names each view by the matched routes' own paths, as written: /orders/:orderId, an optional param /users/:id? with or without its value, a splat /files/:splat*. In framework mode, render it first in root.tsx's Layout, which wraps the ErrorBoundary too.
  • useObserveRouteError() reports the error a route's ErrorBoundary - or a data router's errorElement - shows, once, as unhandled, after naming the view. A thrown 4xx response - throw data(null, { status: 404 }), or a URL no route matches - isn't reported; a 5xx one is, as an ErrorResponse with its status and status text.
  • Routes and useRoutes are React Router's own, naming the view as they match: a declarative router has no matches for <ObserveRoutes /> to read.

A data router can be wrapped instead, rendering nothing: /react's withObserveRouter gives a route the same name.

TanStack Router

@nestjs/observe-browser/tanstack-router wraps a TanStack Router router - TanStack Start's too - to name views by its route templates, and reports what a route's error boundary catches:

// router.ts
import {
  observe,
  observeOnCatch,
  withObserveRouter,
} from "@nestjs/observe-browser/tanstack-router";

observe.init({ publicKey: "pk_..." });

export const router = withObserveRouter(
  createRouter({
    routeTree,
    defaultOnCatch: observeOnCatch,
    defaultErrorComponent: ErrorPage,
  })
);
  • withObserveRouter(router) names each view by the template of the deepest route it matched - /orders/$orderId is /orders/:orderId, a splat $ is :_splat* - once its matches have loaded, and again as the navigation resolves. It returns the router it was given, and on the server does nothing.
  • observeOnCatch, as defaultOnCatch or a route's onCatch, reports what a route's error boundary caught - a render error, or a loader's - as unhandled. TanStack Router calls it only for routes with an error component, so set defaultErrorComponent, or call useObserveError(error) in your own error component instead.
  • notFound() and redirects aren't errors, and aren't reported.

It needs TanStack Router 1.

Next.js

@nestjs/observe-browser/next starts the SDK before the app hydrates, names views by Next's route templates, and reports what error boundaries receive:

// instrumentation-client.ts
import { initObserve } from "@nestjs/observe-browser/next";

initObserve({ publicKey: process.env.NEXT_PUBLIC_OBSERVE_KEY! });
// app/layout.tsx
import { ObserveRoutes } from "@nestjs/observe-browser/next";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <ObserveRoutes />
        {children}
      </body>
    </html>
  );
}
// app/error.tsx
"use client";

import { useObserveError } from "@nestjs/observe-browser/next";

export default function Error({
  error,
}: {
  error: Error & { digest?: string };
}) {
  useObserveError(error);
  return <p>Something went wrong.</p>;
}
  • initObserve() starts the SDK from instrumentation-client.ts, which Next runs before the app hydrates - early enough to see the page load and its first requests. It needs Next 15.3 or later.
  • <ObserveRoutes /> names each view by its Next route template. In the App Router that comes from the path and the matched params - /orders/8812 with { id: "8812" } is /orders/:id, and a catch-all [...slug] is :slug*. In the Pages Router it's the page's own path, /orders/[id] read as /orders/:id, after each route change. Render it once, in app/layout.tsx or pages/_app.tsx.
  • useObserveError(error) reports the error an error.tsx or global-error.tsx boundary received, once, as unhandled, with a server error's digest as a tag.

Vue

@nestjs/observe-browser/vue is a Vue plugin:

// main.ts
import { createApp } from "vue";
import { observePlugin } from "@nestjs/observe-browser/vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App);
app.use(router);
app.use(observePlugin, { publicKey: "pk_..." });
app.mount("#app");

observePlugin takes the options init() takes and starts the SDK as it's installed.

  • Errors. It reports what reaches app.config.errorHandler as unhandled, tagged with the component's name (vue.component) and where in Vue it was thrown (vue.info) in Vue's words - render function, native event handler - from a production build too. Then it hands the error to the app's own handler, set before the plugin or after it, or logs it as Vue does without one. An errorCaptured hook that returns false stops an error before it gets there.
  • Routes. After every vue-router navigation, the first one included, it names the view by its route template: orders/:id(\\d+) under /shop is /shop/orders/:id, a repeatable or catch-all param is :name* - /:pathMatch(.*)* is /:pathMatch* - and an optional one keeps its ?. A failed navigation renames nothing. It finds the router the app installs with app.use(router), before the plugin or after it; otherwise, pass it as router in the options.
  • Versions. It needs Vue 3.3 or later, and vue-router 4 or 5. During server rendering it does nothing.

On Vue 2 the plugin warns in the console and starts nothing. Vue 2 catches what components throw and only logs it, so init() alone sees none of it: start the SDK and report from Vue's error handler yourself, before new Vue({ router }), so the first navigation is named too:

// main.js
import Vue from "vue";
import { observe } from "@nestjs/observe-browser";
import router from "./router";

observe.init({ publicKey: "pk_..." });

const previous = Vue.config.errorHandler;
Vue.config.errorHandler = (err, vm, info) => {
  const tags = { "vue.info": info };
  if (vm && vm.$options.name) tags["vue.component"] = vm.$options.name;
  observe.captureError(err, { handled: false, tags });
  if (previous) previous(err, vm, info);
  else console.error(err); // Vue logs nothing once a handler is set
};

router.afterEach((to) => {
  const route = to.matched[to.matched.length - 1];
  if (route) observe.setRoute(route.path);
});

There, a view is named by its route's path as written: /orders/:id(\\d+), or * for the catch-all.

Nuxt isn't supported yet. Don't install observePlugin through nuxtApp.vueApp.use(): Nuxt sets an error handler that shows its error page, and drops it once the page has hydrated - unless something has replaced it. The plugin replaces it and calls it after reporting, so every later component error would show Nuxt's error page.

Route names

A view is named by the route template your router matched, written the same way whatever the framework:

In the router Sent as
A param: :id, $id, [id] /orders/:id
An optional param /users/:id?, with or without its value
A splat or a catch-all /files/:splat* in React Router and Angular (**), /files/:_splat* in TanStack Router, and the param's own name in Vue and Next.js: /:pathMatch*, /:slug*
  • A URL no route matches keeps its path, with ids folded as below, so each shape of wrong URL becomes a route of its own. Give the app a catch-all route, and they're all one.
  • Under a base path, a matched route is named without it, and a URL no route matches with it.
  • Naming views yourself, in a setup the adapters don't cover: each adapter exports the function it builds a template with. routeTemplateOf takes the router's state in /angular (a route snapshot), /react (a data router's matches) and /vue (a route location); /next has appRouteTemplate(pathname, params) and pagesRouteTemplate(pathname). Pass the result to observe.setRoute().

Without an adapter, a view is named after its path, with every segment that looks like an id folded to :id: a number, a UUID, a hex hash of 16 or more digits, or a run of 20 or more letters and digits that has both. /orders/8812 is /orders/:id, and /blog/how-we-ship-2026 stays a page of its own. With a hash router (#/orders/8812), the route is read from the hash. To use your router's own templates instead, call observe.setRoute() after each navigation.

Calling an API on another origin

Requests to the page's own origin carry the trace headers from the start. An API on another origin has to let them through its CORS first, and only then go in tracePropagationTargets: the other way round, the browser's preflight fails, and so do the calls.

// main.ts of the Nest API
app.enableCors({
  origin: ["https://app.example.com"],
  allowedHeaders: [
    // ...the headers you allow already
    "traceparent",
    "tracestate",
  ],
});
observe.init({
  publicKey: "pk_...",
  // Replaces the default, so the page's own origin is listed too.
  tracePropagationTargets: [location.origin, "https://api.example.com"],
});

Behind your own proxy

An ad blocker can stop requests to observe-api.nestjs.com. To send through your own origin instead, set endpoint to it, or to a path on it such as https://app.example.com/observe, and forward what the SDK posts there, <endpoint>/browser/v1/<publicKey>, to https://observe-api.nestjs.com/browser/v1/<publicKey> with its Origin header as it came: the collector checks it. The SDK leaves alone only its own requests, those under <endpoint>/browser/v1/, so the page's other calls to the same origin keep their spans, breadcrumbs and trace headers.

The collector then sees your proxy's address, not your visitors'. Unless the proxy vouches for them, every page view is placed in the proxy's country, and the cap of 60 beacons a minute per address applies to all of the proxy's traffic at once. To vouch for them, the proxy sends two headers with each beacon:

  • x-observe-proxy-secret: the key's proxy secret, on its card on the API keys page for members who can change the key. It changes when the key is rotated. It's your server's, like the upload token: never put it in the page.
  • x-observe-client-ip: the visitor's address. Without it, the collector takes the address the proxy appended to X-Forwarded-For, as most proxies do, and never one further left, which the visitor could have written.

With the secret, each visitor is capped and placed on their own; without it, or with a wrong one, both headers are ignored. The proxy must set x-observe-client-ip itself, replacing any the visitor's request carried: one that passes the visitor's headers through would let anyone claim any address. A rewrite that can't add request headers - Next.js's and Vercel's rewrites - can't vouch: forward through a route handler or middleware that sets both headers instead.

location /observe/ {
  proxy_pass https://observe-api.nestjs.com/;
  proxy_ssl_server_name on;
  proxy_set_header Host observe-api.nestjs.com;
  proxy_set_header x-observe-proxy-secret "ps_...";
  proxy_set_header x-observe-client-ip $remote_addr;
}

What it records

Page views

A page view starts with each document load, and in a single-page app with each history navigation that changes the path - pushState, replaceState, back and forward - and with a page restored from the back/forward cache. A change to the query string alone starts none. Each view records:

  • Where it was: its route, its URL - path, query and hash, with sensitive values masked - and how it was reached: load, reload, push, replace or back - the back and forward buttons, a page restored from the back/forward cache, or a return to the tab.
  • Web Vitals: LCP, FCP and TTFB for the document load, or a restored page; INP and CLS for the view they happened in, so a slow click on the second route isn't blamed on the first.
  • Load time: the load event, for a document load. For a later view, the end of the last request it started, measured once 100 ms pass with none in flight; a view that makes no request in its first second has no load time, and one still busy after 10 seconds is given up on.
  • API wait: the time at least one of its fetch or XHR calls was in flight.
  • The browser: its name and major version, the OS, and the device class - desktop, mobile or tablet.

A view is sent once it ends: at the next navigation, or when the page is hidden or closed.

If the visitor comes back to a tab whose view was sent, and the page then does something - a request, a click, an error, a span - a new view of the same route starts, reached by back, from when the page was shown again. A long stay on one route, across several tab switches, is then several views. A return with nothing after it starts none, and neither does what a page does while it's hidden - a poll, an analytics call. A page that refetches when its tab regains focus, as TanStack Query and SWR do by default, starts one on every return. Each is a page view, and billed as one. With viewOnReturn: false, a view that was sent records nothing more until the next route change; its errors and custom spans still go.

Calls and assets

Every fetch and XHR is a span of the view it started in: its method, host, path with ids folded to :id, status and timing, at most 50 per view. Its query string, headers and body are never sent. The SDK's own requests, and URLs in ignoreUrls, are left out. Spans your own code times are custom spans, sent and billed on their own.

A call that a click or a key press started - at most a second after it, in the same view - also names that element, the way click breadcrumbs name it: no text and no values. A link's click is not credited with what the next view loads. With click breadcrumbs off (clicks: false, or breadcrumbs: false), nothing is named.

Asset timing adds the view's resources, from Resource Timing - scripts, styles, images, fonts and media: every one that blocked rendering, then the slowest of the rest that took at least 50 ms (minDurationMs), 20 in all (max). A document load takes the resources that started before its load event ended; a later view, those that started while it ran. Requests are spans already, so they aren't repeated here.

Custom spans

What your own code does - rendering a page, hydrating a store, applying a coupon - you time with custom spans. Each is a span of the view it started in, named as you name it, with an op, tags and a parent if you give them:

import { observe } from "@nestjs/observe-browser";

// Wrapping work: a throw or a rejection marks the span failed, and is passed on.
const summary = await observe.span(
  "render checkout",
  async (span) => {
    span.setTag("cart.size", cart.items.length);
    return renderSummary(cart);
  },
  { op: "ui.render", tags: { express: cart.express } }
);

// Work that ends somewhere else: start it, nest under it, end it.
const hydrate = observe.startSpan("hydrate cart", { op: "cart" });
const restore = observe.startSpan("restore cart", { parent: hydrate });
// ...
restore.end();
hydrate.addTags({ source: "storage" }).end();
  • observe.span(name, fn, options) passes fn its span and times it, sync or async. A throw or a rejected promise marks the span failed with the error's class, and is rethrown.
  • observe.startSpan(name, options) returns a span to end yourself: setTag(key, value) and addTags(tags) add tags, fail(error) marks it failed - with the error's class, when you pass one - and end() ends it. A span never ended is never sent, and ending one twice does nothing.
  • Options: op groups spans of a kind (ui.render, cart), up to 64 characters; tags, up to 10, keys up to 64 characters and values a string up to 128, a number or a boolean; parent, a span it nests under. Nesting is explicit: a browser can't follow async work, so a span without parent sits under the page.
  • Names are your own and never folded: up to 200 characters. Each browser application keeps 100 a day (UTC); past that, new ones are (other), as routes are.

A span keeps the view it started in, so one that ends after its view did - or after the view was sent - still reaches it. One that starts an hour or more into its view, or runs an hour or more, isn't sent. The SDK keeps at most 100 per view, and 1,000 a page in any one hour. Each counts as an event - see Billing and limits - and ignoreSpans and beforeSendSpan can drop them before they cost one.

Spans lists them beside the backend's custom spans, and shows either source alone: each name's count, failure rate, p75 and p95 over the window - with its operation (the span's op), and a filter by it, when the source is Browser - and on a span's own page its count and failures over time, its breakdown by route, release, device or any of its tags - over its newest 5,000 - and its newest samples, each opening the trace it ran in, filtered by key:value tags. In that trace, a custom span nests under its parent, with its op and tags on its row and a failed one in red.

What made a vital slow

With attribution on, as it is by default, each vital comes with what caused it, from web-vitals' attribution build:

  • INP: the element interacted with, whether by pointer or keyboard, the input delay, processing and presentation times, and - in Chromium - the script that ran longest during the interaction.
  • LCP: the element, the image or video it loaded, and its four phases: time to first byte, load delay, load time and render delay.
  • CLS: the element of the largest shift.

Elements are named the way click breadcrumbs name them, as in form#checkout>button.btn.pay. While attribution is on, the SDK keeps a passive, empty pointerdown listener on the document: without one anywhere on the page, Chrome doesn't say which element a click's INP was on.

Errors and breadcrumbs

Errors that reach window.onerror or unhandledrejection, or a framework adapter's handler, are reported as unhandled; observe.captureError() reports handled ones. An error carries its class, message, stack and up to 30 frames, the trace id and route of the view it happened in, and your tags. A cross-origin script's bare "Script error." carries nothing to act on and is dropped, and an error that reaches several handlers is reported once.

Each error takes the breadcrumbs before it - up to 30 (max), oldest first, each with how long before the error it happened:

Kind What it records
click The element clicked: its tag, #id, up to two classes, and data-test or name, under up to three ancestors
nav A navigation, as the route templates either side of it
fetch A fetch or XHR that completed: method, path with sensitive values masked, status and duration
console A console call: warn and error by default - console takes any of log, info, warn and error, or false
custom observe.addBreadcrumb({ message, level })

clicks: false, navigation: false and fetch: false switch off one kind; breadcrumbs: false, all of them.

Errors are grouped by their class, their message with what varies replaced - numbers, ids, quoted values, URLs - and their top five in-app frames: the source file and function once a source map resolved them, else the bundle's file name without its content hash. A resolved group that happens again is open again; an ignored one stays ignored.

What caused it. An error's cause chain goes with it, nearest cause first, three deep: each cause's class, message - up to 512 characters - stack and up to 10 frames, resolved by the source maps as the error's own are. An error's page shows them under its stack, each as Caused by over its own frames, from the newest of the group's last 1,000 occurrences that had a cause - as its breadcrumbs and extra data each come from the newest that kept them.

Where it happened. An error carries the page's URL, masked as a view's is, and the page's referrer without its query: a path when the visitor came from your own origin, origin and path when from another, and nothing when there was none. Both show on the error's page, with its occurrences.

What it carried. An error's tags - from captureError(), or a framework adapter's - show on its page: the newest occurrence's, and each key's most common values across its newest 1,000 occurrences. The error object's own fields - an HTTPError's status, a ChunkLoadError's request - go only with the errorData() add-on, since they can hold anything; the page shows the newest occurrence's that had any.

Making it an issue. Create issue - on an error's page, or in its row's menu on the Errors page - opens an issue from the group, with its message, when it was first seen and in which release, its top browsers and its resolved frames; once it's linked, it reads View issue and opens it. Resolving, ignoring and making an issue take write access to the project, as for backend errors: a read-only member sees the group's status, and can open its issue once it has one.

The issue gets Did a release fix this?, judged on the browser release's own page views on the pages the error was thrown on, against the day before the release. A release reaches visitors only as they load it, so it's judged from its first page view to now, for up to 7 days. The releases to pick from are the browser application's own; one that shipped in the last hour is listed once its first hour of page views is counted. The answer rests on the page views and errors the SDK sent: a release that changed its sampling - sampleRate, viewSampleRate or errorSampleRate - changes what it compares.

The new-error email. When a browser application throws an unhandled error the project hasn't seen - no error of the same class and message from its browser applications in the last 30 days - the project's members get it in the new-error email, in a section of its own with up to five listed. An error your code caught and reported, failedRequests()' included, is never news there. A New JS error groups alert rule counts such groups per browser application, against the same class and message in that application.

Add-ons

@nestjs/observe-browser/addons holds what the core leaves out, each opt-in and outside its size budget, added through integrations:

import { observe } from "@nestjs/observe-browser";
import {
  clickSpans,
  errorData,
  failedRequests,
  longFrames,
} from "@nestjs/observe-browser/addons";

observe.init({
  publicKey: "pk_...",
  integrations: [failedRequests(), clickSpans(), longFrames(), errorData()],
});
  • failedRequests({ statuses, network, targets }) reports a failed fetch or XHR as a handled error: class HTTPError, message GET /api/orders/:id → 500, its path folded, with status, method and host as tags - never its headers or body. statuses defaults to [[500, 599]]; network: true adds calls that got no answer at all (→ no response); targets keeps it to matching URLs. Each counts as an error.
  • clickSpans() puts a span on the view for a click or key press that started requests, running to the end of the last one, or that took 50 ms or more to handle: named by its element, as click breadcrumbs name it, up to 20 a view. In a trace it reads click · button#pay. It records nothing while click breadcrumbs are off - clicks: false, or breadcrumbs: false.
  • longFrames({ minDurationMs }) puts a span on the view for each animation frame of 100 ms or more (minDurationMs), named by its longest script, up to 10 a view - Chromium only. In a trace it reads long frame · checkout.js onSubmit.
  • errorData() sends up to 10 of an error's own fields with it - strings up to 128 characters, numbers and booleans, never its name, message, stack or cause - shown on the error's page as its extra data.

The add-ons' spans ride in their view, like its calls, and are free; a view holds up to 50 calls and 80 spans in all.

In the dashboard

Frontend

Frontend data shows up across a project's dashboard, beside its backend's:

  • Frontend shows the browser applications' page views; each vital at p75, with its rating; the Performance Score; JavaScript errors per 1,000 page views; crash-free sessions; how much of the load time went on waiting for the API; the routes most worth fixing - score lost times traffic; the elements and scripts behind slow interactions, largest paints and layout shifts; the calls and resources that cost page views the most time; and the countries views came from. Before the project has a browser application, the page shows what the SDK records and how to add one.
  • Errors lists JavaScript errors beside the backend's, and shows either source alone. A frontend error's page has its frames - source positions once a map resolved them, with the minified position beside each, and the source lines around them where the map carried them - its causes, its raw stack, its tags and extra data, its breadcrumbs - the causes, breadcrumbs and extra data each from the newest of its last 1,000 occurrences that kept them - breakdowns by browser, OS, device, release, route and tag, the users it reached, and its occurrences with their URL and referrer, each opening its trace. Create issue makes it an issue, on its page or from its row's menu.
  • Spans lists your frontend's custom spans beside the backend's, counts both sources' spans over the window in one chart, and shows either source alone. Each opens a page of its own.
  • A trace a page started leads with the page view, with each request to your Nest API under the call that made it - see Traces & spans → The browser half.
  • Releases lists a browser application's releases with the services', each judged against the last release before it with 500 page views or more: worse when its Performance Score fell 5 points or more, its JavaScript errors per 1,000 views rose by half and by at least 1, a p75 vital dropped a rating band, or its crash-free sessions fell by a point or more - when both releases had 500 page loads or more; better the other way round; too early under 500 page views of its own. A release says what moved its verdict, and shows its crash-free sessions and users.
  • Map draws a browser application calling the services its pages called, from a sample of recent page views.
  • What a slow paint waited on. A route's drawer follows each largest paint that waited on an API call - its image's URL came from the reply, or it rendered once the call answered - through the trace, into the Nest operation that answered it: the call's p75 as the page saw it, the operation's on the server, and where its time went, method by method and query by query, averaged over the slower half of its requests.
  • What clicks cost the backend. The Frontend page ranks the elements whose clicks and key presses start API calls by the server time those calls take, over the newest 2,000 page views: the calls each click starts, the Nest operation that answers each, and how long the page waits for them. An element is listed once its calls have taken a tenth of a second of server time in that sample. Clicks that start no call aren't recorded.
  • Called from your frontend. A Nest endpoint's page lists the frontend's pages that call it, for whoever is about to change it: of its newest 2,000 requests in the last 6 hours - 24 for a quiet one - those that ran under a page view's trace, and per route their share, how many of the route's views call it and how often, and how - as the page loads, and after which other call, or on a click, and which elements.

The last three read the trace a page view shares with the requests it made, so they need what Joining the trace needs. A request is matched to the page's call that made it by method, path and when it started.

  • The project's Dashboard charts page views and load time beside the backend's charts.

Where a page load goes, what pages wait on, top errors and where users are

A JavaScript error's page

The Performance Score runs from 0 to 100. Each page view gets one at ingest, from its vitals: each scored on a log-normal curve that gives 90 at its "good" threshold and 50 at its "poor" one, then weighted - LCP 30%, INP 30%, CLS 15%, FCP 15%, TTFB 10%. A vital the view didn't measure drops out and the rest are reweighted, so a view left before any interaction still gets a fair score. A window's score is the average of its views'. Ratings use the same thresholds:

Vital Good Needs improvement Poor
LCP ≤ 2,500 ms ≤ 4,000 ms > 4,000 ms
INP ≤ 200 ms ≤ 500 ms > 500 ms
CLS ≤ 0.1 ≤ 0.25 > 0.25
FCP ≤ 1,800 ms ≤ 3,000 ms > 3,000 ms
TTFB ≤ 800 ms ≤ 1,800 ms > 1,800 ms

Pages, worst first by what fixing them is worth

Crash-free sessions

A session, here, is a page load: a document load or a reload, with the client-side navigations that follow it - a reload starts a new one, a page restored from the back/forward cache doesn't. A document the back and forward buttons load again, rather than restore from that cache, is neither a session nor a crash. A load crashed when an unhandled error broke it, once however many followed. Crash-free sessions is the share of page loads that didn't crash, and crash-free users the share of the users you identify with observe.setUser() who had no crashed load, for a window or a release; neither is read under 50 page loads.

A crash is counted on its own, before error sampling: after ignoreErrors and allowUrls, which decide what is an error at all, and before errorSampleRate and beforeSend, so neither sampling errors nor the collector's caps on them hide one. It carries only its load's id and time, and is free. A load and its crash are sampled together, by sampleRate and viewSampleRate.

Joining the trace

A page view's id is its trace id: a UUIDv7, minted on the browser's clock corrected by the time the collector's replies carry, so it holds the instant the view began. Requests to a propagation target go out with two headers:

traceparent: 00-<the view's trace id, as 32 hex digits>-<the call's span id>-01
tracestate: observe=b1

observe=b1 goes first in tracestate, ahead of any other vendors' members already there, 32 members at most. The flags are 01 in a recorded view. They're 00 when sampling left out the session or the view, and for a call made after its view was sent - a poll while the tab is hidden, say - since no stored view will hold it.

On the Nest side, from @nestjs/observe 0.3.30, the default traceIdGenerator reports a request under that trace when its tracestate carries the observe member and its trace id is a UUIDv7 - ahead of x-request-id, so an id a mesh or a router stamped on the request can't split the page from the API. Nothing else sends that member, so an app that never runs the browser SDK names its requests exactly as before. That's all it takes:

  • Same origin - the frontend and the API served from one origin, by one server or through a proxy: nothing to configure.
  • Another origin - the API's CORS has to let traceparent and tracestate through; see Calling an API on another origin.
  • An agent before 0.3.30 - turn on openTelemetry in ObserveModule.forRoot(). It reads any W3C traceparent, the browser's included, and adds one to the service's own outbound calls.
  • A traceIdGenerator of your own replaces the default, and with it this adoption.

Beside OpenTelemetry in the browser

If your frontend already runs OpenTelemetry's web SDK, the browser SDK works beside it:

  • A request that already carries a traceparent - OpenTelemetry's fetch instrumentation writes one - keeps it. Nothing is overwritten, and the call's span is recorded under that trace.
  • A view that starts inside an active OpenTelemetry span takes that span's trace id, unless openTelemetry is "off".
  • With an OpenTelemetry propagator registered, an XHR's traceparent is left to OpenTelemetry's XHR instrumentation.

OpenTelemetry's trace ids are random rather than UUIDv7, so its requests go out without the observe member, and the Nest app joins those traces through openTelemetry: true, as it joins any W3C trace.

Privacy

The SDK records how a page performs and fails, not what is on it. Never collected or kept:

  • What users type and see. Elements are named by tag, id, classes and data-test or name attributes - never by their text, nor by an input's value.
  • What requests carry. A call is sent as its method, host, path, status and timing - never its query string, headers or body.
  • What objects you log hold. A console breadcrumb shows strings as they print, but an object as {…} and an array as […].
  • The user agent string. The SDK reads the browser's name and major version, the OS and the device class from it, and only those are recorded.
  • IP addresses. The collector stores the visitor's country, an ISO code it looks up from the address, and never the address. The per-address cap counts a keyed hash of it, which hashing every address can't reverse, kept for two minutes.

Storage. The SDK sets no cookies and uses no localStorage: its session lives in the tab's sessionStorage, under observe.session, and only once consent is granted.

Masking. In the page URL, fetch breadcrumbs, error messages and stacks, the values of parameters whose names mark a credential - password, secret, token, jwt, apikey, sessionid, authorization and the like, and code, state, sig and key - become [REDACTED]: in the query, in the fragment (#access_token=) and after a path's ; (;jsessionid=). The names stay, since knowing a page carried a token helps where knowing which one doesn't. A resource's URL - an LCP image, an asset, a script - is sent without its query at all: a path on your own origin, origin and path on another.

Redaction on our side. Whatever the SDK's version or settings, the collector replaces what reads as personal data or a secret before anything is stored: email addresses become [EMAIL], JSON Web Tokens [JWT], Bearer and Basic credentials Bearer [REDACTED], the values of keys named like secrets - password=, "token":, api_key:, X-Amz-Signature= - [REDACTED], and card numbers [CARD]. It covers error messages and stacks, breadcrumbs, routes and URLs, call names and element names, so an error's group and its sample hold the redacted text too. Tags and the user id are stored as you send them: they're yours to choose.

beforeSend sees each view and each error, breadcrumbs included, just before it's queued, and returns it, changed or not, or null to drop it. A beforeSend that throws drops the event, since it may be the one keeping something private out:

observe.init({
  publicKey: "pk_...",
  beforeSend: (event) => {
    if (event.type === "view") {
      event.view.url = event.view.url.split("?")[0]; // no query strings at all
    } else if (event.error.message.includes("ResizeObserver")) {
      return null;
    }
    return event;
  },
});

A view comes as { type: "view", view } - its route, url, navigation, vitals, requests, assets and the rest - and an error as { type: "error", error } - its name, message, stack, frames, handled, tags, breadcrumbs and causes. The shapes are exported as types: ObserveViewData and ObserveErrorData, and for the hooks below ObserveSpanData and ObserveBreadcrumbData.

Users. Nothing ties telemetry to a person unless you call observe.setUser({ id }). Prefer an opaque internal id over anything that identifies someone.

Consent

With consent: "pending", the SDK records into memory and sends and stores nothing - not even its session - until observe.consent(true). While it waits, it holds at most 100 views and 100 errors, letting the oldest go. observe.consent(false) drops what it held, removes the stored session and records nothing more, until a later observe.consent(true).

observe.init({ publicKey: "pk_...", consent: "pending" });

// once the visitor has chosen
observe.consent(visitorAgreed);

Until consent is granted, requests to your propagation targets carry no trace headers either: nothing of the page leaves it.

Sampling

sampleRate is the share of sessions recorded. It's decided once per session - the tab's, kept in its sessionStorage - and an unsampled session sends nothing, views or errors. errorSampleRate thins the errors of a recorded session.

viewSampleRate thins the page views of a recorded session, decided once per view: a number, or a function of the view that returns one, for keeping fewer of a busy route than of a rare one:

observe.init({
  publicKey: "pk_...",
  viewSampleRate: ({ route, navigation }) =>
    route.startsWith("/products/") && navigation !== "load" ? 0.2 : 1,
});

The function gets the view's route, url and navigation - load, push, replace, back or reload. Its route is the path with ids folded, as without an adapter, not your router's template: a view is decided as it starts, before an adapter names it. A view it leaves out sends nothing, and neither do its custom spans or a crash of its load; its errors still go, and its calls carry the trace headers with the 00 flags.

The collector may lower a session's rate, never raise it: a reply can carry a lower sampleRate, which the session keeps, or ask for a pause. A session that a lower rate leaves out drops what it held.

Errors only

To report a frontend's JavaScript errors and none of its page views, set viewSampleRate to 0:

observe.init({
  publicKey: "pk_...",
  viewSampleRate: 0,
});

Errors are still sent, each with its breadcrumbs, and billed as one event each; the page's calls still carry the trace headers, with the 00 flags. What it leaves out goes with the page views:

  • Web Vitals, the performance score and what made a vital slow, and the calls and assets a page waited on.
  • Custom spans, which are sent with the view they started in.
  • Crash entries, so there are no crash-free sessions.
  • The page's half of a trace: an error has no page view to open, and a backend request no page above it.
  • Anything counted per page view: errors per 1,000 page views, and alert rules on page views or on that rate.

Sampling from the dashboard

Each browser application also has Sampling, in the menu of its row on the Applications page. It holds one setting, Page views: All, which is where it starts, A share of sessions, or Off. Whoever may change the key's allowed origins may change it, and it takes effect within a minute, with no deploy.

Sampling

It acts in the collector, not in the page. Pages keep sending what observe.init tells them to, and the page views the setting switches off are dropped before they're stored, counted against a rate cap or the browser budget, or billed. It only ever keeps less than the page sent: it never raises a sample rate.

  • A share of sessions keeps whole sessions, from 1% to 99% of them: a kept visit has every one of its page views, and one left out has none. Sessions are picked by their id, so raising the share keeps the ones already kept.
  • Off keeps no page views, so that application has no Web Vitals, performance score or crash-free sessions.
  • JavaScript errors and custom spans are always kept, whatever the setting. That's the difference from viewSampleRate: 0, which stops custom spans too - and saves your visitors the bytes, which the dashboard's setting doesn't.
  • A crash entry goes with its session's page views, since crash-free sessions is counted on page loads.
  • Counts follow what's kept. With a share, page views are the kept sessions', not scaled up.
  • Errors per 1,000 page views is estimated under a share. Every error is kept, so the Errors chart's rate and an error's own divide by the page views there would have been: each application's kept views over its current share. It's an estimate: a window in which the share changed is off by as much as it changed, and what sampleRate or viewSampleRate left out in the browser isn't counted. The overview's rate, a release's and an alert rule on that rate count a page view's own errors, so they need no estimate. To thin sessions with their errors, use sampleRate.

When the dashboard suggests it. The Frontend page points at an application's Sampling when the account's browser data has used 80% of the month's browser budget - the mark past which the collector starts asking pages to send less - or a day's share of it, which pauses pages until 00:00 UTC. It also says so earlier, when the page's window is a day or longer and its page views are on pace to get there: its page views a day, over thirty days, at five events each. It's shown once per application, to members who can change the setting, for the application the page is narrowed to or the project's only one, and not once that application is sampled.

The email. The first time an account's browser data meets its budget - a day's share is used, or the month passes 80% - its billing owner and the admins of its projects get one email, with the figures and a link that opens the application's Sampling. It's sent once per account, not every month: if what your frontend keeps suits you, there's nothing to do, and we don't write about it again.

Hooks

Four options drop or change what's recorded before it's sent, beside beforeSend for views and errors (see Privacy):

  • ignoreSpans drops fetch and XHR spans, custom spans and the add-ons' spans whose name matches one of its strings or RegExps.
  • beforeSendSpan(span) sees each custom span as it will be sent - its name, op, tags, route, startOffset and duration, and failed and errorName when it failed - and returns it, changed or not, or null to drop it.
  • beforeBreadcrumb(crumb) sees each breadcrumb as it's recorded - its type (click, nav, fetch, console or custom), its message, and a call's status and duration or a line's level - and returns it or null.
  • allowUrls keeps only the errors whose top frame is in a script from a matching URL, the opposite of ignoreUrls: your own bundles, when the page also runs extensions' and third parties'. An error with no frames to judge it by - failedRequests()' HTTPError, a promise rejected with something other than an Error - is kept.

As with beforeSend, a hook that throws drops what it was handed.

Billing and limits

A page view counts as 5 Observability Events, a JavaScript error as 1, like any error - failedRequests()' included - and a custom span as 1. The fetch and XHR spans inside a view are free, as are the add-ons' spans, and a crash costs nothing. A return to a tab that starts a view - see Page views - is a page view like any other; viewOnReturn: false turns those off.

Browser data has its own share of your plan - up to half of its included events in a calendar month, shared by all of the account's projects, paced by the day on Free and Personal, and with a daily ceiling on Pro and Scale - and it's the first thing dropped while your plan holds telemetry back. One case keeps part of it: while a Pro account's traces are being trimmed, its JavaScript errors are still kept, and its page views and custom spans are dropped. See Billing & usage → Browser data.

How long it's kept. The page views, error occurrences, custom spans and crashed loads themselves - what a list of samples shows and a trace opens - are kept for your plan's retention, up to 14 days. The charts and figures built from them are kept for your plan's retention, up to 30 days. So a 30-day window still charts thirty days, and the samples under it are the last fourteen days'.

To send or keep less, see Sampling: the SDK's sample rates, and each browser application's own Sampling in the dashboard.

Each browser application's key also has a rate cap per minute, counted in events as they're billed, and each visitor's address may send it 60 beacons a minute. Past either, pages are paused for the rest of the minute:

Plan Events a minute per key
Free 500
Personal 1,000
Pro 5,000
Scale 20,000
Enterprise 50,000

What one page and one beacon can carry:

Limit Value
A beacon 64 KiB, with up to 20 views, 20 errors and 50 custom spans
Spans per page view 50 calls, and 80 with the add-ons' spans
Custom spans 100 per view, and 1,000 a page in any one hour; 10 tags each
Assets per page view 20
Breadcrumbs per error 30
Frames per error 30
Tags per error 10, values up to 128 characters
Error message and stack 1,024 and 16,384 characters
Errors a page records 100 an hour; per view, 5 of the same class and message, 100 different
Held while consent is pending, or paused 100 views and 100 errors
Occurrences of one error stored 30 a minute per browser application; the rest are dropped, not billed
Routes 100 a day (UTC) per application; past that, new ones are (other)
Custom span names 100 a day (UTC) per application; past that, new ones are (other)

Source maps

Production bundles are minified, so an error's frames read index-3f9c2a.js:1:18234 until a source map resolves them. A build plugin uploads the build's maps once it's done:

// vite.config.ts
import { observeSourceMaps } from "@nestjs/observe-browser/vite";

export default defineConfig({
  build: { sourcemap: true },
  plugins: [
    observeSourceMaps({
      release: process.env.GITHUB_SHA!, // the release the page passes to init()
      deleteAfter: true,
    }),
  ],
});

@nestjs/observe-browser/webpack exports the same observeSourceMaps() for webpack. In Next.js, add it to the client build only:

// next.config.js
const { observeSourceMaps } = require("@nestjs/observe-browser/webpack");

module.exports = {
  productionBrowserSourceMaps: true,
  webpack(config, { isServer, dev }) {
    if (!isServer && !dev) {
      config.plugins.push(
        // deleteAfter: the maps aren't deployed with the build
        observeSourceMaps({ release: process.env.RELEASE, deleteAfter: true })
      );
    }
    return config;
  },
};

From Next.js 16, next build uses Turbopack unless given --webpack, and Turbopack runs no webpack plugins: after a Turbopack build, use the CLI.

The plugins take release, uploadToken - OBSERVE_UPLOAD_TOKEN by default - endpoint, urlPrefix, deleteAfter and debugIds, as the CLI's flags below, and failOnError: a failed upload fails the build, unless it's false, and then it's only logged. Without an upload token, they upload nothing, warn, and let the build go on. Without a plugin, upload with the CLI that ships with the SDK, in CI, after the production build:

OBSERVE_UPLOAD_TOKEN=${{ secrets.OBSERVE_UPLOAD_TOKEN }} \
  npx @nestjs/observe-browser sourcemaps upload ./dist --release $GITHUB_SHA
  • --release is the release the page passes to observe.init(): an error's frames are resolved only by the maps of its own release, so a page without one gets none resolved. Up to 64 characters; a git SHA works.
  • The directory is searched for .map files, subdirectories included. A frame's script is resolved by the map named after it: index-3f9c2a.js by index-3f9c2a.js.map.
  • --url-prefix ~/assets says where the directory is served from, when the files under it load from https://app.example.com/assets/.
  • --delete-after deletes the .map files once every one has uploaded, so deploying the directory doesn't publish them.
  • OBSERVE_UPLOAD_TOKEN is the browser application's upload token, and OBSERVE_ENDPOINT the API's address, when it isn't the hosted one.

One upload takes up to 1,000 files, 15 MB each and 500 MB in all - 500 files before @nestjs/observe-browser 0.1.1 - and the CLI checks before it sends anything; a bigger file is refused with the cap named. It needs Node 20.19 or later.

Frames are resolved as errors arrive, the top 10 of each stack and the top 5 of each cause's, so upload before the release takes traffic: an error that arrived before its maps keeps its minified frames - and, since groups are built on resolved frames, sits in a group of its own.

Debug IDs. The plugins stamp each script that has a map with an id - unless debugIds is false - and npx @nestjs/observe-browser sourcemaps inject <dir> does the same to a build's output: a UUID derived from the file's content, the same for the same build. It's appended after the code, above the //# sourceMappingURL= line, with a //# debugId= comment, so no mapped position moves, and written into the map as debugId; a file already stamped is left as it is. At capture, the SDK tells each frame's script by its id, and the collector finds the map by it before falling back to the release and the file's name - so a renamed or re-hosted bundle still resolves. An error thrown while a bundle first runs, before its stamp has, falls back the same way.

The plugins stamp a script as the build makes it, before it's written - on webpack 5 right after its source map is made, so a [contenthash] counts the id - so what another plugin hashes once the scripts are final, an integrity attribute or a service worker's precache list, is the file that ships. webpack 4 has no stage for that and stamps the scripts once they're written: there, pass debugIds: false if another plugin hashes them, and run inject before that step. inject too goes before anything hashes the scripts, and the files it stamped are the ones to deploy.

Source lines. A frame a map resolved shows the source around it on the error's page, up to 5 lines either side, read from the sources the map embeds.

How long maps are kept. A release keeps its maps while it sends page views. Once it has sent none for 30 days, and none of its maps was uploaded in the last 90, they're deleted: unused from then on, and gone from storage within three days. Uploading a release's maps again keeps them another 90 days.

Maps are stored encrypted and never served to a browser; only the collector reads them. It reads their mappings and names, and the sources a map embeds only for the lines it shows beside a frame. A build that leaves those out - webpack's nosources-source-map, esbuild's --sources-content=false - uploads smaller files that hold none of your code, and its frames show their positions without lines.

When the key is refused

The collector answers a key that's unknown or revoked, or belongs to an archived application, with a 401, and an Origin that's missing or not among the key's allowed origins with a 403. The page can read both, and neither will start working while it stays open, so the SDK stops for that page: it drops what it holds, and records, sends and propagates nothing more - later requests get no trace headers either. It doesn't remember this across page loads: each load finds out again, with one refused request.

The other replies the SDK acts on:

  • A 429 - a rate cap, the browser budget, or telemetry your plan is holding back. The reply says how long to pause, in pauseSeconds and Retry-After, and may lower the sample rate. What the refused beacon carried is dropped; what's recorded meanwhile waits, up to 100 views and 100 errors.
  • No answer, or a 5xx - it backs off: 10 s, then 20 s, and so on, up to 5 minutes while it keeps failing. A send with no answer after 15 seconds is given up on.

A view or a custom span is sent again only when it can't have been stored - a 5xx, or a browser that is offline - since every copy the collector gets is stored and billed; one that may have arrived isn't repeated. Views and errors are each tried 3 times at most. When the page is hidden or left, what it holds goes at once, with sendBeacon, without waiting out a back-off.

Performance

Measured in November 2026 on @nestjs/observe-browser 0.1.0, in Google Chrome 158 on a Mac, against the same page doing the same work without the SDK, as medians. 4x is Chrome's CPU throttling, standing in for a mid-range phone:

Added by the SDK 1x 4x
Its script at page load: parse, run and init() 0.66 ms 2.81 ms
A fetch, with its span and traceparent 10.6 µs 46.6 µs
A captured error 24 µs 80 µs
Leaving a typical page (3 views, 1 error) 0.3 ms 1.2 ms

In a single-page app at 4x - each view with three fetches, an XHR, two clicks and a console line, and an error every few views - it added about 2.5 ms per view (1.5 to 3.2 ms across rounds). In a 2,000-view soak, live JavaScript objects grew by under 5 bytes a view in every state measured - sending, collector down, paused, refused, consent pending and not sampled - with no detached DOM nodes. As an app bundles it, the SDK is about 18 KB minified and gzipped with web-vitals, and its core about 12.4 KB without; the add-ons and the build plugins are in neither. Timing and memory weren't measured in Firefox or WebKit.

Troubleshooting

Nothing arrives

  • The first view arrives when it ends. A page view is sent at the next navigation, or when the page is hidden or closed; errors go every 5 seconds. Switch tabs or navigate, then look.
  • The origin. Each port is an origin of its own: http://localhost:4200 and http://localhost:3000 are two entries. So is www: if https://example.com redirects to https://www.example.com, the pages are served from the second, and that is the one to allow. A refused origin shows in the browser's network panel as a 403 from the collector. A page opened from a file, or in a sandboxed iframe, sends Origin: null, which is never allowed.
  • The key. Rotating revokes the old key, and an archived application's key is refused.
  • An ad blocker can stop requests to observe-api.nestjs.com: send them through your own origin, as Behind your own proxy describes, with the proxy secret, or every visitor shares the proxy's cap of 60 beacons a minute.
  • Sampling. With sampleRate under 1, a session may be one left out.
  • debug: true logs what is queued, sent and dropped to the console, with each reply's status.

Traces don't join

  • The headers. In the browser's network panel, the call to your API should carry traceparent and tracestate: observe=b1. Only same-origin calls do by default: an API on another origin has to be in tracePropagationTargets.
  • CORS. Without traceparent and tracestate in a cross-origin API's allowedHeaders, the browser refuses the call itself.
  • The agent. The Nest app needs @nestjs/observe 0.3.30 or later, or openTelemetry: true in ObserveModule.forRoot() on an older one - either way with the default traceIdGenerator.
  • OpenTelemetry in the browser. A view in an OpenTelemetry trace has a random id, which the Nest app joins only with openTelemetry: true.

Console lines point at the SDK

With console breadcrumbs on - the default, for warn and error - the browser's devtools show those lines as logged from the SDK's file. Add @nestjs/observe-browser to the devtools' ignore list, or set breadcrumbs: { console: false }.

webpack 4 can't build it

The SDK is ES2020, and its entry points are reached through exports. webpack 4 - Vue CLI 4, Create React App 4 - reads neither. Run Babel over the SDK and web-vitals (ES2022) for a target older than both, and alias each entry point you import to its file:

// webpack.config.js, webpack 4
const path = require("path");

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.m?js$/,
        include: /node_modules[\\/](@nestjs[\\/]observe-browser|web-vitals)[\\/]/,
        use: {
          loader: "babel-loader",
          options: { presets: [["@babel/preset-env", { targets: "chrome 71" }]] },
        },
      },
    ],
  },
  resolve: {
    alias: {
      "@nestjs/observe-browser/vue$": path.resolve(
        __dirname,
        "node_modules/@nestjs/observe-browser/dist/vue.js"
      ),
    },
  },
};

npm ls lists a framework as invalid

Each entry point lists its framework as an optional peer - vue 3.3 or later for /vue. An app that uses only the core on an older framework, Vue 2 for one, installs as usual, but npm ls reports that framework as invalid for @nestjs/observe-browser. Nothing is wrong: the entry point that needs the newer version isn't the one the app imports.

Where to go next