The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·32

Frontend Observability

Seeing what happens in users' browsers: error tracking and source maps, real-user monitoring and Web Vitals, structured logs, distributed traces from browser to database with W3C trace context and correlation IDs, session context, and release health. Includes the privacy and sampling trade-offs.

25 topics · ~26 min read · 28-question quiz
Updated Suggest a correction

Start here: knowing what users actually experience

The frontend is a blind spot

When a backend fails, its logs and dashboards show it immediately. When a frontend fails, it fails on the user's device: a JavaScript error on one phone model, a page that takes 9 seconds on a slow network, a button that silently does nothing in one browser. Unless the page itself reports what happened, nobody on the team ever finds out; the user just leaves. Frontend observability means collecting enough information from real users' browsers to answer three questions:

  1. Is it broken? Errors, failed requests, crashes: error tracking.
  2. Is it slow? Load and interaction timings from real devices: real-user monitoring (RUM) of Web Vitals.
  3. Why? Context to connect a symptom to a cause: the release, browser, route, user action, and the backend trace behind a slow request.

Catching errors in the browser

Two global events see errors your code didn't catch:

JavaScript
const report = e => navigator.sendBeacon("/report", JSON.stringify(e));
window.addEventListener("error", e => report({ type: "error", message: e.message, source: e.filename, line: e.lineno, col: e.colno, stack: e.error?.stack }));
window.addEventListener("unhandledrejection", e => report({ type: "unhandledrejection", message: String(e.reason?.message ?? e.reason) }));

sendBeacon queues a small POST that the browser delivers even if the page is closing. A page with a failing API call and two third-party scripts that throw produced these reports:

Text
{"type":"unhandledrejection","message":"orders API returned 404"}
{"type":"error","message":"Script error.","source":"","line":0,"col":0,"stack":null}
{"type":"error","message":"Uncaught TypeError: Cannot read properties of undefined (reading 'toFixed')",
 "source":"http://127.0.0.1:8131/vendor-cors.js","line":1,"col":46,"stack":"TypeError: … at checkoutB (…/vendor-cors.js:1:46)"}

The second and third errors were the same bug in two copies of a script from another origin. The browser hid everything about the first ("Script error.", no file, no line) because it was loaded without permission to expose details across origins. The second was loaded with crossorigin="anonymous" and the server sent Access-Control-Allow-Origin, so the full message and stack came through. If your error tracker is full of useless "Script error." entries, that's why.

In practice you use a library or service (Sentry, Datadog RUM, New Relic, Grafana Faro, Bugsnag, or the OpenTelemetry web SDK) that does this plus grouping identical errors, source-map un-minifying (chapter 30), breadcrumbs (the clicks and requests before the error) and alerting.

Measuring speed for real users

Chapter 27 measured Web Vitals in a lab; RUM measures them for every real visit with the web-vitals library and sends them home:

JavaScript
import { onLCP, onINP, onCLS } from "web-vitals";
const send = metric => navigator.sendBeacon("/rum", JSON.stringify({ name: metric.name, value: metric.value, id: metric.id, page: location.pathname, release: "2026.10.29-1" }));
onLCP(send); onINP(send); onCLS(send);

How you summarise the numbers matters more than collecting them. 1,000 simulated visits, mostly fast with a slow tail of older phones on poor networks:

Text
LCP over 1,000 visits: average 2050 ms | median 1555 | p75 2397 | p95 5573 | share of visits over 2,500 ms: 23.9%

The average (2.05 s) looks "good"; but nearly a quarter of visits took longer than 2.5 s, and one in twenty took over 5.5 s. That's why Web Vitals are judged at the 75th percentile, and why dashboards should show percentiles and distributions (split by device type, country and route), never only averages.

Following one request from the browser to the database

A slow "My orders" page might be slow in the browser, the frontend server, the orders service or the database. Distributed tracing gives every operation a trace id shared across all the services it touches, passed along in the standard W3C traceparent header. The browser started a trace and each service logged with it:

Text
browser   trace=7919cd06c92c… span=2e66422bea842a50 user clicked 'My orders'
bff       trace=7919cd06c92c… span=bfb812da27fb099d GET /api/orders?user=42 (parent span 2e66422bea842a50)
orders    trace=7919cd06c92c… span=fd1953074cb9f436 GET /orders?user=42 (parent span bfb812da27fb099d)
orders    trace=7919cd06c92c… span=fd1953074cb9f436 SELECT … FROM orders took 42 ms

One id ties the click to the database query; each span records its parent, so a tracing tool (Jaeger, Grafana Tempo, Honeycomb, Datadog) can draw the whole request as a timeline and show which step was slow. OpenTelemetry is the vendor-neutral standard for producing these traces in browsers and servers alike (Volume 9 covers it in depth).

Releases and privacy

Tag every report with the release (a version or commit hash) so you can compare error rates and Web Vitals before and after each deploy, and roll back quickly when a release makes things worse (chapter 31). And collect responsibly: never send passwords, payment details or personal data in error messages or URLs, mask form inputs in session replays, sample high-volume data, and respect consent requirements (GDPR, India's DPDP Act).

How deep to go in frontend observability

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain error tracking, RUM, Web Vitals in the field, and tracing
L2 Add an error tracker and RUM to an app with releases and source maps
L3 Explain global error capture, cross-origin error masking, beacons and page lifecycle, percentiles, trace context propagation, sampling
L4 Diagnose production-only bugs from stack traces, breadcrumbs and traces; find which release, route or device regressed
L5 Design telemetry: what to collect, sampling, dashboards and alerts, privacy and consent
L6 Run observability as practice: SLOs for the frontend, release health gates, cost control, on-call for client issues

Why the frontend is a blind spot

Server code runs on machines you own, where logs, metrics and traces are routine (Vol. 6). Frontend code runs on millions of devices you don't control: old phones, flaky networks, browser extensions that inject scripts, ad blockers, corporate proxies, and dozens of browser versions. Without instrumentation, the first sign of a broken checkout is a drop in revenue or an angry tweet. Frontend observability answers four questions:

  1. Is it broken? Errors and crashes, with enough context to reproduce them.
  2. Is it slow? Real-user performance: Web Vitals, API latency as users experience it.
  3. Where is it slow or broken? Which release, route, browser, country or backend dependency.
  4. What did the user do? Breadcrumbs and session context leading up to the problem.

The three classic pillars apply, adapted to the browser:

Pillar Browser form Backend counterpart (Vol. 6)
Errors and logs Uncaught exceptions, rejected promises, console errors, structured events Application logs, exceptions
Metrics RUM: Web Vitals, page loads, API timings, aggregated as percentiles Micrometer/Prometheus metrics
Traces Spans for page load, navigation, fetch calls, propagated to the backend OpenTelemetry server spans

Errors

Frontend error tracking

Capture every failure path, not just window.onerror:

JavaScript
// 1. Uncaught synchronous errors (and errors in event handlers, timers)
window.addEventListener("error", (e) => {
  if (e.target !== window && e.target?.src) {          // resource load failure (img/script/link): no e.error
    report({ type: "resource", url: e.target.src || e.target.href });
    return;
  }
  report({ type: "error", message: e.message, stack: e.error?.stack, file: e.filename, line: e.lineno, col: e.colno });
}, true);                                               // capture phase: resource errors don't bubble

// 2. Unhandled promise rejections (most async bugs land here)
window.addEventListener("unhandledrejection", (e) => {
  report({ type: "rejection", reason: String(e.reason), stack: e.reason?.stack });
});

// 3. Framework error boundaries: React <ErrorBoundary>/onCaughtError/onUncaughtError (React 19 createRoot options),
//    Angular ErrorHandler, Vue app.config.errorHandler. Frameworks catch render errors before window.onerror.

// 4. Failed fetches: network errors throw; HTTP 4xx/5xx don't. Report both from your API client wrapper.

// 5. CSP violations (chapter 28): the securitypolicyviolation event or report-to endpoint.

What a good error event carries: message, stack trace, error type, release version, environment, URL and route, browser and OS, user or session ID (pseudonymous), breadcrumbs (the last N clicks, navigations, fetches and console messages), and the trace ID of the failing request. Tools: Sentry (the de facto standard, open source and self-hostable), Bugsnag, Rollbar, Datadog RUM, New Relic, Elastic RUM, Grafana Faro, Honeycomb, and LogRocket and Highlight for session replay.

Noise control matters as much as capture:

  • Group errors by fingerprint (normalised stack and message), so 50,000 events become one issue with a count and a trend.
  • Filter junk: browser-extension frames (chrome-extension://), Script error. from cross-origin scripts without CORS (add crossorigin="anonymous" plus Access-Control-Allow-Origin on your CDN to see real errors), ResizeObserver loop warnings, known bots, and aborted requests (AbortError from navigating away).
  • Rate-limit and sample, so one infinite error loop on one client doesn't exhaust your quota.
  • Alert on new issues, regressions (resolved issues that reappear in a new release), and spikes, not on every event.

Source maps

Production JavaScript is minified and bundled (chapter 30), so a raw stack trace reads at a.b (app.77d0e2.js:1:48213), which is useless. A source map (app.77d0e2.js.map) maps generated positions back to original file, line, column and identifier names, so the tracker can show at CheckoutForm.submit (src/checkout/CheckoutForm.tsx:84:11).

browserapp.77d0e2.js:1:48213release 2026.10.3 error trackermatch release +file → .map readable stackCheckoutForm.tsx:84:11+ source context CI: upload .map files(private, not on CDN)
Source map symbolication. The browser reports minified positions; the error tracker uses privately uploaded source maps to recover original files and lines.

How to handle them in production:

  • Generate them in production builds (build.sourcemap: "hidden" in Vite produces maps without the //# sourceMappingURL comment, and Angular has sourceMap: { hidden: true }).
  • Upload them privately to the error tracker in CI, tagged with the release identifier that the app also reports (sentry-cli sourcemaps upload --release 2026.10.3 dist/, or the Sentry Vite/webpack plugins). Newer tooling uses debug IDs injected into both the bundle and its map, which removes fragile release and filename matching.
  • Don't serve them publicly unless you're fine exposing your original source (comments, internal names, sometimes secrets someone mistakenly committed). Delete .map files from the deploy artifact after upload, or block *.map at the CDN.
  • The release identifier must be the same in the uploaded maps, in the SDK init (release: import.meta.env.VITE_RELEASE), and in the deploy. A mismatch is the most common reason stack traces stay minified.

Java parallel: source maps are to minified JS what debug symbols are to native binaries (DWARF/PDB for C, C++, Rust, Zig and Go binaries, symbolicated crash reports for iOS and Android). You strip symbols from the shipped artifact, keep them privately, and symbolicate on the server. JVM stack traces don't need this because bytecode keeps class, method and line tables, unless you obfuscate with ProGuard/R8, which produces a mapping.txt that plays exactly the source map's role.

Performance

Real-user monitoring (RUM)

Synthetic monitoring (Lighthouse, WebPageTest, Playwright checks from fixed locations) runs in controlled lab conditions: repeatable, good for catching regressions in CI (chapter 27). Real-user monitoring measures actual users on their real devices and networks, which is what they actually experience. You need both: lab data tells you why, field data tells you whether it matters.

RUM collects, per page view: navigation timing (DNS, TCP, TLS, TTFB, DOM content loaded, load), resource timing (per-file durations and sizes, for cross-origin files only with Timing-Allow-Origin), Web Vitals, long tasks and long animation frames, route changes in SPAs (soft navigations), and API call durations, plus dimensions: route, release, browser, device class, connection type (navigator.connection.effectiveType where available), and country.

JavaScript
// Navigation timing (one entry per page load)
const [nav] = performance.getEntriesByType("navigation");
const ttfb = nav.responseStart - nav.startTime;          // startTime is 0 for the navigation entry

// Observe long animation frames (LoAF): what blocked the main thread, with script attribution
new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (e.duration > 100) report({ type: "loaf", duration: e.duration, scripts: e.scripts?.map(s => s.sourceURL) });
  }
}).observe({ type: "long-animation-frame", buffered: true });

Aggregate as percentiles, never averages. Averages hide the long tail, and the tail is where users suffer and churn (Vol. 6). Report p75 (Google's Web Vitals threshold), p95 and p99, segmented by device and route. A median LCP of 1.8 s with a p95 of 9 s on low-end Android is a real problem that an average of 2.4 s conceals.

Web Vitals in the field

The Core Web Vitals (chapter 27) are field metrics measured at the 75th percentile of page views:

Metric Measures Good Poor
LCP (Largest Contentful Paint) Loading: when the main content appears ≤ 2.5 s > 4 s
INP (Interaction to Next Paint) Responsiveness: the worst-ish interaction latency over the visit ≤ 200 ms > 500 ms
CLS (Cumulative Layout Shift) Visual stability: unexpected layout movement ≤ 0.1 > 0.25

Supporting metrics: TTFB and FCP. Collect them with Google's web-vitals library, which handles the edge cases (back/forward cache restores, background tabs, reporting the final value when the page is hidden):

JavaScript
import { onLCP, onINP, onCLS, onTTFB } from "web-vitals/attribution";   // attribution build: tells you WHY

function send(metric) {
  const body = JSON.stringify({
    name: metric.name, value: metric.value, rating: metric.rating,     // "good" | "needs-improvement" | "poor"
    id: metric.id, navigationType: metric.navigationType,
    route: location.pathname.replace(/\d+/g, ":id"),                    // low-cardinality route, not raw URLs
    release: window.__CONFIG__.release,
    attribution: metric.name === "INP" ? metric.attribution.interactionTarget
               : metric.name === "LCP" ? metric.attribution.target : undefined,
  });
  // sendBeacon survives page unload; fetch keepalive is the alternative
  navigator.sendBeacon?.("/rum", body) || fetch("/rum", { method: "POST", body, keepalive: true });
}
onLCP(send); onINP(send); onCLS(send); onTTFB(send);

Key points:

  • Report on page hide, not on load: INP and CLS accumulate over the whole visit. The library does this for you, and sendBeacon/keepalive let the request survive unload.
  • Attribution turns a number into a fix: which element was the LCP and what delayed it (TTFB, resource load delay, render delay); which interaction target had the bad INP and whether the time was input delay, processing or presentation; which element shifted for CLS.
  • SPAs: classic Web Vitals are per page load. Route changes inside an SPA aren't separate page loads, so LCP reflects only the first route. Browsers are adding soft navigation measurement, and RUM vendors approximate it. Meanwhile, measure route-change durations yourself.
  • CrUX (Chrome User Experience Report) is Google's public field dataset for popular origins (Chrome users only), visible in PageSpeed Insights and Search Console. It's what Google Search uses. Your own RUM covers all browsers, at finer granularity, with your release tags.
  • Browser support: LCP and INP are available in Chromium-based browsers and in Firefox and Safari in recent versions, so check current Baseline status for your audience. CLS remains Chromium-centred. Your RUM coverage of the metric depends on the browser mix.

Logs and traces

Frontend logs

console.log in a user's browser goes nowhere you can see. Structured frontend logs are events you deliberately ship to a backend:

  • Log meaningful events (checkout step reached, payment SDK failed to load, feature flag evaluated, retry exhausted), not every render.
  • Use a structured shape (JSON with level, event, route, release, sessionId, traceId, and fields) so logs are queryable alongside backend logs (Vol. 6).
  • Batch and send periodically and on page hide (sendBeacon). Cap volume per session. Sample debug-level logs.
  • Ship through your own endpoint (a first-party /telemetry path, or a tunnel route for the vendor SDK). This avoids ad blockers, keeps CSP simple (connect-src 'self'), and lets you scrub data server-side.
  • Never log PII or secrets: form values, tokens, full URLs with query strings (?token=, ?email=), or response bodies. Redact by default and allow-list fields.

Distributed traces

A user's click ends up crossing many systems. Distributed tracing (Vol. 6) follows one request across all of them as a tree of spans, linked by a shared trace ID:

trace-id 4bf92f3577b34da6a3ce929d0e0e4736 browser: click "Place order" (user interaction span) browser: fetch POST /api/orders → traceparent: 00-4bf9…-01 gateway / ingress (Nginx, Envoy) order-service (Spring Boot): POST /api/orders Postgres INSERT orders Kafka publish inventory consumer (linked span) gap between browser span and server span = network + queueing as the user saw it the async consumer runs later; context travels in Kafka message headers
One trace from click to database. The browser starts the trace and propagates context in the traceparent header; every hop adds child spans with the same trace ID.
  • The browser creates the root span (a page load, a route change or a user interaction) and child spans for each fetch.
  • It propagates context to the backend in the W3C Trace Context header: traceparent: 00-<32-hex trace-id>-<16-hex parent-span-id>-<flags> (plus tracestate for vendor data). Older systems use B3 (X-B3-TraceId) or vendor headers.
  • Every backend hop (gateway, Spring Boot with Micrometer Tracing or the OpenTelemetry Java agent, Go and Rust services with their OTel SDKs) continues the same trace, and context flows through message headers into Kafka or queue consumers too.
  • The result is one waterfall from click to database. It shows whether the 3 seconds the user waited went to the network, the gateway, a slow SQL query, or a downstream call.

OpenTelemetry is the vendor-neutral standard. The browser SDK (@opentelemetry/sdk-trace-web with fetch, XHR and document-load instrumentations) exports OTLP to a collector, which forwards to Jaeger, Tempo, Honeycomb, Datadog, New Relic or others.

JavaScript
import { WebTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-web";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";

const provider = new WebTracerProvider({
  spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({ url: "/otel/v1/traces" }))], // first-party collector route
});
provider.register();

registerInstrumentations({
  instrumentations: [
    new DocumentLoadInstrumentation(),
    new FetchInstrumentation({
      // ONLY propagate traceparent to your own APIs: sending it cross-origin leaks IDs
      // and triggers CORS preflights (traceparent is not a CORS-safelisted header)
      propagateTraceHeaderCorsUrls: [/^https:\/\/api\.shop\.example\.com\//],
    }),
  ],
});

CORS caveat: traceparent is a custom header, so cross-origin API calls with it require a preflight and the API must list it in Access-Control-Allow-Headers (chapter 19). Same-origin APIs (behind the reverse proxy of chapter 31) avoid this.

The server can also send its trace ID back to the browser (the Server-Timing header: Server-Timing: traceparent;desc="00-…", readable through PerformanceResourceTiming.serverTiming when Timing-Allow-Origin allows it), which links even the HTML document request (which the browser makes before your JS runs) to the server-side trace.

Correlation IDs

Full tracing isn't always available. A correlation ID (request ID) is the minimum: one ID per request, generated at the edge or in the client, passed in a header (X-Request-ID), logged by every service, and returned in error responses.

Java
// Spring Boot: put the trace/correlation ID in every log line (MDC) and in error bodies
@Component
class CorrelationFilter extends OncePerRequestFilter {
  @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
      throws ServletException, IOException {
    String id = Optional.ofNullable(req.getHeader("X-Request-ID")).filter(s -> s.matches("[A-Za-z0-9-]{8,64}"))
                        .orElseGet(() -> UUID.randomUUID().toString());     // validate untrusted input
    MDC.put("requestId", id);
    res.setHeader("X-Request-ID", id);
    try { chain.doFilter(req, res); } finally { MDC.remove("requestId"); }  // thread reuse: always clear
  }
}
// With Micrometer Tracing, traceId/spanId are added to the MDC automatically, and
// ProblemDetail error responses can include them so support can find the trace.
Go
// Go: the same idea via context.Context
func withRequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" { id = uuid.NewString() }
        w.Header().Set("X-Request-ID", id)
        ctx := context.WithValue(r.Context(), requestIDKey{}, id)
        next.ServeHTTP(w, r.WithContext(ctx))   // loggers read it from ctx (slog handler)
    })
}

The frontend attaches the ID from failed responses to its error reports and shows it to users in error messages ("Something went wrong. Reference: 7f3a…"). Then a support ticket leads straight to the backend logs and the trace. Thread-local MDC breaks across async boundaries (Vol. 1 ch. 8's thread pools, Reactor, virtual threads with context propagation), so use Micrometer's context propagation or OpenTelemetry context, which carry it correctly.

Users and releases

Session context

Errors and slow pages make sense only in context:

  • Breadcrumbs: a ring buffer of recent events (navigations, clicks with element selectors, fetches with status codes, console warnings), attached automatically to error reports.
  • Session ID: a random pseudonymous ID per visit (stored in sessionStorage), linking all errors, vitals, logs and traces from one visit. A user ID (hashed or internal, never an email) lets support look up "what happened to this customer".
  • Session replay (Sentry Replay, LogRocket, FullStory, PostHog): records DOM mutations (not video) so you can watch what the user saw. It's extremely powerful for debugging, but heavy on privacy. Mask all text and inputs by default, block sensitive areas (payment forms, health data), and sample (for example 1% of sessions, 100% of sessions with errors).
  • Feature-flag state and A/B variants in the context, so a regression can be tied to the flag that caused it.

Privacy and law (GDPR, ePrivacy, CCPA): telemetry that identifies people is personal data. Minimise what you collect, scrub PII at the source and the collector, set retention limits, honour consent where required (analytics-style tracking often needs it, while strictly necessary error monitoring is argued differently by different regulators, so involve your privacy team), document processors, and consider self-hosted or EU-region tooling.

Release health

Every telemetry event carries the release (version or git SHA) and environment. That enables release health:

  • Crash-free sessions/users per release (Sentry's release health, Firebase Crashlytics for mobile).
  • New issues introduced in a release, and regressions of resolved issues.
  • Web Vitals and API error rates per release, compared against the previous release. This is a canary analysis signal for progressive rollouts (chapter 31).
  • Adoption: what fraction of sessions run the new release. Long-lived tabs and service workers keep old versions alive (chapter 29), so expect version skew.
  • Suspect commits: linking releases to commits (CI uploads commit ranges) lets the tool suggest which change introduced an issue and who touched it.
JavaScript
// One init, release-tagged, sampled, privacy-aware (Sentry shown; others are similar)
Sentry.init({
  dsn: window.__CONFIG__.sentryDsn,
  release: window.__CONFIG__.release,           // same string used when uploading source maps
  environment: window.__CONFIG__.env,
  tunnel: "/telemetry/sentry",                    // first-party route: survives ad blockers, CSP connect-src 'self'
  tracesSampleRate: 0.1,                          // 10% of transactions traced
  tracePropagationTargets: [/^\/api\//],          // propagate traceparent only to own API
  replaysSessionSampleRate: 0.01,
  replaysOnErrorSampleRate: 1.0,
  integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration({ maskAllText: true, blockAllMedia: true })],
  beforeSend(event) {                             // last-chance scrubbing
    if (event.request?.url) event.request.url = event.request.url.split("?")[0];
    return event;
  },
});

The full picture: browser to database

browsererrors·RUM·spans gatewayaccess logs Spring Boot APIlogs·metrics·spans Postgres · Kafkaquery spans · consumers traceparent / X-Request-ID / release on everything collector (OTel) + scrubbing error tracker metrics / RUM traces logs
End-to-end observability. Every layer emits telemetry tagged with the same trace ID and release, so one user-reported problem can be followed across the stack.

A typical investigation: an alert fires that INP p75 regressed on /checkout in release 2026.10.3. Attribution shows the slow interaction is the "Apply coupon" button, and LoAF shows a long script in the coupon module. Separately, an error spike for that release shows TypeError in CouponField.tsx:42 (source-mapped), with breadcrumbs showing a POST /api/coupons that returned 500. Its trace ID leads to a Spring span whose SQL query took 2.8 s because of a missing index on coupons(code). Logs carrying the same trace ID confirm the timeout. One identifier joins the evidence across five systems.

Paradigm note: observability is the same discipline in every stack, and only the instrumentation surface differs. Java uses Micrometer plus OpenTelemetry (agent-based bytecode instrumentation, or the Spring Boot starter). Go passes context.Context explicitly through every call (no thread-locals, so propagation is visible in signatures). Rust uses the tracing crate (spans as scoped guards, #[instrument]) with an OTel layer. C, C++ and Zig use the OTel C++ SDK or manual instrumentation. Browser JavaScript has no threads but has async continuations, which is why browser context propagation across await is harder and relies on Zone.js-style tricks or explicit context passing until the TC39 AsyncContext proposal lands.

Lab: telemetry from the browser, examined

Chromium 153 sending reports to small Node servers; the percentile experiment ran in Node 22 on simulated data. The point is to see exactly what reaches your backend, because that's all your dashboards will ever know.

Experiment 1: what global error handlers actually receive

A shop page installs error and unhandledrejection listeners that send each report with sendBeacon. Then three things go wrong: an API call returns 404 inside a promise chain with no catch; and two copies of the same buggy checkout script are loaded from another origin (127.0.0.1:8131), one plainly and one with crossorigin="anonymous" from a server that sends Access-Control-Allow-Origin: *:

HTML
<script src="http://127.0.0.1:8131/vendor.js"></script>
<script crossorigin="anonymous" src="http://127.0.0.1:8131/vendor-cors.js"></script>
<script>fetch("/api/missing").then(r => { if (!r.ok) throw new Error("orders API returned " + r.status); });</script>
Text
{"type":"unhandledrejection","message":"orders API returned 404"}
{"type":"error","message":"Script error.","source":"","line":0,"col":0,"stack":null}
{"type":"error","message":"Uncaught TypeError: Cannot read properties of undefined (reading 'toFixed')",
 "source":"http://127.0.0.1:8131/vendor-cors.js","line":1,"col":46,
 "stack":"TypeError: Cannot read properties of undefined (reading 'toFixed') | at checkoutB (http://127.0.0.1:8131/vendor-cors.js:1:46)"}
  • The failed fetch surfaced only as an unhandled rejection, not an error event, which is why trackers must listen to both. Note that fetch didn't reject on the 404 (chapter 15); the code's own throw did. Many apps never report HTTP errors at all unless they check response.ok.
  • The plain cross-origin script produced the useless "Script error.": browsers deliberately strip details from errors in scripts that haven't opted in to CORS, so a page can't learn things about other origins' scripts (for example, whether you're logged in somewhere, from an error message). Most applications serve their own bundles from a CDN on a different hostname, so this bites first-party code too.
  • With crossorigin="anonymous" plus the CORS header, the full message, file, line, column and stack came through, ready for source-map un-minifying.

Experiment 2: averages versus percentiles

1,000 simulated LCP measurements: 70% fast (0.9–1.8 s), 20% middling (1.8–3.3 s), 10% slow (3.3–7.3 s), the typical shape of real traffic with a long tail from older devices and weaker networks:

Text
LCP over 1,000 visits: average 2050 ms | median 1555 | p75 2397 | p95 5573 | share of visits over 2,500 ms: 23.9%

The average is a number no user experienced: it's dragged up by the tail yet still sits under the 2.5 s "good" line, while one visit in four was slower than that and one in twenty over 5.5 seconds. The p75 (2,397 ms) is the official Core Web Vitals summary; the p95 and the "share over threshold" tell you how bad the tail is. Real dashboards also split by dimension, because a fine global p75 can hide a broken segment (one route, one browser version, one country, low-end Android). Note the cost side too: RUM sends a beacon per metric per visit, so high-traffic sites sample (for example 10% of sessions), which still gives tight percentiles at scale.

Experiment 3: one trace from click to query

The browser generated a W3C traceparent header (00-{32 hex trace id}-{16 hex span id}-01) for the "My orders" request; the frontend server (a BFF) and the orders service each started a child span and passed the header on:

Text
browser   trace=7919cd06c92c… span=2e66422bea842a50 user clicked 'My orders'
bff       trace=7919cd06c92c… span=bfb812da27fb099d GET /api/orders?user=42 (parent span 2e66422bea842a50)
orders    trace=7919cd06c92c… span=fd1953074cb9f436 GET /orders?user=42 (parent span bfb812da27fb099d)
orders    trace=7919cd06c92c… span=fd1953074cb9f436 SELECT … FROM orders took 42 ms

Every log line about this one user action shares a trace id, and each span names its parent, which is all a tracing backend needs to reconstruct the tree. Two details matter in production. Browsers may only send a custom header like traceparent to another origin if that origin's CORS policy allows it (Access-Control-Allow-Headers: traceparent), so cross-origin APIs must opt in; and to avoid leaking trace ids to third parties, OpenTelemetry's web instrumentation propagates context only to URLs you list (propagateTraceHeaderCorsUrls). The server side should sample consistently with the browser's decision (the 01 flag means "sampled").

Try it yourself

  1. Add Sentry (or Grafana Faro, or the OpenTelemetry web SDK) to a project, upload source maps for a release, and trigger an error in a minified build. Compare the stack trace with and without the maps.
  2. Find the "Script error." share in your tracker. Which of your scripts are loaded cross-origin without crossorigin?
  3. Compute p50, p75 and p95 of your site's INP from CrUX (PageSpeed Insights) and compare them with your own RUM. Why might they differ?
  4. Propagate traceparent from a browser fetch into a Spring Boot or Node backend instrumented with OpenTelemetry, and view the joined trace in Jaeger.

Revision sheet: frontend observability

Key ideas

  • The frontend runs on devices you don't control; without client telemetry, errors and slowness are invisible.
  • Error tracking: error and unhandledrejection handlers (plus framework error boundaries); grouping by fingerprint; breadcrumbs; release tagging; source maps uploaded per release; cross-origin scripts need crossorigin + CORS for details.
  • Delivery: sendBeacon or fetch(…, { keepalive: true }), triggered on visibilitychange to hidden (the last reliable moment, especially on mobile); batching; sampling.
  • RUM: Web Vitals via web-vitals (with attribution builds), navigation and resource timing, long animation frames; summarise with percentiles and distributions by segment.
  • Tracing: W3C Trace Context (traceparent, tracestate), OpenTelemetry web SDK, spans for page loads, route changes and fetches, propagation only to allowed origins; correlation ids in logs.
  • Session context and replay: route, release, feature flags, device; session replay with input masking.
  • Release health: crash-free sessions, error rate and Web Vitals per release; canary comparison; fast rollback.
  • Privacy: no secrets or personal data in telemetry; masking; consent; data retention.

Numbers to remember

  • Lab: average LCP 2,050 ms while 23.9% of visits exceeded 2.5 s; p75 2,397 ms; p95 5,573 ms.
  • traceparent = version 00 - 32-hex trace id - 16-hex parent span id - flags (01 sampled).

Pitfalls

  • Only listening for error and missing rejected promises; not reporting HTTP failures.
  • "Script error." from CDN-hosted bundles without crossorigin.
  • Averages on dashboards; no segmentation; no release dimension.
  • Sending telemetry on unload (unreliable on mobile, blocks the bfcache).
  • Unbounded volume (every console log, 100% sampling) and cost surprises.
  • Personal data in URLs, error messages and replays.

Glossary

  • RUM: real-user monitoring, performance data from actual visits.
  • Breadcrumbs: the recent events (clicks, navigations, requests, logs) attached to an error report.
  • Fingerprint: the key that groups identical errors together.
  • Span: one timed operation in a trace, with a parent.
  • Sampling: recording a fraction of sessions or traces to control cost.
  • Release health: error and performance metrics compared per deployed version.