research/verifying-a-webhook-signature-with-hmac
Verifying a Webhook Signature With HMAC: The Raw-Body Mistake and a Timing-Safe Compare
Engineering Note · November 24, 2026 · 9 minute read · Node.js · Webhooks · Security · Testing
To verify a webhook signature with HMAC, compute the HMAC over the exact bytes of the request body you received, before you parse it, and compare the result with crypto.timingSafeEqual after checking the two are the same length. The common mistake is to parse the JSON first and sign JSON.stringify(body): we sent eight valid JSON bodies through that round trip and seven came out as different bytes, so their signatures failed. The one that survived was compact, plain-ASCII JSON, exactly the kind a quick local test sends, which is how this bug reaches production. A timestamp inside the signature and a record of processed event IDs handle replays and retries.
Everything below was run on Linux with Node.js 22.23.5, using node:crypto, node:http and the built-in fetch. No packages were installed. The outputs are the real ones from these runs.
What is a webhook signature?
A webhook is an HTTP request another service sends you when something happens: a payment succeeded, a booking was made. Your endpoint is public, so anyone can send it a request that looks like one. A signature proves the request came from the service and was not changed on the way.
With HMAC (a hash-based message authentication code), you and the sender share a secret. The sender computes HMAC-SHA256 over the message using that secret and puts the result in a header. You compute the same thing over what you received. If they match, the message came from someone who knows the secret and was not altered.
For this note we defined a simple scheme. The header looks like x-signature: t=1795000000,v1=<hex>, where t is a Unix timestamp in seconds and v1 is the hex HMAC-SHA256 of the string <t>.<raw body>. Real providers use their own header names and formats; the principles carry over.
What do the sign and verify functions look like?
// sign.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
export const SECRET = 'whsec_test_only_not_a_real_secret';
// Sender side: sign "<timestamp>.<raw body>" with HMAC-SHA256, hex encoded.
export function sign(rawBody, timestamp, secret = SECRET) {
return createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest('hex');
}
// Receiver side. rawBody must be the exact bytes received (a Buffer).
export function verify(rawBody, header, secret = SECRET, { now = Date.now(), toleranceSec = 300 } = {}) {
const parts = Object.fromEntries(
String(header ?? '').split(',').map((p) => p.trim().split('=', 2))
);
const t = Number(parts.t);
if (!Number.isInteger(t) || !parts.v1) return { ok: false, reason: 'malformed header' };
if (Math.abs(now / 1000 - t) > toleranceSec) return { ok: false, reason: 'timestamp outside tolerance' };
const expected = Buffer.from(sign(rawBody, t, secret), 'hex');
const given = Buffer.from(parts.v1, 'hex');
if (given.length !== expected.length) return { ok: false, reason: 'wrong length' };
return timingSafeEqual(given, expected) ? { ok: true } : { ok: false, reason: 'signature mismatch' };
}
Three details matter:
verifytakes aBufferof the raw body, never a parsed object.- Both signatures are decoded from hex into bytes before comparing, so the comparison is byte against byte.
- The length check comes before
timingSafeEqual, for a reason shown below.
Why does verifying a re-serialized body fail?
If a framework parses the JSON body before your handler runs, it is tempting to verify against JSON.stringify(req.body). That only works if stringifying the parsed object gives back the exact bytes the sender signed, and JSON does not promise that.
We took eight bodies a sender might send, all valid JSON with the same meaning, signed each as sent, then parsed and re-serialized it and signed the result:
// rawbody.mjs
import { sign } from './sign.mjs';
// Bodies as a sender might serialize them. Each is valid JSON.
const bodies = {
'pretty-printed': '{\n "id": "evt_1",\n "amount": 2500\n}',
'trailing newline': '{"id":"evt_1","amount":2500}\n',
'float written as 25.0': '{"id":"evt_1","amount":25.0}',
'escaped unicode': '{"id":"evt_1","name":"Caf\\u00e9"}',
'escaped slash': '{"id":"evt_1","url":"https:\\/\\/example.com"}',
'big integer': '{"id":"evt_1","order":12345678901234567890}',
'duplicate key': '{"id":"evt_1","id":"evt_2"}',
'compact, plain ASCII': '{"id":"evt_1","amount":2500}',
};
const t = 1795000000;
for (const [label, raw] of Object.entries(bodies)) {
const sent = sign(Buffer.from(raw), t);
const reserialized = JSON.stringify(JSON.parse(raw));
const recomputed = sign(Buffer.from(reserialized), t);
console.log(
`${label.padEnd(22)} ${sent === recomputed ? 'match ' : 'MISMATCH'} re-serialized: ${reserialized}`
);
}
pretty-printed MISMATCH re-serialized: {"id":"evt_1","amount":2500}
trailing newline MISMATCH re-serialized: {"id":"evt_1","amount":2500}
float written as 25.0 MISMATCH re-serialized: {"id":"evt_1","amount":25}
escaped unicode MISMATCH re-serialized: {"id":"evt_1","name":"Café"}
escaped slash MISMATCH re-serialized: {"id":"evt_1","url":"https://example.com"}
big integer MISMATCH re-serialized: {"id":"evt_1","order":12345678901234567000}
duplicate key MISMATCH re-serialized: {"id":"evt_2"}
compact, plain ASCII match re-serialized: {"id":"evt_1","amount":2500}
Seven of eight failed. Each failure is a different way the round trip loses the original bytes:
| Body | What the round trip changed |
|---|---|
| Pretty-printed | Removed the spaces and newlines |
| Trailing newline | Dropped the final newline |
25.0 | Wrote the number as 25 |
é | Turned the escape into the character é |
\/ | Turned the escaped slash into / |
| A 20-digit integer | Rounded it to the nearest double: ...567000 |
| A duplicate key | Kept only the last value |
The big-integer and duplicate-key rows are worse than a failed check: the parsed object is not even what the sender sent. That is another reason to verify first and parse second.
The last row is the trap. A developer testing locally with a hand-written compact body will see verification pass, ship it, and only find out when the real sender pretty-prints, escapes a character or appends a newline.
What does a correct endpoint look like?
Collect the body as bytes, verify, and only then parse:
// server.mjs
import http from 'node:http';
import { verify } from './sign.mjs';
const seen = new Set(); // event ids already processed
const server = http.createServer((req, res) => {
const chunks = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
const raw = Buffer.concat(chunks);
const check = verify(raw, req.headers['x-signature']);
if (!check.ok) {
res.writeHead(401).end(check.reason + '\n');
return;
}
const event = JSON.parse(raw); // parse only after the signature passes
if (seen.has(event.id)) {
res.writeHead(200).end('duplicate, ignored\n');
return;
}
seen.add(event.id);
res.writeHead(200).end(`accepted ${event.id}\n`);
});
});
server.listen(0, '127.0.0.1', () => console.log(server.address().port));
If you use a framework, look for its option to keep the raw body for one route, and verify against that.
What happened with nine deliveries?
A client script sent the server one valid pretty-printed delivery and eight variations:
// client.mjs
import { sign } from './sign.mjs';
const port = process.argv[2];
const url = `http://127.0.0.1:${port}/webhook`;
const now = () => Math.floor(Date.now() / 1000);
async function send(label, body, header) {
const r = await fetch(url, { method: 'POST', body, headers: { 'x-signature': header } });
console.log(`${label.padEnd(34)} ${r.status} ${(await r.text()).trim()}`);
}
const body = '{\n "id": "evt_1",\n "type": "booking.paid",\n "amount": 2500\n}';
const t = now();
const good = `t=${t},v1=${sign(Buffer.from(body), t)}`;
await send('valid, pretty-printed body', body, good);
await send('same delivery again (retry)', body, good);
await send('amount changed to 1', body.replace('2500', '1'), good);
await send('signed with the wrong secret', body, `t=${t},v1=${sign(Buffer.from(body), t, 'wrong')}`);
await send('signature cut short', body, good.slice(0, -2));
await send('signature not hex', body, `t=${t},v1=zz`);
await send('no header', body, '');
const old = t - 600;
await send('replayed with a 10-minute-old t', body, `t=${old},v1=${sign(Buffer.from(body), old)}`);
await send('valid, uppercase hex', body.replace('evt_1', 'evt_2'),
`t=${t},v1=${sign(Buffer.from(body.replace('evt_1', 'evt_2')), t).toUpperCase()}`);
valid, pretty-printed body 200 accepted evt_1
same delivery again (retry) 200 duplicate, ignored
amount changed to 1 401 signature mismatch
signed with the wrong secret 401 signature mismatch
signature cut short 401 wrong length
signature not hex 401 wrong length
no header 401 malformed header
replayed with a 10-minute-old t 401 timestamp outside tolerance
valid, uppercase hex 200 accepted evt_2
What each line shows:
- The pretty-printed body passed, because we verified the bytes as they arrived.
- The retry got a 200 but did no work. A sender that did not see your first response will send again; answering 200 stops it, and the ID check stops a double booking.
- A changed amount failed with the original signature, which is the whole point.
- A cut-short or non-hex signature decoded to the wrong number of bytes and was refused by the length check, before
timingSafeEqualran.Buffer.from('zz', 'hex')decodes to an empty buffer rather than throwing. - A ten-minute-old timestamp failed even though the signature over it was genuine. Without that check, anyone who captured one delivery could resend it forever.
- Uppercase hex passed, because both sides are compared as decoded bytes, not as strings.
Why check the length before timingSafeEqual?
timingSafeEqual compares every byte no matter where the first difference is, so the time taken does not reveal how much of a guessed signature was right. It does not accept inputs of different lengths:
// tse.mjs
import { timingSafeEqual } from 'node:crypto';
try {
timingSafeEqual(Buffer.from('abcd'), Buffer.from('abc'));
} catch (e) {
console.log(e.code, '-', e.message);
}
try {
timingSafeEqual('abc', 'abc');
} catch (e) {
console.log(e.code, '-', e.message.split('.')[0]);
}
console.log(timingSafeEqual(Buffer.from('abc'), Buffer.from('abc')));
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH - Input buffers must have the same byte length
ERR_INVALID_ARG_TYPE - The "buf1" argument must be an instance of ArrayBuffer, Buffer, TypedArray, or DataView
true
An uncaught throw on a malformed header turns a 401 into a 500, and a sender may keep retrying a 500. Checking the length first returns a clean refusal. Comparing lengths does not leak anything useful: the length of a SHA-256 signature is public.
Plain strings are refused too, so decode both sides to buffers.
A checklist for any webhook endpoint
- Read the raw body as bytes. Verify before parsing.
- Compute the HMAC with the shared secret, kept in an environment variable, never in the repository.
- Decode both signatures to bytes, check the lengths match, then
timingSafeEqual. - Sign a timestamp with the body and reject anything outside a few minutes.
- Record processed event IDs and answer repeats with a 2xx without repeating the work.
- Return 401 for a bad signature, and log the reason on your side only.
- Test with a pretty-printed body, a body with escapes, and a trailing newline, not only compact JSON.
Limitations
- The header format and signing scheme are ours, defined for this test. Your provider’s documentation decides the header name, what is signed, the encoding and the tolerance. We could not open any provider’s documentation from this environment, so we make no claim about a specific provider.
- We did not measure timing differences between
===andtimingSafeEqual. The case fortimingSafeEqualhere rests on how it is specified to behave, not on a measurement. - The set of seen event IDs lives in memory and is lost on restart. In production, store it alongside the work the event triggers, so the two are written together.
- Only Node.js 22.23.5 and
node:httpwere tested. Frameworks expose the raw body in different ways.
Related reading
- Idempotency Keys for a Booking Form: Stopping Double Clicks and Retries From Creating Two Bookings
- Rate-Limiting a Contact Form Endpoint: A Fixed Window Against a Token Bucket, Tested With a Burst
- Treating visitor text as untrusted when it reaches a model
Frequently asked questions
Why does my webhook signature verification fail when the secret is right?
Usually because the HMAC is computed over a re-serialized body instead of the raw bytes. Parsing JSON and calling JSON.stringify drops whitespace, rewrites escapes, changes number formats and collapses duplicate keys. In our test, seven of eight valid bodies produced a different signature after that round trip. Read the raw body, verify it, then parse.
Why use crypto.timingSafeEqual instead of === to compare signatures?
A normal comparison can stop at the first differing character, so in principle the time it takes leaks how much of a guess was right. timingSafeEqual compares every byte regardless. It needs two buffers of the same length: in Node.js 22.23.5 it threw ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH on a length mismatch, so check the length first and reject.
How do you stop a webhook from being replayed?
Sign a timestamp together with the body, and reject deliveries whose timestamp is more than a few minutes from your clock. Then record each event ID you process and ignore repeats. In our test, a correctly signed delivery with a timestamp ten minutes old was refused, and a second copy of a valid delivery was acknowledged but not processed again.
Should a webhook endpoint return an error for a duplicate event?
Usually not. Senders retry when they do not get a success response, so a duplicate is often a delivery that already worked. Return a 2xx status so the sender stops retrying, and simply do not repeat the work. Return 401 only for signatures that fail, so the sender's logs show a real problem.
Does this note match my payment provider's webhook format?
Not necessarily. The header format here, a timestamp and a hex HMAC-SHA256 of the timestamp and body, is one we defined for the test. Providers differ in header names, what is signed, the encoding and the tolerance window. Follow your provider's documentation for those details; the raw-body and timing-safe rules apply either way.