Skip to content

Measuring in Production ​

Collect the field data that makes performance and errors debuggable, without shipping user data to a vendor or drowning in noise.

In this chapter: field against lab, and what each cannot see · web-vitals and attribution · the four places an error reaches you · the context that gets a bug fixed · redaction and sampling · crash-free sessions as the frontend SLO

💡 The Core Idea ​

Performance and error tracking are the same instrument. Both answer "what actually happened to real users". Both are collected in the browser and sent to something you did not build. And both are useless without the same three fields: which release, which user, which page.

They share one chapter because the interesting failures are linked. A spike in INP and a spike in unhandled rejections after a deploy are the same incident described twice. Wiring them separately gives you two dashboards nobody joins up.

The uncomfortable half is that all of this data leaves the browser. Session replay is a recording of somebody using your product. Treat it as a technical decision rather than a privacy one, and you end up with card numbers in a vendor's database.

How It Works ​

Field and lab answer different questions ​

Field (real users)Lab (a scripted load)
Tells youWhether you have a problem, and for whomWhy, with a waterfall and a trace
Device and networkWhatever users haveOne profile you chose
Can measure INPYesNo — nobody is interacting
Good in CINo — needs trafficYes, and deterministic enough to gate on

You need both, and the split is clean: lab data gates the pull request, field data tells you what to work on. A team with only lab data optimises for a simulated profile. A team with only field data knows it is slow and cannot say why.

The one hard difference is INP. There is no interaction in a lab run, so Lighthouse reports Total Blocking Time as a stand-in. Fixing INP therefore requires field data. See Core Web Vitals.

Collecting vitals, and the attribution build ​

typescript
import { onCLS, onINP, onLCP, onTTFB, type Metric } from "web-vitals";

function report(metric: Metric): void {
  const { name, value, rating } = metric;
  const body = JSON.stringify({ name, value, rating, release: __APP_VERSION__, route: location.pathname });
  // sendBeacon survives the unload that finalises CLS and INP.
  navigator.sendBeacon?.("/api/vitals", body) ??
    fetch("/api/vitals", { body, method: "POST", keepalive: true });
}

[onLCP, onINP, onCLS, onTTFB].forEach((collect) => collect(report));

⚠️ onFID no longer exists. FID was retired in 2024 and removed from the library. Code or an article using it is out of date by more than a metric name.

A bare value tells you there is a problem. The attribution build tells you where:

typescript
import { onINP, onLCP } from "web-vitals/attribution";

onLCP((m) => report({ ...m, element: m.attribution.target }));
onINP((m) => report({ ...m, target: m.attribution.interactionTarget }));

That turns "p75 INP is 480 ms" into "p75 INP is 480 ms, on the filter dropdown in the reports table". Collect attribution from the start. Adding it later means waiting another week for data.

For anything the vitals do not cover, PerformanceObserver watches the browser's own timeline:

typescript
// Long tasks are the direct cause of poor INP — over 50 ms cannot be interrupted.
new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.duration > 50) report({ name: "longtask", value: entry.duration });
  }
}).observe({ type: "longtask", buffered: true });

The four places an error can reach you ​

Miss any one and a whole class of failure is invisible.

SourceCatchesInvisible without it
Framework error boundariesThrows during render and commitEvery render crash
window.onerrorUncaught errors in handlers, timers, third-party codeHandler and vendor-script failures
unhandledrejectionRejected promises with no .catch()Most failed fetch calls
Explicit captureHandled errors you still want to know aboutRetries and degraded modes — the silent ones
typescript
window.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) => {
  const { reason } = event;
  const stack = reason instanceof Error ? reason.stack : undefined;
  navigator.sendBeacon("/api/errors", JSON.stringify({
    kind: "rejection", message: String(reason), stack,
    release: __APP_VERSION__, route: location.pathname,
  }));
});

unhandledrejection is the one teams forget, and it is where most real failures land. An await fetch with no try produces a rejection, not an error, so window.onerror never fires. See Suspense, Streaming and Error Boundaries for the render-time half.

The context that decides whether a bug gets fixed ​

An error report without these is a string somebody closes.

FieldWhy it matters
Release versionWhether this is new. Without it every deploy resets your baseline
Source maps, uploaded per releaseA minified stack is unreadable. Keep them private, not public on the CDN
Component stackLocates the failure in the tree when the JavaScript stack cannot
BreadcrumbsThe last few clicks, navigations and requests — the nearest thing to a reproduction
A user identifierTurns "1,200 events" into "three users, one in a retry loop"
Browser and deviceMost long-tail errors are one engine or one old version

An identifier, not an identity. user.id is enough to count affected people. A name and an email address in an error service is personal data you now have to account for.

Redact in the browser, before it leaves ​

Every serious client offers a before-send hook. Use it: that is the last point at which the data is still yours. Strip any query parameter or header matching /token|password|secret|authorization|email|card/i. Query strings are the most common accidental leak, because tokens often end up in URLs and then in error reports.

⚠️ Mask session replay by default and unmask deliberately. An allow-list fails safe. A deny-list fails the first time somebody adds a form field. A replay of a checkout captures the card input unless you stopped it in advance, and "we will add it to the deny-list" is not a plan.

Sampling, because both budgets are finite ​

An error service bills per event, and a human triages per issue.

SignalRateWhy
Errors100%They are rare, and the rare one is the interesting one
Performance traces1–10%Continuous and expensive; a sample is statistically sufficient
Session replay, all sessions~1%Storage and privacy cost
Session replay, sessions with an error100%The only session you actually want is the one that broke

Most noise is not your code: browser extensions injecting scripts, bot traffic, and ResizeObserver loop completed with undelivered notifications, which is usually harmless. Filter in the client rather than in triage, and drop any event whose stack has no frame from your own origin.

Alert on user impact, not on event count ​

A spike of 500 events from one user in a retry loop is not an incident. Five users unable to check out is.

IndicatorTargetWindow
Sessions with no fatal error99.5%24 h
Checkout started → completed97%1 h
p75 LCP under 2.5 s90%24 h

Crash-free sessions is the frontend metric to reach for first, because it normalises by traffic. A raw error count spikes on a busy day and hides a regression behind growth. A rate does neither. The alerting discipline itself is Metrics, Dashboards and Alerting, and it applies here unchanged.

When to Use It ​

SituationReach forWhy
"Is the site slow?"Field data, segmented by deviceYour laptop is not the 75th percentile
"Why is this page slow?"A lab run — trace and waterfallDeterministic and inspectable
Poor INP with no idea whereAttribution buildNames the interaction target
A regression that only appears in CILab, in the pipelineGate the pull request on it
A crash nobody can reproduceBreadcrumbs, and a replay of that sessionThe nearest thing to a repro
Deciding what to fix nextAffected user count, not event countImpact, not volume

Common Mistakes ​

❌ Collecting vitals without attribution. You learn there is a problem and not where. ✅ Use the attribution build from day one.

❌ No unhandledrejection listener. Most failed fetch calls are silent. ✅ Both window listeners, plus framework boundaries and explicit capture.

❌ No release version on reports. Every deploy resets the baseline and nothing is ever "new". ✅ Stamp the release, and upload matching source maps.

❌ Session replay unmasked by default. The first form you add leaks. ✅ Mask everything, unmask specific fields deliberately.

❌ Alerting on error count. It tracks traffic as much as it tracks health. ✅ Alert on crash-free sessions and completion rates.

🔑 Key Takeaways ​

  • Lab data gates the pull request, and field data tells you what to work on. INP exists only in the field.
  • The attribution build is what turns a bad metric into a named element or interaction.
  • Four capture points are needed for full error coverage, and unhandledrejection is the one usually missing.
  • Release version and uploaded source maps are what make a minified production stack usable at all.
  • Crash-free sessions is the frontend SLO (service-level objective) to start with, because a rate does not move with traffic.

Interview Questions ​

Q: Lighthouse gives the site 95 and users say it is slow. Who is right?

The users. Lighthouse is one scripted load on one device profile. It cannot measure INP at all, because nothing interacts with the page. Field data at the 75th percentile describes reality. It will usually show the problem is responsiveness on mid-range phones rather than load. The lab run is still useful, but for diagnosis, not for judgement.

Q: What do you need on an error report before it is worth triaging?

Release version, a readable stack from uploaded source maps, the route, and a user identifier. The identifier lets you count affected people rather than events. Add breadcrumbs if you can get them: the clicks and requests before the throw are the closest thing to a reproduction. Without the release version in particular, you cannot tell a new regression from something that has been failing for months.

Q: What is the privacy exposure here, and what do you do about it?

Everything collected leaves the browser for a third party, and session replay is a recording of someone using your product. First, redact in a before-send hook, so the last decision happens on your side. Mask replay input by default and unmask specific fields deliberately. Send an opaque user id rather than a name or email. And strip sensitive query parameters: tokens in URLs are the most common accidental leak.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.