What you'll learn: By the end of this lesson you will be able to say which ids a page should create (session, page view, trace, span) and for what, write client log lines that carry them, build and read a W3C
traceparentheader, explain why a trace id sent by a page is input and not truth, find the three places where a page-to-server join silently breaks (no header, a blocked header, an invalid header), and keep client logs from leaking secrets or flooding the network.
Picture a hospital wristband. Reception prints one number, and every department that touches the patient writes it on its notes. Without it, three departments hold three sets of notes and nobody can tell they describe one person. A correlation id is that wristband for a user action: the page creates it, every log line carries it, and every request forwards it, so one search shows the whole story.
The running example is a checkout button. The visitor presses "Pay", the page calls an API, the API calls a payment service, which fails once, and the page retries. When the visitor says "it said error at 14:02", can support see the page's lines and the services' lines side by side? The server side is in Correlation IDs and Trace Context Across Services; this lesson is the start of the chain, the page.
The core idea
- The page is where a user action begins, so the page creates the trace id. One id per action (a click, a page load, a form submit), made when the action starts and used for everything it triggers.
- Every client log line carries the ids, and every outgoing request forwards them. The id is worth nothing if it is on the lines but not on the requests, or the other way round.
- An id from a browser is input, not evidence. Anyone can send any header. Servers validate it, restart the trace when it is invalid, and never trust it for authorization.
Three illustrations run through the lesson: a minimal example (one action, one request, lines on both sides), a realistic example (the checkout with a retry) and a failure example (the join that finds nothing).
Four ids, four jobs
| Id | Created | Lives for | Answers |
|---|---|---|---|
| Session id | When a visit starts | The visit | "What else did this visitor do?" |
| Page-view id | On each page load or navigation | One page view | "Which load of the app was this?" |
| Trace id | At the start of a user action | One action and everything it causes | "Which lines belong to this action?" |
| Span id | For each unit of work (a request, a render) | One unit | "Which step, and who called it?" |
Session and page-view ids are in the log context from the start; the trace id changes with every action; the span id is new for every request. The W3C Trace Context Recommendation fixes the last two: a trace id is 16 bytes (32 lowercase hex characters), a span id (the header calls it the parent-id) is 8 bytes (16 hex characters), and all-zero values are invalid. It also says the random generator behind them must not rely on anything that can identify the user, and the ids must not carry personal data. A real page can use crypto.getRandomValues, which MDN describes as cryptographically strong; the lab uses a seeded generator only to make its output repeatable.
Figure 1. One action, one trace id, from the page to the log store
How to read this: the solid arrows carry the request and the header, the flowing dashes carry log lines. Both kinds of line arrive at the same store carrying the same trace id, and that match is what makes one search show the whole action.
Client log lines with context
A client log line is a record: a level, a message, the context (release, session, page view and, during an action, the trace id) and a few fields. The lab's logger adds the context to every record, and a finished action removes the trace id so later lines are not blamed on it.
Four rules keep client logging safe and cheap, because logs leave the visitor's device.
- Redact by field name, and do not trust it for free text. The logger replaces the value of
authorization,cookie,password,tokenandemailat any depth. OWASP's Logging Cheat Sheet lists access tokens, passwords and session identification values among data that usually should not be logged directly, and suggests removing, masking, hashing or encrypting them. A key-based filter cannot find a token pasted into a message, which the lab shows on purpose. Scrub URLs too: a callback address can carry a code in its query string. - Cap sizes. OWASP advises limiting the size of user input used in a log message, and preferring structured formats such as JSON.
- Sample by level. Keep errors and warnings; sample or drop debug lines.
- Bound the buffer. When it is full the lab drops the oldest record and counts it: unbounded memory in a visitor's tab is worse than a gap in the logs.
Records then leave in batches under a size limit. MDN says navigator.sendBeacon() queues a small amount of data (up to 64 KiB in total), returns true if the browser queued it, and that the most reliable moment to send final data is visibilitychange with the document hidden, because unload, beforeunload and pagehide are not reliably fired, especially on mobile. The lab's flush takes the transport as a function returning true or false and keeps what a refused transport did not take. OWASP also treats data from client software as untrusted event data: the collector validates and bounds it.
The traceparent header
W3C Trace Context Level 1, a Recommendation dated 23 November 2021, defines traceparent as four fields joined by dashes:
00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
version - trace-id (32 hex) - parent-id (16 hex) - trace-flags (2 hex)
The version is 00 and ff is invalid; hex is lowercase. Only one flag is defined, the right-most bit, sampled: when set, the caller may have recorded trace data. The header name should be sent in lowercase and receivers must accept any case.
The page puts its own span id in parent-id: "the request I am making is the parent of whatever you do next". The service keeps the trace id, makes a new span id for its own work and passes that on. A service that gets a header it cannot use (a bad version, an invalid trace id, parent id or flags) creates a new traceparent and discards tracestate: the trace restarts. The Recommendation also says vendors must assess the risk of header abuse, which is why a page's id groups lines and never proves identity.
Figure 2. One action with a failed attempt and a retry
How to read this: the trace id says "same action" and the span id says "which attempt". A retry that reused the span id would merge two attempts into one step; a retry that made a new trace id would split one action into two.
Where the join breaks
A trace that does not connect is worse than none, because people trust a search that returns nothing. Three places fail quietly.
- The header was never sent. The destination is another origin and the page's HTTP client forwards trace headers only to an allow-list. The service starts its own trace. OpenTelemetry's browser documentation configures this separately from exporter CORS, with
propagateTraceHeaderCorsUrlson the fetch instrumentation. - The browser blocked the request. MDN says a cross-origin request is "simple" only when the headers set by hand are all CORS-safelisted (
Accept,Accept-Language,Content-Language,Content-Typewith limited values,Range).traceparentis not on that list, so it triggers a preflight, and the server must list it inAccess-Control-Allow-Headersor the browser refuses the real request. The page sees a network error; the server sees nothing. See CORS Preflight, Credentials and Debugging. - The header was invalid. An uppercase hex, a zero trace id or a truncated value restarts the trace on the server: lines exist on both sides, under different ids.
Figure 3. Should this request carry the header?
the page?"} -->|"yes"| S["Send traceparent"] Q -->|"no"| L{"On the propagation
list?"} L -->|"no"| N["No header: the server
starts its own trace"] L -->|"yes"| A{"Server allows the
header in preflight?"} A -->|"yes"| S A -->|"no"| B["Browser blocks the request:
page error, no server line"]
How to read this: only the path on the right ends in a joined trace. Every other path loses the join, and two of them lose it without a visible error.
Retries follow the rule in Figure 2: reuse the trace id, change the span id. Their mechanics are in Request Cancellation, Retries and Timeouts.
Build it: ids, logs, headers and the join
Goal. Run a model of a page, a network and two services through six situations: one action across two systems, a retry, a destination not on the propagation list, a blocked request, a table of traceparent values and the logger's hygiene rules.
Setup. The lab is in the course's example workspace (Node 26.13.1). It is pure logic: no browser, no DOM.
cd examples/frontend
pnpm install
cd labs/correlation-ids-client
pnpm test # 31 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare the output below.
- In section 1, the
parent=on theweblines equals thespan=on the page'sresponseline. That equality is the join. - In section 3, the page has lines under the trace id, the server has none, and the server's own line says why.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; scenarios 1 and 2):
=== 1. One user action, one trace id, lines from the page and the service
trace id: fef5bb3a6f0adb82310ef5a1c6858dec
status: 200
t= 1 page info action started
t= 2 web GET /api/cart/items: continued trace span=22c38aa4 parent=69f16094
t= 3 web done, answering 200 span=22c38aa4 parent=69f16094
t= 4 page info response 200 span=69f16094 attempt=1
=== 2. A retry: same trace id, a new span id for each attempt
final status: 200, preflights: 2
t= 1 page info action started
t= 2 api GET /orders: continued trace span=20f6387e parent=1f7c7ad1
t= 3 api upstream unavailable, answering 503 span=20f6387e parent=1f7c7ad1
t= 4 page warn response 503 span=1f7c7ad1 attempt=1
t= 5 api GET /orders: continued trace span=461b32ab parent=97a3ba39
t= 6 api done, answering 200 span=461b32ab parent=97a3ba39
t= 7 page info response 200 span=97a3ba39 attempt=2
Expected output, captured from a real run (the same run; scenarios 3 and 4):
=== 3. A cross-origin API that is not on the propagation list: the join finds nothing on the server
page lines with the trace id: 2
server lines with the trace id: 0
the server started its own trace: eac97a88 (page trace 6a5ab992)
server line: GET /orders: new trace (traceparent missing)
=== 4. A cross-origin API on the list that does not allow the header: the browser blocks the request
status: 0, preflights: 1, server lines: 0
t= 1 page info action started
t= 2 page error request failed: blocked by CORS: header not allowed: traceparent span=bc87a5bd attempt=1
Expected output, captured from a real run (the same run; scenarios 5 and 6):
=== 5. What a service does with each traceparent it might receive
valid, sampled -> continue trace 4bf92f35, sampled=true
valid, not sampled -> continue trace 4bf92f35, sampled=false
missing -> start a new trace (missing)
uppercase hex -> start a new trace (format)
trace id all zero -> start a new trace (trace-id-zero)
version ff -> start a new trace (version-ff)
too few fields -> start a new trace (format)
=== 6. Log hygiene: redaction, truncation, sampling, a bounded buffer, batches
fields after redaction: {"user":{"id":7,"email":"[redacted]"},"Authorization":"[redacted]"}
message after cap: the token abc123 pasted into free text i...[truncated]
url after scrub: https://shop.example/cb?code=1&token=x
debug at rate 0.25: kept 4 of 20, sampled out 16
buffer (max 5): 5 held, 1 dropped for space
flush: sent 5 records, batches: 2 (sizes 230, 124), kept 0
flush refused: sent 0, kept 1 for the next try
What the lab does not show. No browser: it never calls fetch, sendBeacon or crypto.getRandomValues, and its network applies one CORS rule only (a non-safelisted header needs a preflight and an allow-list entry); the preflight cache, credentials and proxies are ignored. Only version 00 is parsed. The sizes and the sampling rate in section 6 are made up for the demo.
Break it. In test/correlation.test.ts, the test "a cross-origin API that is not on the propagation list starts its own trace" builds the world with propagateTo: []. Change it to propagateTo: [API] and it fails, because the server now continues the page's trace. Change it back.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| One trace id per user action | Support finds everything one action caused | Long sessions need a session id too |
| Send the header to every origin | Fewest joins lost | Preflights, blocked requests, and ids exposed to third parties |
| Send it to an allow-list | Predictable preflights and no leaks to third parties | The list must be kept in step with the services |
| Sample debug lines, keep errors | Cheaper, still shows failures | A sampled-out line cannot be recovered |
Figure 4. From a log call to the log store
How to read this: each box can remove or refuse something. Redaction and the cap change a record, sampling removes it, a full buffer drops the oldest, and a refused send keeps the batch for the next try.
In practice: a payment error nobody could trace
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop's checkout page calls api.shop.example, a different origin. Support gets tickets like "Pay failed, 14:02". Engineers can find the page's error lines by session id and the payment service's logs by time, but cannot match them: two hundred payments happened that minute (illustrative).
Starting architecture
Figure 5. Starting point: ids on the page, none on the wire
How to read this: each system can be searched, but the page and the API do not share an id, so the first hop is a guess.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Send traceparent to the API origin and log the trace id on the page |
The whole action is searchable from the first hop | A preflight on every cross-origin call; the API must allow the header; the trace id must be on every line | Misconfigured CORS blocks checkout |
The decision
| Field | Decision record |
|---|---|
| Context | Support cannot connect page errors to server errors for cross-origin API calls. |
| Decision | Create a trace id per user action, add it to the logger context, send traceparent to the API origin only (an allow-list of one), and show the trace id on the error screen. |
| Consequences, good | One search shows an action from the click to the payment service; a support ticket can quote the id. |
| Consequences, bad | Every cross-origin call now needs a preflight; the list of origins must be maintained. |
| Revisit when | More origins need the header, or a sampling decision must be passed on (the sampled flag). |
Rollout and verification
- Allow the header on the server first, and check the preflight answer in staging before any page sends it.
- Ship the page change behind a flag for a small share of visitors, watching the checkout error rate.
- Verify the join: one test checkout, then search its trace id; lines must come from the page, the API and the payment service.
The 2 a.m. failure
Soon after the change reaches everyone, checkout errors jump from a handful to a large share of attempts (illustrative). The page logs request failed with no status, and the API logs nothing, because the browser blocked the requests. The cause is a second API host, used by one region, whose gateway does not list traceparent as an allowed header.
First three checks: (1) look at the browser's network panel for a failed preflight on one failing request; (2) compare the Access-Control-Allow-Headers answer of a failing host with a working one; (3) check which hosts the propagation list names. Mitigation: turn the flag off, which stops sending the header and restores checkout at once. Follow-up: add the header to every gateway, test each API host for it in release checks, and alert on a rise in page-side request failed lines that have no server line.
Architect's notes
- Make the first hop visible. Test the page-to-first-service hop first.
- Treat a trace id from a page as untrusted. Validate it, bound it, never use it for access decisions.
- Redact in code, not by hope, and do not log request bodies by default.
- Count what you drop, so the logger's own failures show.
Common mistakes
- One id for the whole visit, so a session cannot be narrowed to one action.
- Reusing the span id on a retry, which merges two attempts.
- Sending the header everywhere, then meeting preflights and blocked requests.
- Logging full URLs and bodies, which carry tokens and personal data.
- Flushing on
unload; usevisibilitychange.
Key takeaways
- The page creates the trace id for a user action, logs it, and forwards it.
- A
traceparentheader is00-<32 hex trace id>-<16 hex parent id>-<flags>; invalid values make a service start a new trace. - A retry keeps the trace id and gets a new span id.
traceparentis not CORS-safelisted: a cross-origin call needs a preflight and an allow-list entry on the server.- Client logs need redaction, size caps, sampling and a bounded buffer; send them in batches, on
visibilitychange. - Treat every client-sent id and log line as untrusted input.
Practice exercises
Exercise 1 — Starter (45 min): Find a cross-origin API call in an app you know. List the headers it sends, and say which would trigger a preflight and which would not.
Exercise 2 — Intermediate (2 hours): In the lab, add a x-session-id field to the log context and make a test that a record written between two actions has the session id but no trace id.
Exercise 3 — Advanced (half day): Implement the Recommendation's rule for reading a version higher than 00 in parseTraceparent, add fixtures for a long header and a short one, and say what the server should log in each case.
Related reading
In this course:
- Correlation IDs and Trace Context Across Services, the server side of the same header.
- Observability with Micrometer, Prometheus and OpenTelemetry, the back-end stack that stores the lines.
- Real User Monitoring, the page-side data that is not logs.
- CORS Preflight, Credentials and Debugging, why a new header costs a preflight.
- Request Cancellation, Retries and Timeouts, what a retry does to ids.
Official documentation
- W3C Trace Context, Level 1 Recommendation of 23 November 2021: the
traceparentformat, processing and privacy sections. - MDN: Cross-Origin Resource Sharing, simple requests, safelisted headers and preflight.
- MDN: Navigator.sendBeacon(), queued size and
visibilitychange. - MDN: Crypto.getRandomValues(), cryptographically strong random values.
- OWASP Logging Cheat Sheet, data to exclude, sanitising and untrusted event data.
- OpenTelemetry: Web (client apps), trace header propagation configured separately from exporter CORS.