Node.js webhooks: receive and verify them with Express
By the HookWatcher team · Updated
What you'll build
The endpoint receives GitHub webhooks, but the pattern is the same for any provider that signs with HMAC-SHA256. In order, the Express handler:
- verifies
X-Hub-Signature-256over the raw body bytes, before anything parses them, and answers401if it doesn't match; - requires an
X-GitHub-DeliveryID and parses the JSON (400if either is missing or broken); - skips a delivery ID it has already processed with a
200, so GitHub records success and the event runs once; - answers
202straight away and does the work after the response, because GitHub gives up after 10 seconds.
| Request | Status | Body |
|---|---|---|
| Valid signature, new delivery | 202 | accepted |
| Same delivery ID again | 200 | duplicate |
| Missing or wrong signature, or body changed after signing | 401 | invalid signature |
| Valid signature, no delivery ID or not JSON | 400 | missing delivery id / invalid JSON |
Tested with Node.js 24 and Express 5.2.1. Express 5 needs Node.js 18 or later.
Set up the project
mkdir github-webhooks && cd github-webhooks npm init -y npm install express@5
Then make package.json look like this (the two scripts are what matter):
{
"name": "github-webhooks",
"private": true,
"scripts": {
"start": "node server.js",
"test": "node --test"
},
"dependencies": {
"express": "^5.2.1"
}
}Verify the signature
GitHub sends X-Hub-Signature-256: sha256=<hex>, the HMAC-SHA256 of the body with your webhook secret. Keep the check in its own module so you can test it without a server. crypto.timingSafeEqual compares in constant time, but throws if the two buffers differ in length, so the length check comes first: a short or garbage header should be a 401, not a crash.
const crypto = require("node:crypto");
/** True when header is "sha256=" + the hex HMAC-SHA256 of the raw body. */
function verifyGitHubSignature(rawBody, header, secret) {
if (typeof header !== "string" || !header.startsWith("sha256=")) return false;
const expected = Buffer.from(
"sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex"),
);
const received = Buffer.from(header);
// timingSafeEqual throws on different lengths, so compare those first.
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}
module.exports = { verifyGitHubSignature };Test it against the values GitHub publishes for exactly this purpose:
const test = require("node:test");
const assert = require("node:assert/strict");
const { verifyGitHubSignature } = require("./verify");
// GitHub's published test values (docs: Validating webhook deliveries).
const secret = "It's a Secret to Everybody";
const body = Buffer.from("Hello, World!");
const signature = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
test("accepts GitHub's test signature", () => {
assert.equal(verifyGitHubSignature(body, signature, secret), true);
});
test("rejects a changed body, another secret, a cut signature and no header", () => {
assert.equal(verifyGitHubSignature(Buffer.from("Hello, World?"), signature, secret), false);
assert.equal(verifyGitHubSignature(body, signature, "another secret"), false);
assert.equal(verifyGitHubSignature(body, signature.slice(0, -1), secret), false);
assert.equal(verifyGitHubSignature(body, undefined, secret), false);
assert.equal(verifyGitHubSignature(body, "sha256=" + "é".repeat(64), secret), false); // no exception
});npm test # 2 tests pass
The Express route
The route gets its own body parser, express.raw(), so req.body is a Buffer holding the bytes GitHub signed. type: "*/*" matters: by default express.raw() only parses application/octet-stream, and for anything else Express 5 leaves req.body undefined. The 25 MB limit is GitHub's payload cap; the parser's default is 100 KB, too small for large push events.
const express = require("express");
const { verifyGitHubSignature } = require("./verify");
const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret) throw new Error("Set GITHUB_WEBHOOK_SECRET");
const app = express();
const seen = new Set(); // processed delivery IDs; use a unique database key in production
// Register this route before any app.use(express.json()): it needs the raw bytes.
app.post("/webhooks/github", express.raw({ type: "*/*", limit: "25mb" }), (req, res) => {
const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); // undefined without a body
if (!verifyGitHubSignature(body, req.get("X-Hub-Signature-256"), secret)) {
return res.status(401).type("text").send("invalid signature");
}
const delivery = req.get("X-GitHub-Delivery");
if (!delivery) return res.status(400).type("text").send("missing delivery id");
let payload;
try {
payload = JSON.parse(body.toString("utf8"));
} catch {
return res.status(400).type("text").send("invalid JSON");
}
if (seen.has(delivery)) return res.status(200).type("text").send("duplicate");
seen.add(delivery);
const event = req.get("X-GitHub-Event");
setImmediate(() => handleEvent(event, payload)); // after the response; use a job queue in production
res.status(202).type("text").send("accepted");
});
function handleEvent(event, payload) {
console.log(`${event} ${payload.action ?? ""} ${payload.repository?.full_name ?? ""}`);
}
const port = Number(process.env.PORT) || 3000;
app.listen(port, () => console.log(`Listening on http://localhost:${port}`));Why it's built this way
setImmediate runs the work after the response is written, which keeps the example dependency-free. In production, put the event on a job queue (BullMQ, SQS, a database table) inside the request, then answer; if the process dies after 202, the job is still there. The Set of delivery IDs is the simplest correct deduplication for one process; see the FAQ for multiple instances.
Run it and test it
GITHUB_WEBHOOK_SECRET="It's a test secret" npm start # Listening on http://localhost:3000
In a second terminal, save this script as test-webhook.sh. It signs requests with openssl exactly like GitHub does and checks each status code against the table above. It's the same script for every tutorial in this series, so it also tells you whether a port to another framework behaves the same.
#!/usr/bin/env bash
# Sends five deliveries to a GitHub webhook handler and checks each status code.
# Usage: GITHUB_WEBHOOK_SECRET='...' ./test-webhook.sh http://localhost:3000/webhooks/github
set -u
URL="${1:?usage: test-webhook.sh URL}"
SECRET="${GITHUB_WEBHOOK_SECRET:?set GITHUB_WEBHOOK_SECRET}"
BODY='{"action":"opened","issue":{"number":1347,"title":"Found a bug"},"repository":{"full_name":"octocat/Hello-World"}}'
ID="test-$(date +%s)-$$"
FAILED=0
sign() { printf '%s' "$1" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.*= //'; }
send() { # body, signature ("" = none), delivery ID
local args=(-s -o /dev/null -w '%{http_code}' -X POST "$URL"
-H 'Content-Type: application/json' -H 'X-GitHub-Event: issues' -H "X-GitHub-Delivery: $3")
[ -n "$2" ] && args+=(-H "X-Hub-Signature-256: sha256=$2")
curl "${args[@]}" --data-binary "$1"
}
check() { # name, status received, status expected
if [ "$2" = "$3" ]; then echo "ok $1 ($2)"; else echo "FAIL $1: expected $3, got $2"; FAILED=1; fi
}
SIG=$(sign "$BODY")
check "valid delivery" "$(send "$BODY" "$SIG" "$ID")" 202
check "same delivery again" "$(send "$BODY" "$SIG" "$ID")" 200
check "body changed after signing" "$(send "${BODY/1347/1348}" "$SIG" "$ID-b")" 401
check "no signature" "$(send "$BODY" "" "$ID-c")" 401
check "signed but not JSON" "$(send "not json" "$(sign "not json")" "$ID-d")" 400
exit $FAILEDchmod +x test-webhook.sh GITHUB_WEBHOOK_SECRET="It's a test secret" ./test-webhook.sh http://localhost:3000/webhooks/github
ok valid delivery (202) ok same delivery again (200) ok body changed after signing (401) ok no signature (401) ok signed but not JSON (400)
The server logs issues opened octocat/Hello-World once, after the first response. A FAIL line names the check that broke; the mistakes table below lists what usually causes each one.
Receive real GitHub deliveries on localhost
GitHub won't send webhooks to localhost. Give it a HookWatcher endpoint instead, and let hwcli deliver each capture to your server byte for byte:
- Create a free HookWatcher account (or sign in) and create an endpoint; hwcli works with the endpoints in your account. Its URL looks like
https://hookwatcher.com/<endpoint-id>. - In the repository on GitHub, open Settings → Webhooks → Add webhook. Use the endpoint URL as the payload URL,
application/jsonas the content type, and the same secret your server reads fromGITHUB_WEBHOOK_SECRET. - Run hwcli on your machine.
--include-sensitivematters here: without it, signature headers are left out of local deliveries and every request fails with401.
hwcli login hwcli listen <endpoint-id> --to http://localhost:3000/webhooks/github --include-sensitive
GitHub's ping arrives as soon as the webhook is saved, and your handler answers 202. To send a capture again, run hwcli replay <request-id>: it keeps the original X-GitHub-Delivery, so your handler should answer 200 duplicate. That's your deduplication tested with a real delivery. GitHub's signature has no timestamp, so replayed bytes still verify.
Common mistakes in Node.js webhook handlers
| Symptom | Cause | Fix |
|---|---|---|
| Every request is 401, but the secret is right | app.use(express.json()) runs first, so req.body is an object and re-serialising it never reproduces GitHub's bytes | Register the webhook route before express.json(), or keep the bytes with express.json({ verify: (req, res, buf) => { req.rawBody = buf; } }) |
| 401 for application/json only | express.raw() without type skips JSON, leaving req.body undefined | Pass type: "*/*" or "application/json" |
| 500 RangeError on bad signatures | timingSafeEqual throws when lengths differ | Compare lengths first, as verify.js does |
| 413 Payload Too Large on big pushes | The body parser's 100 KB default limit | Set limit: "25mb" (and your proxy's limit, e.g. NGINX client_max_body_size) |
| Works locally, 401 in production | The secret has a trailing newline or quotes from how it was stored | Trim the value where you set it; log its length, never the secret |
| GitHub shows "Timed out" | The handler awaits slow work before responding | Queue the work and answer 202 first |
| Events processed twice | Redeliveries keep the same X-GitHub-Delivery, and nothing records it | Record delivery IDs atomically and skip seen ones with a 2xx |
See the exact bytes your Express app must verify
Frequently asked questions
Why can't I verify req.body after express.json()?
HMAC is computed over bytes. JSON.stringify(req.body) produces different bytes from what the provider sent whenever spacing, key order, number formatting or escaping differ, and with real payloads they almost always do. Verify the raw Buffer, then parse it.
Do I need a library to verify GitHub webhooks in Node.js?
No. node:crypto has everything: createHmac and timingSafeEqual. GitHub also publishes @octokit/webhooks if you prefer one; for Stripe use the official stripe package's constructEvent.
How do I use this with Fastify, Koa or NestJS?
Keep verify.js as it is and get the raw body from the framework: a raw-body option or content-type parser that hands you a Buffer for this route. The rule doesn't change: verify the bytes before anything parses them.
Is an in-memory set of delivery IDs enough in production?
No. It's empty after a restart and separate in every process or server. Store processed IDs where all instances see them: a database table with a unique key on the delivery ID (insert, and treat a unique-constraint error as a duplicate) or Redis SET key value NX EX 259200. Three days covers GitHub's redelivery window.
Sources
- Express 5 API: express.raw()
- Node.js: crypto.timingSafeEqual
- Node.js: test runner
- GitHub Docs: Validating webhook deliveries
- GitHub Docs: Best practices for using webhooks
More on GitHub's headers and delivery errors: GitHub webhook testing. Body-parser options: body-parser README.