APIs · Intermediate · 22 min
How to Receive and Verify Webhooks Safely in Node.js
By Padding · Updated 16 Nov 2026
Node.js 26 · Express 5.3
You will build an Express 5.3 webhook receiver on Node.js 26 that checks an HMAC-SHA256 signature over the raw request body, compares it in constant time, rejects stale timestamps and duplicate events, and a small sender that proves each rejection works.
On this page
A webhook is a request that another service sends to your server when something happens: a payment succeeds, a repository gets a push, an invoice is paid. Your endpoint is a public URL, so anyone on the internet can post to it. If your code trusts every request, anyone can tell your app that an order was paid.
The fix is a signature. The sender and you share a secret. The sender computes an HMAC of the request, a keyed hash that only someone with the secret can produce, and sends it in a header. You recompute it and compare. This tutorial builds the receiver and a stand-in sender that uses the scheme Stripe documents for its webhooks: a Stripe-Signature header of the form t=<unix time>,v1=<hex HMAC-SHA256>, computed over the text <t>.<raw body> with the endpoint's signing secret as the key (see https://docs.stripe.com/webhooks). Other providers differ in header names and what they sign, but the checks that keep you safe are the same: raw body, constant-time comparison, a timestamp window, and duplicate detection.
Everything runs on your own computer: the receiver listens on 127.0.0.1 and the sender is a script. No account with any provider is needed.
Step 1 · Create the project and the secret
Make a folder, add Express 5.3 and mark the project as using ES modules. Then create the shared secret in a file only you can read. umask 077 makes the file private from the start, and the secret never appears on a command line:
mkdir -p ~/webhook-demo
cd ~/webhook-demo
npm init -y > /dev/null
npm pkg set type=module
npm install express@^5.3.0
(umask 077; printf 'WEBHOOK_SECRET=whsec_%s\n' "$(openssl rand -hex 24)" > .env)
ls -l .envThe listing starts with -rw-------. The whsec_ prefix only imitates the look of Stripe's secrets. If the project is in Git, add .env to .gitignore first: see keep secrets out of Git. Node loads the file for you with the --env-file option, so no extra package is needed.
Check it worked
cd ~/webhook-demo
node -p "require('express/package.json').version"The output is 5.3.0, or a later 5.3 patch release.
Step 2 · Write the verification function
Put the check in its own file, so you can test it without a server. Read the comments, because each line guards against one attack:
cd ~/webhook-demo
cat > verify.js <<'JS'
import crypto from 'node:crypto';
export const TOLERANCE_SECONDS = 300;
// Returns { ok: true } or { ok: false, reason }.
// rawBody must be the exact bytes that arrived: a Buffer.
export function verifySignature(rawBody, header, secret, nowSeconds = Date.now() / 1000) {
if (!Buffer.isBuffer(rawBody)) return { ok: false, reason: 'body is not raw' };
if (!header) return { ok: false, reason: 'missing signature header' };
// Header looks like: t=1798765432,v1=<hex>,v1=<hex>
let timestamp = null;
const signatures = [];
for (const part of header.split(',')) {
const [key, value] = part.split('=');
if (key === 't') timestamp = value;
if (key === 'v1' && value) signatures.push(value);
}
if (!/^\d+$/.test(timestamp ?? '') || signatures.length === 0) {
return { ok: false, reason: 'malformed signature header' };
}
// HMAC-SHA256 over "<timestamp>.<raw body>", keyed with the shared secret.
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest();
// Compare every v1 value (a sender may send two while rotating secrets)
// in constant time. timingSafeEqual throws if lengths differ, so skip those.
const match = signatures.some((hex) => {
const given = Buffer.from(hex, 'hex');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
if (!match) return { ok: false, reason: 'signature mismatch' };
// Only after the signature is valid is the timestamp trustworthy.
const age = Math.abs(nowSeconds - Number(timestamp));
if (age > TOLERANCE_SECONDS) return { ok: false, reason: 'timestamp outside tolerance' };
return { ok: true };
}
JSrawBodymust be aBuffer. The signature covers the exact bytes the sender produced. If you parse the JSON and serialise it again, spacing and key order can change and a valid signature stops matching.- A plain
===on two strings stops at the first different character, and a patient attacker can use the timing difference to guess a signature one character at a time.crypto.timingSafeEqualtakes the same time wherever the values differ. - The timestamp is part of the signed text, so an attacker cannot change it without breaking the signature. A valid old request (a replay) fails the window check instead. Five minutes is the tolerance Stripe's libraries use by default.
- Your server's clock matters for the window: keep it synchronised with NTP, which Ubuntu does by default.
Check it worked
Call the function directly with one signature you compute here and two wrong ones:
cd ~/webhook-demo
cat > try.mjs <<'JS'
import crypto from 'node:crypto';
import { verifySignature } from './verify.js';
const secret = 'whsec_example';
const body = Buffer.from('{"id":"evt_1"}');
const t = Math.floor(Date.now() / 1000);
const sig = crypto.createHmac('sha256', secret).update(`${t}.`).update(body).digest('hex');
console.log(verifySignature(body, `t=${t},v1=${sig}`, secret));
console.log(verifySignature(Buffer.from('{"id":"evt_2"}'), `t=${t},v1=${sig}`, secret));
console.log(verifySignature(body, `t=${t - 3600},v1=${sig}`, secret));
JS
node try.mjs
rm try.mjsThe output has three lines: { ok: true }, then { ok: false, reason: 'signature mismatch' } for the changed body, then { ok: false, reason: 'signature mismatch' } again for the old timestamp. The third one fails on the signature because changing t changes the signed text. A genuinely old request, signed with its old timestamp, fails on the window instead, and the sender script in a later step shows that case.
Step 3 · Write the receiver
The receiver has one route. express.raw keeps the body as a Buffer, and only for that route, so the rest of your app can still use express.json():
cd ~/webhook-demo
cat > server.js <<'JS'
import express from 'express';
import { verifySignature } from './verify.js';
const secret = process.env.WEBHOOK_SECRET;
if (!secret) throw new Error('WEBHOOK_SECRET is not set');
const app = express();
const seen = new Set(); // event ids already handled; use a database table in production
app.post(
'/webhooks',
express.raw({ type: 'application/json', limit: '256kb' }),
(req, res) => {
const result = verifySignature(req.body, req.get('Stripe-Signature'), secret);
if (!result.ok) {
console.log(`rejected: ${result.reason}`);
return res.status(400).json({ error: 'invalid webhook' });
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).json({ error: 'invalid webhook' });
}
if (!event || typeof event.id !== 'string') {
return res.status(400).json({ error: 'invalid webhook' });
}
if (seen.has(event.id)) {
console.log(`duplicate: ${event.id}`);
return res.status(200).json({ received: true });
}
seen.add(event.id);
console.log(`accepted: ${event.id} ${event.type}`);
// Do the slow work after answering: queue a job, do not make the sender wait.
res.status(200).json({ received: true });
},
);
app.listen(3000, '127.0.0.1', () => {
console.log('listening on http://127.0.0.1:3000');
});
JS- The
400body is the same for every failure. The real reason goes to your log, not to a caller who might be probing for a way in. - A body that is valid JSON but has no string
id, such asnull, is refused with400rather than crashing the handler. - A duplicate still gets
200. The sender only wants to know it was received, and answering with an error would make it retry. Senders deliver at least once, so the same event can arrive twice. Keeping the ids you have handled makes your handler safe to run twice. - The handler answers quickly. Senders treat a slow response as a failure and retry, so queue anything that takes time.
listen(3000, '127.0.0.1')accepts connections from your own computer only. To receive real webhooks, a public HTTPS address must reach this port: put it behind a reverse proxy as in nginx as a reverse proxy for a Node app. While developing, a provider's forwarding tool can post to localhost for you, such asstripe listen --forward-to localhost:3000/webhooksfor Stripe.
Start it in a second terminal:
cd ~/webhook-demo
node --env-file=.env server.jsThe terminal prints listening on http://127.0.0.1:3000 and keeps running.
Step 4 · Write the stand-in sender
The sender builds a signed request the way a provider would, with options to break it in each way you want to see refused. It reads the same secret file:
cd ~/webhook-demo
cat > send.mjs <<'JS'
import crypto from 'node:crypto';
const scenario = process.argv[2] ?? 'valid';
const url = 'http://127.0.0.1:3000/webhooks';
const secret = process.env.WEBHOOK_SECRET;
const sign = (key, t, body) =>
crypto.createHmac('sha256', key).update(`${t}.`).update(body).digest('hex');
async function post(body, header) {
const headers = { 'Content-Type': 'application/json' };
if (header) headers['Stripe-Signature'] = header;
const res = await fetch(url, { method: 'POST', headers, body });
console.log(`${scenario}: ${res.status} ${await res.text()}`);
}
const now = Math.floor(Date.now() / 1000);
const body = JSON.stringify({ id: `evt_${scenario}_1`, type: 'invoice.paid', amount: 4200 });
switch (scenario) {
case 'valid':
await post(body, `t=${now},v1=${sign(secret, now, body)}`);
break;
case 'duplicate':
await post(body, `t=${now},v1=${sign(secret, now, body)}`);
await post(body, `t=${now},v1=${sign(secret, now, body)}`);
break;
case 'tampered': {
const header = `t=${now},v1=${sign(secret, now, body)}`;
await post(body.replace('4200', '9999'), header);
break;
}
case 'wrong-secret':
await post(body, `t=${now},v1=${sign('whsec_not_the_secret', now, body)}`);
break;
case 'stale': {
const old = now - 3600;
await post(body, `t=${old},v1=${sign(secret, old, body)}`);
break;
}
case 'unsigned':
await post(body, null);
break;
default:
console.log('unknown scenario');
}
JSCheck it worked
Send a correctly signed event in the first terminal:
cd ~/webhook-demo
node --env-file=.env send.mjs validThe sender prints valid: 200 {"received":true} and the receiver logs accepted: evt_valid_1 invoice.paid.
Step 5 · Watch every attack fail
Run the other scenarios one at a time. Each prints the status and body the sender received:
cd ~/webhook-demo
for s in tampered wrong-secret stale unsigned duplicate; do
node --env-file=.env send.mjs "$s"
doneYou should see 400 {"error":"invalid webhook"} for tampered, wrong-secret, stale and unsigned. For duplicate you see two lines with 200 {"received":true}. The receiver's log tells the reasons apart. In the receiver terminal you see, in order, rejected: signature mismatch for the tampered body and the wrong secret, rejected: timestamp outside tolerance for the stale request, rejected: missing signature header for the unsigned one, then accepted: evt_duplicate_1 invoice.paid once and duplicate: evt_duplicate_1 once. The stale request has a valid signature, so it passes that check and is stopped by the window alone.
Troubleshooting
- Every valid request is rejected with
signature mismatch: something changed the body before your check. The usual cause isexpress.json()running first for the same route. Registerexpress.rawon the webhook route, or mount the webhook route before any global body parser. - Your real provider's signatures never match: check that you are using the secret of that endpoint (providers often have one per endpoint and one for test mode), and that the proxy in front does not rewrite the body.
timestamp outside tolerancefor fresh events: your server clock is wrong. Checktimedatectl.WEBHOOK_SECRET is not set: start withnode --env-file=.env server.jsfrom the project folder.
Step 6 · Carry the pattern into production
- Store event ids in a database. The
Setforgets everything at a restart and is not shared between processes. Use a table with a unique constraint on the event id, and insert before you do the work. - Keep the secret out of the code. Load it from a file or your host's secret store, and rotate it if it leaks. Senders that allow two active secrets let you rotate with no downtime, which is why the verifier accepts several
v1values. - Limit the body size.
express.raw({ limit })refuses oversized bodies, so a flood of huge posts cannot fill your memory. - Use the provider's library when there is one. Stripe's official libraries do this verification for you. Writing it by hand once, as here, shows you what they check.
- Do not trust the payload's own data alone. For money, treat the event as a signal and fetch the object from the provider's API before you fulfil an order.
Step 7 · Stop the receiver and clean up
Press Ctrl+C in the receiver terminal. Then delete the folder, which holds the secret:
cd ~
rm -rf ~/webhook-demoNext steps
- Take card payments and use this receiver for fulfilment: take payments with Stripe Checkout.
- Put the receiver behind a public HTTPS address: nginx as a reverse proxy for a Node app.
- Build the rest of the API: build a REST API with Express 5.
- Limit abusive callers: rate limit an API with Nginx.
Related tutorials
- How to Build a REST API with Express 5You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.
- How to Install Node.js 26 LTS on Ubuntu 26.04You will install Node.js 26 LTS with npm from the NodeSource apt repository on Ubuntu 26.04 so that apt keeps it patched, run a first script, set up global npm packages without sudo, and learn the checksum-verified tarball route as an alternative.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials