Most debugging attention goes to the response body. That is where the payload lives, where errors surface, and where your API client points by default. But a well-instrumented API often keeps a second, quieter copy of its telemetry in the response headers: a compact JSON object tucked into a custom field such as X-Rz-Debug. One line, no formatting, occasionally truncated, and easy to miss entirely. Once you know it is there, it answers which shard served this, did this come from cache, and what goes in a support ticket in seconds.
This guide covers where these header payloads come from, why they look the way they do, the extraction traps that silently corrupt them, and how to turn a one-line blob into readable, comparable JSON. Everything here uses fictional header names, so nothing below describes a specific vendor's implementation.
Why APIs stash JSON in response headers
The pattern is simple: the server serializes a small diagnostics object and emits it as the value of a custom response header.
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Rz-Debug: {"request_id":"rz-9f31c2a8","upstream_ms":142,"cache":"miss","shard":"eu-west-2c"}
X-Rz-Route: edge-fra2/app-14
{"order_id":9412,"status":"shipped","items":3}
Why put this data in a header instead of the body? Three practical reasons come up again and again.
First, it keeps the body contract clean. The body describes the resource; the header describes the request. If every response carried a request_id field, every schema would need optional wrapper fields and every version bump would risk breaking on telemetry nobody asked for. Headers are the natural side channel: clients that care can read them, clients that do not are unaffected.
Second, headers survive clients that mangle bodies. Interceptors and middleware routinely rewrite response bodies — injecting defaults, wrapping results in envelopes. Raw headers usually pass through untouched, making them a trustworthy record of what the server actually sent, and often the tiebreaker when a dispute arises about whether a field was dropped.
Third, it is cheap for support workflows. Asking a user to copy the value of one header in developer tools beats asking for a full HAR capture, and the request ID unlocks the server-side trace.
What typically lives inside these payloads? Request IDs and trace IDs, upstream timing, cache status (hit, miss, stale, bypass), the region or shard that handled the request, and sometimes rate-limit context. The same design philosophy shows up in error responses: when APIs want to convey machine-readable error details, they increasingly do it in the body with the Problem Details format, which we cover separately in Problem Details: Reading Structured API Errors. Debug headers complement that — errors explain what went wrong, debug headers explain how the request was processed.
The constraints that shape a header payload
Header values are not free-form text. HTTP field syntax, proxy behavior, and transport rules all constrain what a server can safely put in one, and those constraints explain almost every oddity you will see in a debug payload. (These are the rules that shape real-world values; the numbers below are typical figures, not guarantees — every proxy configures its own limits.)
The visible-ASCII rule is the big one. In practice, header values are expected to contain printable ASCII characters. That does not stop servers from sending raw UTF-8 bytes — many do, and most parsers tolerate it — but it means a careful API author will not put a Unicode arrow or an em dash into a header value. JSON that might contain non-ASCII strings gets escaped, so you will see \u00e9 instead of the actual character.
Line breaks are forbidden outright. A header value cannot contain CR or LF characters — that is not a convention but a hard rule of HTTP field syntax, enforced because header smuggling depends on injected line breaks. Consequently a debug payload must be serialized as a single line: no pretty-printing, no newlines between keys, no folded values in the style of old mail headers. Everything runs together, which is exactly why the raw value is so hard to read.
Whitespace is unreliable. HTTP explicitly allows optional whitespace around field values, and it is supposed to be trimmed. Trailing spaces after the last character of the value may or may not survive the trip, and spaces after commas inside the JSON depend entirely on how the server serialized it. You cannot rely on spacing to reconstruct anything; you must rely on the JSON grammar itself.
Size is bounded, loosely. There is no universal HTTP limit on a single header's length, but real infrastructure imposes its own: a common default for a total header section is around 8 KB in widely deployed proxies, with some defaulting closer to 4 KB per header, and application frameworks frequently impose their own smaller caps. When a debug payload grows — say it accumulates a list of retry attempts — it becomes a candidate for silent truncation, a failure mode handled in a dedicated section below.
| Header constraint | What it means | Consequence for a JSON payload |
|---|---|---|
| Visible ASCII expected | Non-ASCII characters should not appear raw in field values | Strings are \uXXXX-escaped; accented text and symbols arrive as escape sequences |
| No CR/LF in values | Line breaks cannot appear anywhere in a field value | The payload is one unbroken line; never pretty-printed by the server |
| Optional whitespace trimmed | Spaces around the value and between list items may be removed | Spacing after commas and colons is unpredictable; parse, do not split |
| Proxy size limits | Typical defaults land around 4–8 KB for a header or the whole header section | Long payloads may be silently cut mid-token, producing invalid JSON |
| Case-insensitive names | x-rz-debug and X-Rz-Debug name the same field |
Lookups must be case-insensitive; strict key matching misses the header |
| Repeated names allowed | The same field name may appear on multiple lines | Recipients fold the lines into one comma-joined value |
One more constraint interacts with JSON specifically: escaping. The slash-escaping question — whether / appears as \/ — catches people off guard when comparing header values against body values; see Forward Slash Escaping in JSON.
Extraction pitfalls: how a clean payload gets mangled
The header on the wire is well-formed JSON. The string in your clipboard, log file, or code editor frequently is not. Four mechanisms account for most of the damage.
Duplicate header names and comma-folding
HTTP allows the same field name to appear more than once in a response. When it does, most recipient implementations fold the separate lines into a single value joined with commas. A server that emits two debug blocks — say the edge layer adds its view and the application adds its own — arrives at your tooling as one value:
# What the server sent (two header lines):
X-Rz-Debug: {"request_id":"rz-9f31c2a8","cache":"miss"}
X-Rz-Debug: {"edge_pop":"fra2","tls_ms":11}
# What your client sees after folding (one value):
X-Rz-Debug: {"request_id":"rz-9f31c2a8","cache":"miss"}, {"edge_pop":"fra2","tls_ms":11}
That folded string is not valid JSON — it is two JSON documents separated by a comma-space, and JSON.parse rejects it without explaining why. The fix is to split on the first top-level }, and parse each segment separately; the tell is a closing brace followed by a comma and another opening brace. And never use a naive split(","), which will shred the object, because commas also occur inside it.
Case-insensitive names, case-sensitive code
HTTP field names are case-insensitive by specification: X-Rz-Debug, x-rz-debug, and X-RZ-DEBUG all name the same field. Servers and proxies take liberties with capitalization, and you should expect the same header to arrive in different casings across environments — staging behind one proxy, production behind another. Browser APIs handle this correctly: res.headers.get("x-rz-debug") matches regardless of how the server capitalized the name. Lower-level tooling varies. If you are parsing raw response text with a regex or a case-sensitive header map, a casing mismatch silently yields null while the header sits right there.
Proxies and intermediaries appending their own data
Intermediaries may add fields of their own, and some append to existing ones. A CDN might decorate the debug value with its node identity, or a gateway might join its telemetry onto your field:
X-Rz-Debug: {"request_id":"rz-9f31c2a8","cache":"miss"}, cdn-node=fra2, tier=gold
The trailing fragments are not JSON, and extraction code that assumes everything after the field name is a document will fail on a token in the middle of the string. When a value resists parsing, scan its tail first: content after the final closing brace is almost always an intermediary's contribution, and stripping it recovers the valid JSON prefix.
Copy-paste corruption
The most embarrassing mangling source is you. Terminal emulators wrap long lines visually; selecting the wrapped output can insert newline characters into the middle of the value. Rich text editors autocorrect straight quotes into smart quotes, which breaks JSON instantly. A trailing space pasted from a log viewer is invisible to a parser but not to a strict comparator. When a copied payload that parsed fine yesterday suddenly fails, diff it character by character against a fresh capture before you suspect the server.
Never retype a header value by hand and never let a word processor touch it. Capture it with a tool that writes raw bytes — curl -D headers.txt -o body.txt — and copy from that file. One smart-quote substitution or inserted line break costs more debugging time than the capture step saves.
Step-by-step extraction: from wire to readable JSON
With the pitfalls in mind, a reliable extraction workflow has four steps: capture raw, copy exactly, validate, format. None of them are optional.
Step 1: Capture the raw response
Use a tool that preserves the response verbatim. With curl, dump headers and body to separate files so you never have to parse them out of a mixed stream:
curl -s -D headers.txt -o body.txt https://api.example.test/orders/9412
# headers.txt now contains every response header, byte-for-byte:
# HTTP/2 200
# content-type: application/json; charset=utf-8
# x-rz-debug: {"request_id":"rz-9f31c2a8","upstream_ms":142,"cache":"miss","shard":"eu-west-2c"}
Browser developer tools also work, but beware of their copy button normalizing anything; the curl -D route is the reference.
Step 2: Copy the value exactly
Take everything after the first colon in the field line, minus exactly one leading space. Do not trim further, do not add anything. If you are scripting the extraction, a minimal approach looks like this in pseudocode, independent of any particular runtime:
# Pseudocode: read the debug header and format it
const res = await fetch("/api/orders/9412");
// Field names are case-insensitive; lowercase works everywhere.
const raw = res.headers.get("x-rz-debug");
if (raw === null) {
// Absent, or blocked by CORS: custom response headers are invisible
// to cross-origin JavaScript unless the server exposes them via
// Access-Control-Expose-Headers. This is a server config issue,
// not a parsing bug.
console.warn("X-Rz-Debug not visible");
} else {
try {
const debug = JSON.parse(raw);
console.log(debug.request_id, debug.upstream_ms, debug.cache);
} catch (err) {
console.warn("Not valid JSON — check for folding, truncation, or appends:", err.message);
}
}
The CORS note in that pseudocode is worth expanding: in a browser, JavaScript cannot read custom response headers on cross-origin requests unless the server lists them in Access-Control-Expose-Headers. If the header shows up in the Network tab but headers.get() returns null from page code, that is the cause. It is the most common report of a "missing" debug header — the header was never missing, merely hidden.
Step 3: Validate before you trust
Run the copied string through a JSON validator before doing anything else with it. Validation catches every corruption mode from the previous section: folding produces "unexpected token," truncation produces "unexpected end of input," smart quotes produce "unexpected character." Validation takes one second and turns "why is my script crashing" into a specific, fixable complaint.
Step 4: Format for reading
Once validated, pretty-print the object. The server could not give you line breaks, so you add them:
{
"request_id": "rz-9f31c2a8",
"upstream_ms": 142,
"cache": "miss",
"shard": "eu-west-2c"
}
Formatting is where non-ASCII escapes become readable: \u00e9 renders back into the actual character in a good formatter. This is also the moment to check that numbers survived as numbers — upstream_ms should be a numeric 142, not the string "142", and you want to know that before writing comparisons.
Comparing the header copy against the body copy
Many APIs expose overlapping information in both places: the debug header carries a flat, compact summary, while the body (or a separate status object) carries a nested, verbose version. These two copies rarely agree on structure, and sometimes they disagree on substance. Comparing them structurally — key by key, type by type — is more useful than eyeballing both.
Suppose the same request surfaces these two representations:
// Header copy (X-Rz-Debug, formatted):
{
"request_id": "rz-9f31c2a8",
"upstream_ms": 142,
"cache": "miss"
}
// Body copy (inside a status object, formatted):
{
"request": { "id": "rz-9f31c2a8" },
"timing": { "upstream_ms": 142 },
"cache": "MISS"
}
Three classes of difference appear, and each means something different. Structural differences — flat request_id versus nested request.id — are cosmetic and expected; the two producers simply serialize differently. Casing differences — miss versus MISS — are semantically neutral if the field is an enumeration, but they will break naive string equality in tests, which is a frequent source of flaky integration suites. Substantive differences — different request IDs, different timings — are the interesting ones, because they usually mean the two values were captured at different pipeline stages: the header reflects the moment the response left the app server, the body a later reconciliation. A structural diff is the right tool: flatten both documents, align the keys, and let it show only what actually differs.
Recognizing and handling a truncated payload
Truncation is the failure mode that least announces itself. A size-limited intermediary cuts the value at some byte boundary and forwards the rest without ceremony. The symptom at your end is a validation error: "unexpected end of JSON input." The diagnostic signature is recognizable on sight:
X-Rz-Debug: {"request_id":"rz-9f31c2a8","upstream_ms":142,"cache":"mi
Three checks identify truncation reliably. First, brace balance: count opening and closing braces — a truncated object ends without its closing brace. Second, quote parity: a cut inside a string value leaves an odd number of quote characters. Third, the tail: valid JSON never ends mid-word like "mi — it ends in a complete value, a comma, or a closing bracket. If any check fails and the value otherwise looks healthy, assume it was cut at a size boundary.
There is no way to recover bytes that never reached you, but the surviving keys are intact and informative: a payload large enough to hit a limit suggests the server is appending something that grows over a request's lifetime, such as retry attempts. The remedy is server-side — shorten the payload, move verbose parts to a lookup endpoint keyed by request_id, or raise the limit. When reporting upstream, include the capture verbatim; the byte count tells the server team roughly where their limit sits.
Truncation is silent by design: every intermediary between you and the server may apply its own limit, and none of them are obligated to tell you. If a debug header parses correctly in staging but fails in production, compare the byte lengths of both captures before debugging anything else — a size limit difference between environments is a one-line finding.
Debug only: never trust headers for application logic
The final rule is the one that saves the most pain. Everything in a debug header is a courtesy, not a contract, and your application code should never depend on it. The reasons are structural, not stylistic.
Headers are modifiable by every intermediary on the path, and custom fields especially so — proxies rewrite, append, and drop headers as a matter of course, and nothing in a debug payload is signed. There is no guarantee that the upstream_ms you received is the one the application server measured. Headers can also disappear: a caching layer may serve a stored response with stale or stripped debug fields, and browsers may hide them from page code unless CORS exposes them.
Availability is the other half of the argument. Debug payloads are the first thing cut when a team needs to shave response size, the first thing disabled under load, and entirely absent from responses served by some CDNs. Code that treats X-Rz-Debug as a data source will work in every test environment and then fail — quietly, since it reads a header, not loudly — in production traffic routed through a different intermediary.
The correct posture: application logic reads the body, which is versioned and documented. Debug headers are for humans during development and for support tickets. If you need machine-readable request metadata in application code, ask the API team to expose it in the body or a documented header with a stability guarantee — and for error details specifically, the body is where they belong anyway, per the Problem Details convention covered in Problem Details: Reading Structured API Errors.
Building URLs from debug data? Mind your encoding
A common follow-up: the header gives you a request_id and you build a trace URL like /traces?request_id=rz-9f31c2a8 with it. IDs are usually URL-safe, but any other header-derived string — a shard name, a deprecation message — needs correct component encoding. The distinction between encoding a full URI and a single component is covered in encodeURI vs encodeURIComponent; the short version: query values always get the component-level encoder.
Test it yourself
The whole workflow is easy to reproduce: capture a header and paste it into the JSON Inspector to validate and format it, then paste the header copy and body copy into JSON Compare to see structural differences key by key. Both tools run entirely in your browser — which matters, because debug headers routinely carry request IDs tied to real customer traffic.
Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.