Every developer who builds a webhook receiver eventually meets the same baffling failure. The event arrives, the log line looks perfect, the payload parses cleanly into a well-formed object — and the signature check rejects it anyway. The provider's dashboard insists the delivery is genuine; your verification code insists it is not. After an hour of diffing strings, you discover that nothing about the values is wrong. What is wrong is the bytes — and the culprit was a JSON formatter you ran ten minutes before the test.
This guide explains that failure: why HMAC-style webhook signatures are computed over the exact bytes of the request body, why parsing a payload and writing it back out produces different bytes even when the data is identical, and how to arrange your verification and testing workflow so that readability never has to compete with security.
How webhook signatures actually work
Most webhook providers authenticate deliveries with a keyed hash. When an event fires, the provider takes the request body — the literal sequence of bytes it is about to transmit — computes an HMAC over those bytes using a shared secret, and attaches the result to the request in a header. That header may carry a plain digest or a structured value such as a timestamp paired with a digest; the provider's documentation is the only reliable source for which, and the signed input may be the body alone or that timestamp-body concatenation.
Verification on your side mirrors the process exactly. You recompute the HMAC over the same input using the same secret and compare your result to the delivered signature. If the two strings match, you can conclude that the body was produced by someone holding the secret — which, in practice, means the provider — and that the bytes were not altered in transit.
The crucial property of an HMAC, and the property that causes every failure described in this guide, is that it is a function of bytes, not of meaning. Two byte sequences that differ in any position produce completely different digests. There is no fuzzy comparison, no tolerance for cosmetic variation, no notion of "these two payloads are semantically the same." A single flipped bit anywhere in the input changes roughly half of the output bits. Cryptographers call this the avalanche effect; webhook developers usually learn its name at two in the morning while debugging a signature mismatch that "should not be possible."
So the question "why did my signature check fail?" always reduces to one question: are the bytes you hashed byte-for-byte identical to the bytes the provider signed? Formatting breaks verification precisely because the answer becomes "no" even though the data itself is untouched.
A fair question follows: why do providers sign raw bytes instead of a canonical form that would survive formatting? Because canonicalization is genuinely hard. JSON offers many valid encodings for the same value, and agreeing on one deterministic rendering across languages, number formats, and Unicode forms is a specification project of its own. Signing the raw bytes is simple and auditable; the cost of that simplicity is inherited by receivers, and the cost is this guide.
Parsing and re-serializing always changes bytes
To see where the bytes diverge, look at a payload exactly as it arrives on the wire. Providers emit compact JSON: no indentation, no spaces around delimiters, keys in whatever order their serializer happened to emit them.
{"id":"evt_51902","amount":1000,"live":false,"note":"ok"}
Now run that payload through a typical JSON formatter — the kind built into editors, browser developer tools, log viewers, and API dashboards. The formatter parses the text into a value, then writes that value back out as text, applying its own conventions along the way:
{
"amount": 1000,
"id": "evt_51902",
"live": false,
"note": "ok"
}
Read as data, the two documents are identical. Every parser that consumes either one produces the same in-memory object with the same fields and the same values. Read as bytes, they share almost nothing. The key order changed. Whitespace was inserted after every colon and comma. The closing brace moved to its own line. Those differences are invisible to a JSON parser and decisive to an HMAC.
Whitespace and key order are only the most visible rewrites. A formatter or serializer can alter a document in subtler ways while preserving the value exactly:
- Number tokens. The value one thousand can be written as
1000,1e3,1.0e3, or10.00e2. JSON permits any of them, they are different byte sequences, and serializers normalize freely. A formatter that prints1e3as1000has preserved the value and destroyed the bytes. - String escaping. A forward slash may appear as
/or as the escape sequence\/; both denote the same character. Many serializers escape slashes defensively — Go's default encoder is a well-known example — and control characters can likewise be written as short escapes or as numeric escape sequences, all denoting the same value with different bytes. - Unicode normalization. The character é can be encoded as a single precomposed code point or as the letter e followed by a combining acute accent. The two forms are visually indistinguishable and numerically different. A tool that applies Unicode normalization changes the string's bytes without changing how it looks on screen.
- Trailing bytes. A newline after the closing brace is common in files and log output and absent from most wire payloads. One extra byte is enough to invalidate every bit of the signature.
The differences become stark when you inspect the bytes directly. Here are the first bytes of the compact original and the formatted version, shown as hexadecimal:
raw: 7b 22 69 64 22 3a 22 65 76 74 5f 35 31 39 30 32
22 2c 22 61 6d 6f 75 6e 74 22 3a 31 30 30 30 ...
formatted: 7b 0a 20 20 22 61 6d 6f 75 6e 74 22 3a 20 31 30
30 30 2c 0a 20 20 22 69 64 22 3a 20 22 65 76 74 ...
The very second byte already differs, and the avalanche effect takes over from there: the two HMAC outputs are effectively independent strings that will never match.
| Transformation | Value changed? | Bytes changed? | Signature survives? |
|---|---|---|---|
| Pretty-printing (indentation, newlines) | No | Yes | No |
| Reordering object keys | No | Yes | No |
Printing 1e3 as 1000 | No | Yes | No |
Unescaping \/ back to / | No | Yes | No |
| Applying Unicode normalization | No | Yes | No |
| Dropping a trailing newline | No | Yes | No |
Editing a value (1000 to 1001) | Yes | Yes | No |
Every row except the last is a transformation a formatter performs routinely, without prompting and without warning. The last row is the one failure the signature was designed to catch: an actual change of data. The irony of formatting is that it fails verification exactly the way an attacker would, while sharing none of the attacker's intent.
The classic failure story: replay testing with a formatted payload
Here is how the failure unfolds, more often than any provider's documentation warns.
A developer is building or debugging a webhook receiver. An event fires in the provider's production or sandbox environment. To inspect it, the developer copies the payload from a delivery log, a dashboard, or an application log line — and because the raw payload is a dense single line of text, the developer does the natural thing: pastes it into a JSON formatter to make it readable. Perhaps they also save the formatted output to a file called payload.json, intending to replay the event against a local receiver and step through the handler in a debugger.
The replay usually looks something like this:
curl -X POST https://localhost:8080/webhooks \
-H "Content-Type: application/json" \
-H "X-Signature: t=1762425600,v1=5f8ac21b..." \
--data @payload.json
The receiver parses the body without complaint — the formatted file is perfectly valid JSON. Then the signature check runs. The receiver computes an HMAC over the pretty-printed file, compares it to the delivered signature, which was computed over the compact original, and the two have nothing in common. The request is rejected with a 400. The developer spends the next hour comparing values field by field, finding them identical, and concluding that the signature library is broken. It is not. The provider signed one byte sequence; the replay delivered a different one.
The same failure arrives by other routes that never involve a formatter directly. A middleware layer logs the body after a framework has already parsed and re-serialized it. A load balancer or API gateway normalizes whitespace in transit. An integration test reconstructs the payload from a fixture object instead of the captured raw text. In every case the value survives and the bytes do not — and the signature, doing precisely its job, notices.
Rule of thumb: if a payload has been made more comfortable for a human to read, it is no longer the payload the provider signed. Keep the raw bytes; format a copy.
The wrong fix: verifying a re-serialized body
Faced with the mismatch, some developers reach for an intuitive but dangerous fix: compute the signature over whatever their own code produces. Parse the body, re-serialize it, hash the result, compare. It feels principled — the signature now consistently covers the bytes the receiver actually processes, and the test suite goes green.
It verifies nothing. The entire point of the scheme is that the provider, holding the secret, produced the bytes; your recomputation over the delivered bytes proves that someone with the secret sent them. If you hash your own re-serialization instead, you are signing a value the sender supplied, using whatever rendering your serializer chooses. An attacker needs to intercept nothing at all: they forge a payload, choose any formatting they like — including one that matches your serializer's output exactly — and the "verification" accepts it. Meanwhile, honest traffic formatted differently from your serializer's choices still gets rejected. The broken pattern manages to deliver false rejections for legitimate events and zero resistance to forged ones at the same time.
A related dead end is canonicalization. Some developers attempt to canonicalize both sides — parse the delivered body, render it in a canonical JSON form, and sign that. The result is still wrong: the provider signed its own bytes, not your canonical rendering, and no local scheme can reproduce a hash over input you never saw. Canonical JSON formats are useful for signing documents you author yourself; they cannot reconstruct a signature computed by someone else over different bytes.
The correct pattern: verify raw bytes, then parse
The sound pattern inverts the order of operations. The raw bytes must reach your verification code untouched, and parsing happens only after the signature has been validated:
function handleWebhook(rawBytes, deliveredSignature, secret) {
// 1. Sign NOTHING but the delivered bytes.
// rawBytes is the exact request body as received:
// not parsed, not re-serialized, not trimmed,
// not "normalized" by any middleware.
computed = hex(hmacSha256(secret, rawBytes))
// 2. Compare against the delivered signature in
// constant time, so response timing does not
// leak how many leading hex digits matched.
if (!constantTimeEquals(computed, deliveredSignature)) {
return reject(400, "signature mismatch")
}
// 3. Only after verification succeeds, build the value.
// From this point on, formatting is free.
event = jsonParse(utf8Decode(rawBytes))
return process(event)
}
The practical difficulty is rarely the cryptography; it is the plumbing. Most web frameworks parse JSON bodies eagerly and hand your handler a decoded object, so the raw bytes are gone before you can hash them. Every framework has an escape hatch — a raw-body reader, a stream interface, a middleware ordering option — and it is worth locating on the first day of the project rather than during an incident. If the scheme signs a timestamp concatenated with the body, that timestamp must come from the delivery header and be concatenated with the raw bytes exactly as specified, with no re-encoding in between, because the concatenated string is itself a byte sequence subject to the same rules.
A replay and testing workflow that works
Nothing about signature verification forces you to work with unreadable payloads. It only requires that the readable version never impersonate the original:
- Capture raw, at the edge. Save the request body to a file before any parsing occurs — in a logging middleware that runs before body parsers, or in a local reverse proxy in front of your receiver. That file is the ground truth for everything that follows.
- Verify first, then format. Run signature verification against the raw capture. Once it passes, produce a formatted copy in a separate file for reading. Never overwrite the original, and never feed the formatted copy back into anything that checks signatures.
- Replay with byte fidelity. When replaying, send the original file, not a reformatted one. With curl,
--data-binary @payload.rawsends the file's bytes without processing; the plain-dflag may strip or translate newlines and quietly mangle the body you meant to send. - Recompute for local harnesses. If your own test environment verifies signatures, sign the same bytes you send: compute the HMAC over the exact file you are posting and put that fresh signature in the header. The provider's original signature covers the provider's bytes, and it will not transfer to your harness unless the bytes are identical.
Teams that adopt this workflow gain a side benefit beyond passing tests: the raw capture doubles as an exact record for reproducing bugs, because the bytes that failed verification are the bytes sitting on disk. When you attach evidence to an incident review, you are attaching the artifact, not a paraphrase of it.
The text layer and the value layer
The principle underneath all of this is that a JSON document exists on two layers at once. There is the value layer: the abstract data — objects, arrays, strings, numbers — that parsers produce and that comparison tools reason about. And there is the text layer: the specific sequence of bytes that encodes that value on the wire. Countless formatting decisions — key order, whitespace, number spelling, slash escaping, Unicode composition — move freely between equivalent texts of the same value, and every one of them rewrites the text layer while leaving the value layer untouched.
Different tools operate on different layers, and choosing the right tool for the question you are actually asking prevents most JSON disputes. Comparators and inspectors work at the value layer, which is what you want when the question is "is this the same data?" Signatures, checksums, and hashes work at the text layer, which is what you want when the question is "did these exact bytes come from the expected source?" Confusing the two questions is what turns an innocent formatter into a security incident.
This same split explains several behaviors covered in other field notes. Escape sequences such as \/ are a text-layer choice that some serializers make for defensive reasons; see why JSON escapes forward slashes for the full story. Array order, by contrast, is meaningful at the value layer — reversing an array changes the data itself, a fundamentally different situation from reordering object keys, which changes only the text; formatting and array order covers when order carries meaning. And when a provider does reject your request, the error body it returns is itself JSON travelling through the same machinery; reading structured error responses shows how to extract the failure details instead of squinting at a status code.
A debugging checklist for signature mismatches
When a signature check fails, work through these questions in order. Most mismatches are fully resolved by step two.
- Confirm exactly which bytes were signed. Read the provider's specification and determine the signed input: the body alone, a timestamp and body concatenated with a separator, or a selected subset of headers. Replicating the wrong input is the most common cause of permanent, correct-looking failures — the code is impeccable, and it is hashing the wrong thing.
- Compare raw text byte-for-byte, not values. Capture the bytes your code actually hashed and compare them against the bytes the provider says it signed. A hex dump of both sides makes every invisible difference visible. Byte equality is the pass/fail line; if the bytes match, the signature will too.
- Check for transport mangling. Proxies, API gateways, web application firewalls, and compression layers can rewrite whitespace, re-encode character sets, decompress bodies, or rebuild the request before it reaches your code. Verify what arrives at your handler, not what the provider claims to have sent.
- Check for framework-level re-serialization. Trace the body's path through your middleware chain. If anything parsed and re-serialized it before verification ran, the original bytes are unrecoverable at that point; move verification earlier, ideally to the first handler that touches the request.
- Rule out time skew last. If the scheme signs a timestamp and enforces a tolerance window, an old replay can fail even with perfect byte fidelity. This failure mode is real but distinct: establish byte equality first, then look at clocks. Debugging them in the wrong order wastes hours.
One habit makes every step of this checklist cheaper: log the raw body and the delivered signature header together, before anything processes either. When a mismatch appears days later, you will have the exact evidence instead of a memory of what should have arrived.
Test it yourself
You can watch the two layers disagree with your own tools. Take any webhook payload and open it in the JSON Inspector: it will parse cleanly, because parsing is exactly the operation that discards the text layer. Then paste the compact wire version and a pretty-printed version into JSON Compare. The comparator will report that there are no differences — and it is right. As values, the two documents are identical. Yet an HMAC computed over each text would produce entirely different signatures. That contrast is the point. The comparator answers "is this the same data?" with yes; the signature answers "is this the same bytes?" with no. Both tools are correct, and knowing which question you are asking is the whole discipline.
Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.