Secure Webhooks in Node.js: HMAC Signatures, Replay Protection and Idempotency
An invoice provider sends an invoice.paid event. Your server records the payment, but the connection drops before the provider receives your response. A minute later, the same event arrives again with a valid signature. Should you grant another month of service?
Three checks answer different parts of that question. An HMAC lets you check that someone who holds the shared secret signed the payload. A signed timestamp limits how long you will accept a delivery. A durable record of the event ID tells you whether the invoice has already been handled.
Sign the bytes that arrive
In this example, the sender posts JSON to /webhooks/example and signs the ASCII timestamp, a period and the exact body bytes with HMAC-SHA-256. The timestamp goes in X-Demo-Timestamp and the hex digest in X-Demo-Signature, prefixed with sha256=. These are example headers. Use your provider’s signing format, test vectors and retry rules for an actual integration. Use HTTPS in production: an HMAC leaves the message readable.
Consider the following two bodies. Both describe the same event, but they produce different signatures:
{"id":"evt_42","type":"invoice.paid"}
{ "type": "invoice.paid", "id": "evt_42" }
In a framework that normally parses JSON before calling your handler, configure this route to retain the original bytes. Serializing the parsed value can change whitespace, key order or escaping. The guide to JSON, form data and multipart requests explains how those formats appear on the wire.
Run a local receiver
Save this as webhook-server.mjs. It listens on the loopback interface, caps the body at 1 MiB and accepts timestamps up to five minutes either side of its clock. The demo logs verified event IDs and types. It performs no billing operation.
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
const secret = process.env.WEBHOOK_SECRET;
if (!secret) throw new Error("Set WEBHOOK_SECRET first");
const maxBodyBytes = 1024 * 1024;
const toleranceSeconds = 300;
function verify(rawBody, timestampText, signatureText) {
if (typeof timestampText !== "string" || !/^\d{10}$/.test(timestampText)) return false;
if (typeof signatureText !== "string" || !/^sha256=[a-f0-9]{64}$/i.test(signatureText)) return false;
const timestamp = Number(timestampText);
const now = Math.floor(Date.now() / 1000);
if (!Number.isSafeInteger(timestamp)) return false;
if (Math.abs(now - timestamp) > toleranceSeconds) return false;
const expected = createHmac("sha256", secret)
.update(`${timestampText}.`, "utf8")
.update(rawBody)
.digest();
const received = Buffer.from(signatureText.slice(7), "hex");
return received.length === expected.length &&
timingSafeEqual(received, expected);
}
createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/webhooks/example") {
res.writeHead(404).end("Not found");
return;
}
if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/json") {
res.writeHead(415).end("Expected application/json");
return;
}
const chunks = [];
let size = 0;
try {
for await (const chunk of req) {
size += chunk.length;
if (size > maxBodyBytes) {
res.writeHead(413).end("Too large");
return;
}
chunks.push(chunk);
}
} catch {
if (!res.headersSent) res.writeHead(400).end("Invalid body");
return;
}
const rawBody = Buffer.concat(chunks, size);
if (!verify(
rawBody,
req.headers["x-demo-timestamp"],
req.headers["x-demo-signature"]
)) {
res.writeHead(401).end("Signature rejected");
return;
}
let event;
try {
event = JSON.parse(rawBody.toString("utf8"));
} catch {
res.writeHead(400).end("Invalid JSON");
return;
}
if (typeof event?.id !== "string" || !event.id.trim() ||
typeof event.type !== "string" || !event.type.trim()) {
res.writeHead(400).end("Invalid event");
return;
}
// Demo only: use a durable unique event ID record in production.
console.log("Verified", JSON.stringify({ id: event.id, type: event.type }));
res.writeHead(200, { "Content-Type": "text/plain" }).end("OK");
}).listen(8080, "127.0.0.1", () => {
console.log("Webhook demo listening on localhost:8080");
});
The signature format check ensures that the two digests have the same byte length for comparison. Node documents the signing and comparison functions under createHmac() and timingSafeEqual().
Send the same bytes with cURL
In a terminal, set a disposable secret and start the receiver:
export WEBHOOK_SECRET='local-webhook-example-only'
node webhook-server.mjs
In a second terminal, run the same export line, then sign and send the request below. Both printf and --data-binary preserve the body without adding a final newline. The cURL command builder can help you assemble the headers and body. Keep your signing secret on the server or in your local test environment.
body='{"id":"evt_42","type":"invoice.paid","invoice":"inv_7"}'
ts=$(date +%s)
digest=$(printf '%s' "$ts.$body" | node --input-type=module -e '
import { createHmac } from "node:crypto";
const mac = createHmac("sha256", process.env.WEBHOOK_SECRET);
for await (const chunk of process.stdin) mac.update(chunk);
process.stdout.write(mac.digest("hex"));
')
curl -i http://127.0.0.1:8080/webhooks/example \
-H 'Content-Type: application/json' \
-H "X-Demo-Timestamp: $ts" \
-H "X-Demo-Signature: sha256=$digest" \
--data-binary "$body"
Expect 200 OK. Repeat just the cURL command while the timestamp is fresh and the demo logs the same event twice. To test the byte check, add a space to the JSON while keeping the original digest. Expect 401. To test the time check independently, sign the original body again with a timestamp one hour in the past. Expect 401 even though the digest matches that timestamp and body.
Decide when it is safe to acknowledge the event
For the invoice example, store a unique key such as (provider, account_id, event_id). In one database transaction, insert the key and apply the invoice update. Let a uniqueness constraint arbitrate concurrent deliveries. A second delivery of an already committed event can receive a success response. If the first transaction rolled back, a retry must still be able to do the work.
If a background worker handles the invoice, commit the unique event record and a pending job together before sending a success response. Otherwise a crash between recording the ID and creating the job can make every retry look like a duplicate while the invoice stays unpaid. If the job calls another service, reuse a stable idempotency key there where supported. Keep the record through the provider’s retry and redelivery period, which may be much longer than the signature window.
Test what happens if two deliveries arrive together, if the database is unavailable, and if the worker finishes but loses its response. Also check out-of-order events against the provider’s version or current resource state. The API sequence diagram tutorial shows how to map those failure paths. Before enabling live deliveries, check how your provider rotates signing keys and how it treats each response code.