Frontend tracing with OpenTelemetry: traceparent, CORS and linking browser spans to the backend

Trace from click to database: W3C traceparent, OpenTelemetry web instrumentation, propagateTraceHeaderCorsUrls, CORS preflights, sampling, OTLP export and privacy.

Advanced 13 min readBy , updated 23 November 2026

A user reports that checkout takes eight seconds. Real-user monitoring confirms the page is slow for some people. The backend dashboards show every service answering quickly. Nobody can say where the time went, because the browser's view and the servers' views are separate datasets with nothing joining them. Distributed tracing fixes that: the browser starts a trace, sends its id with every API request, and each backend service adds its spans to the same trace, so one timeline shows the click, the network, the gateway, the services and the database. This guide covers how that works in a browser with OpenTelemetry: the W3C Trace Context headers, the web instrumentations, the CORS rules that trip most teams up, sampling, exporting, privacy, and where tracing fits next to RUM.

The vocabulary

  • A trace is one end-to-end operation, such as "submit checkout", identified by a 16-byte trace id.
  • A span is one timed step inside it: a fetch from the browser, a handler on the server, a database query. Each span has an 8-byte span id, a parent span id, a start and end time, a name and attributes.
  • Context propagation carries the current trace id and span id from one process to the next, in HTTP headers.
  • An exporter sends finished spans somewhere, usually as OTLP (the OpenTelemetry protocol) to an OpenTelemetry Collector, which batches, filters, samples and forwards them to a tracing backend.

OpenTelemetry (OTel) is the vendor-neutral standard for all of this, with an API, SDKs per language and instrumentation libraries. Using it on both the frontend and the backend means traces join regardless of which tracing vendor stores them.

W3C Trace Context: traceparent and tracestate

Propagation between services uses the W3C Trace Context headers. The main one is traceparent:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             │  │                                │                └ trace flags (01 = sampled)
             │  │                                └ parent id: the caller's span id, 16 hex characters
             │  └ trace id: 32 hex characters, shared by every span in the trace
             └ version

When the browser's fetch span sends this header, the server creates its own span with the same trace id and with the browser's span as its parent. The trace flags carry the sampling decision, so a backend that respects its parent records the trace whenever the browser decided to.

tracestate is an optional companion header: a list of vendor-specific key-value pairs (up to 32 entries) that lets tracing systems carry their own data alongside the standard ids. Many browser setups never set it. A related W3C header, baggage, carries application key-value pairs to downstream services. Be careful with it from a browser: anything in baggage is sent to every service that receives the request, so it must never contain personal data or anything you would not put in a URL.

What the browser records

The OpenTelemetry JavaScript project provides browser instrumentations that create spans without changing your application code:

  • Document load creates spans for the page navigation and the resources it fetched, built from the Navigation Timing and Resource Timing data the browser already collects.
  • Fetch and XMLHttpRequest instrumentations wrap every request in a span and inject the traceparent header.
  • User interaction creates spans for clicks and similar events, so requests triggered by a click become children of it.

You add your own spans around operations that matter to the product, such as "render search results" or "submit checkout", with the tracing API:

import { trace } from "@opentelemetry/api";

const tracer = trace.getTracer("checkout");

async function submitCheckout(cart) {
  return tracer.startActiveSpan("checkout.submit", async (span) => {
    try {
      span.setAttribute("cart.item_count", cart.items.length);
      const res = await fetch("/api/orders", { method: "POST", body: JSON.stringify(cart) });
      span.setAttribute("http.response.status_code", res.status);
      return res;
    } finally {
      span.end(); // a span that never ends is never exported
    }
  });
}

Because the fetch happens while checkout.submit is the active span, the fetch span becomes its child, and the backend's spans become the fetch span's children. One trace, from the click to the database.

Setting it up

Browser support in OpenTelemetry JavaScript is still marked experimental, and the packages have been moving. In the JS SDK 3.0 line, the separate sdk-trace-base, sdk-trace-web and sdk-trace-node packages were replaced by one @opentelemetry/sdk-trace package, and newer browser instrumentations are being developed in the opentelemetry-browser repository. The concepts and option names below have stayed the same; check the version you install against the official browser getting-started docs.

import { context, propagation, trace } from "@opentelemetry/api";
import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler, TracerProvider } from "@opentelemetry/sdk-trace";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import { W3CTraceContextPropagator } from "@opentelemetry/core";
import { ZoneContextManager } from "@opentelemetry/context-zone";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";

const provider = new TracerProvider({
  resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "web-checkout" }),
  sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.1) }), // keep 10% of traces
  spanProcessors: [new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ url: "https://telemetry.example.com/v1/traces" }) })],
});

trace.setGlobalTracerProvider(provider);
context.setGlobalContextManager(new ZoneContextManager().enable());
propagation.setGlobalPropagator(new W3CTraceContextPropagator());

registerInstrumentations({
  instrumentations: [
    new DocumentLoadInstrumentation(),
    new FetchInstrumentation({
      propagateTraceHeaderCorsUrls: [/^https:\/\/api\.example\.com\//], // our API only, never third parties
      ignoreUrls: [/\/v1\/traces$/], // do not trace the exporter's own requests
    }),
  ],
});

A few pieces need explaining.

The context manager. On a server, Node.js tracks the active span across await using async hooks. Browsers have no equivalent, so after an await or a setTimeout the SDK can lose track of which span is active. ZoneContextManager uses Zone.js to carry context across asynchronous boundaries. It adds weight to the bundle and patches browser APIs, so some teams use the default stack-based context manager instead and pass context explicitly in the few places that need it. Know that the choice exists; it explains "why are my fetch spans not children of my click span?"

The batch processor. Spans are queued and sent in batches rather than one request per span. In the browser it also flushes when the page is hidden, which is the last reliable moment before a tab is closed or frozen, much like sending analytics on visibilitychange.

Loading it late. The SDK and its instrumentations are not tiny. Load them after the page's critical work, for example in an idle callback after first render. Document load spans are reconstructed from timing data the browser keeps, so they are still accurate when recorded later.

Propagating headers across origins

By default the fetch and XHR instrumentations add traceparent only to same-origin requests. If your API lives on another origin, such as api.example.com called from www.example.com, you must list it in propagateTraceHeaderCorsUrls, which takes strings and regular expressions. This default is deliberate, and you should keep the list narrow for two reasons:

  • Leaking ids to third parties. A trace id sent to an analytics vendor or payment provider tells them nothing useful and reveals your internal trace ids.
  • Breaking other people's servers. Adding a custom header to a cross-origin request changes how the browser sends it, as the next section explains. Third-party APIs and CDNs that do not expect traceparent will reject the request, and a feature breaks because of telemetry.

CORS and the preflight

traceparent is not a CORS-safelisted request header. The safelist covers only a few headers, such as Accept, Accept-Language, Content-Language and Content-Type with simple values. So the moment the browser adds traceparent to a cross-origin request, the request becomes non-simple, and the browser first sends a preflight OPTIONS request asking the server whether that header is allowed. If the server's response does not list traceparent in Access-Control-Allow-Headers, the browser blocks the real request and your code sees a network error. A tracing rollout that forgets this breaks every cross-origin call.

The API server's CORS handler must allow the trace headers:

const ALLOWED_ORIGINS = new Set(["https://www.example.com"]);

function handleCors(req, res) {
  const origin = req.headers.origin;
  if (ALLOWED_ORIGINS.has(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Vary", "Origin");
  }
  if (req.method !== "OPTIONS") return false;

  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "content-type, authorization, traceparent, tracestate");
  res.setHeader("Access-Control-Max-Age", "600"); // cache the preflight so it is not repeated on every call
  res.statusCode = 204;
  res.end();
  return true;
}

Preflights also cost time: an extra round trip before requests that did not need one. Access-Control-Max-Age lets the browser cache the answer per URL, and browsers cap it (Chromium at two hours). The cleanest fix is to avoid the cross-origin call altogether by serving the API from the same origin through a reverse proxy path such as /api. Then no preflight is needed, and the trace header is propagated by default. Diagnosing a failing CORS preflight practises exactly this failure, and the CORS answer covers the rules.

Linking the page load to the server render

Fetch spans carry context outwards, but the HTML document itself is requested by the browser before any JavaScript runs, so nothing can add a header to it. To join the server-side render with the browser's document load span, the server sends its trace context in the page. The document load instrumentation reads a meta tag:

<meta name="traceparent" content="00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-01" />

The server renders this with the trace id of the request that produced the HTML, and the browser's document load spans join that trace. For a server-rendered app this answers "was the page slow because of the server render or the client?" in one view. Do not cache HTML containing a per-request trace id at a CDN, or every visitor joins the same trace.

Sampling

Recording every trace from every browser is expensive and unnecessary. Decide what to keep:

  • Head sampling in the browser. TraceIdRatioBasedSampler(0.1) keeps about one trace in ten, decided at the start from the trace id. Wrapping it in ParentBasedSampler makes child spans follow their parent's decision, so a trace is never half recorded. The decision travels in the sampled flag of traceparent.
  • Respect the flag on the backend. If the browser samples 10% and the API independently samples 1%, most browser traces arrive with no backend spans. Configure backend services to follow the parent's decision for requests that carry one.
  • Tail sampling at the collector. The collector can hold whole traces briefly and keep the interesting ones: errors, slow traces, specific routes. This needs the browser to send more spans than you will keep, so it trades network and collector cost for better data.
  • Sample by session for some questions. "What did this user's whole session look like?" needs every trace in a sampled session, not a random 10% of requests.

The frontend observability design question practises choosing sampling rates against a budget.

Exporting to a collector

Browsers export over OTLP using HTTP; the gRPC exporters do not work in browsers. The usual path is browser to a public endpoint, then to a collector:

  • Do not expose the collector directly. Put a reverse proxy or gateway in front that rate-limits, checks the origin, caps payload sizes and drops malformed data. Anyone can send spans to a public endpoint, so treat incoming telemetry as untrusted input.
  • No secrets in the browser. API keys for your tracing vendor must not ship in JavaScript. The proxy or collector adds credentials when forwarding.
  • CORS on the collector too. The exporter's request is cross-origin unless you proxy it, and its JSON or protobuf content type is not a simple one, so it is preflighted. The collector's OTLP HTTP receiver has a cors setting:
receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318
        cors:
          allowed_origins:
            - https://www.example.com
          max_age: 7200
  • Content Security Policy. If the site has a CSP, the telemetry endpoint must be allowed in connect-src, or the browser blocks exports silently.

Privacy: no personal data in spans

Spans are easy to fill with personal data by accident, and tracing backends are rarely designed to delete one user's data on request. Rules to state in an interview:

  • URLs are the main leak. Fetch spans record the full URL in url.full, including query strings with emails, search terms or tokens, and path segments with user ids. Strip or rewrite them in the instrumentation's hooks (applyCustomAttributesOnSpan can overwrite attributes once a request finishes), and scrub again in the collector with its attribute-processing features, so a missed case on one client is still caught.
  • Never record bodies, headers or form values. Authorization headers and cookies especially.
  • Use pseudonymous ids. A random session id is enough to group traces; an email is not needed.
  • Respect consent. In regions that require it, do not start the SDK until the user has agreed to performance telemetry.

Masking PII in log lines trains the scrubbing step.

Tracing, RUM and Web Vitals

Tracing does not replace real-user monitoring; they answer different questions.

  • RUM and Web Vitals answer "how fast is the site for real users?" as distributions: LCP, INP and CLS by route, device and country, reported with the web-vitals library or a RUM vendor. See the Core Web Vitals answer and measuring Web Vitals with a performance monitor.
  • Traces answer "why was this particular operation slow?" by showing every step of one request across systems.

They are strongest together. Attach the trace id to RUM events and error reports, so a poor INP sample or an error links straight to the trace of the interaction that caused it. OpenTelemetry's newer browser work includes Web Vitals and long animation frame instrumentation that emit events through the same pipeline, which may let one SDK cover both in future; it is experimental today. For main-thread problems, traces show the gaps, and a performance profile shows what filled them, as in analysing a performance trace for long tasks.

The broader picture of errors, source maps, RUM and rollouts is in observability and testing in system design.

How to talk about it in an interview

Tracing comes up when an interviewer asks "how would you debug a slow checkout in production?" or "how do you connect frontend errors to backend logs?". A strong answer, in order:

  1. The goal: one trace from the user's action to the database, so slowness can be located.
  2. Propagation: the W3C traceparent header, its trace id, parent id and sampled flag.
  3. Instrumentation: OpenTelemetry's document load and fetch instrumentations, plus custom spans around key user actions.
  4. Cross-origin calls: propagateTraceHeaderCorsUrls for your own API only, the preflight it causes, Access-Control-Allow-Headers on the server, or a same-origin proxy to avoid both.
  5. Cost: head sampling with parent-based decisions honoured by the backend, tail sampling at the collector, lazy loading the SDK.
  6. Export and safety: OTLP over HTTP to a proxied collector, no secrets in the client, CSP and CORS on the endpoint, scrubbing URLs and no personal data.
  7. Correlation: trace ids attached to RUM events and error reports.

Mentioning the CORS preflight unprompted is a strong signal. It is the detail that separates people who have rolled tracing out from people who have read about it. The BFF design question is a good place to practise, because a page calling nine services is exactly where a trace earns its keep.

Follow-up questions

Why do my backend spans not join the browser's trace?

Usually because the header never arrived. Check that the request is same-origin or matches propagateTraceHeaderCorsUrls, that the server's CORS response allows traceparent, and that the backend uses the W3C propagator rather than a vendor-specific one. If the header arrives but the trace is still empty, the backend may be making its own sampling decision instead of following the parent's sampled flag.

Why did adding tracing break requests to a third-party API?

The instrumentation added traceparent to a cross-origin request. That header is not CORS-safelisted, so the browser sent a preflight, the third party did not allow the header, and the browser blocked the request. Restrict propagateTraceHeaderCorsUrls to origins you control and whose CORS configuration you have updated.

How do you link the HTML page load to the server that rendered it?

The browser requests the document before your code runs, so it cannot add a header. The server writes its trace context into a <meta name="traceparent"> tag, and the document load instrumentation uses it as the parent of the browser's load spans. Do not let a CDN cache that per-request tag.

How would you choose a sampling rate?

Start from the budget and the questions. A low head-sampling rate in the browser, perhaps a few percent, gives representative latency data; parent-based sampling keeps traces whole; and tail sampling at the collector keeps every error and slow trace from the larger set it receives. Make sure backend services follow the browser's decision, or sampled browser traces arrive without server spans.

What personal data could end up in a trace, and how do you stop it?

Mostly URLs: query strings with emails or search terms and paths with user ids, recorded on every fetch span. Rewrite URL attributes in the instrumentation hooks, scrub again in the collector, never record headers or bodies, use pseudonymous session ids, and start the SDK only after consent where it is required.

Is tracing a replacement for RUM?

No. RUM measures how fast the site is across all users, as distributions of Web Vitals and custom timings. Tracing explains individual slow or failed operations across the frontend and backend. Use both, and attach trace ids to RUM events and error reports so one leads to the other.

Practise it

Each question opens in an editor with tests, so you can check your understanding by writing the code.

  1. Design frontend observability: errors, real-user metrics, source maps and samplingHard50 min
  2. Diagnose a failing CORS preflight and write the server's CORS handlerMedium35 min
  3. Design a backend-for-frontend (BFF) for a page that calls nine servicesHard45 min
  4. Implement a performance monitor measuring Web Vitals and reporting metricsMedium45 min
  5. Mask PII in log lines: Luhn-checked card numbers, emails, Indian mobile numbers and AadhaarEasy35 min
  6. Analyse a performance trace: find long tasks, compute Total Blocking Time and attribute it to scriptsMedium40 min