Verify GitHub webhook signature
Verify a GitHub webhook signature by computing an HMAC-SHA256 of the raw body and comparing it with the X-Hub-Signature-256 header.
GitHub sends X-Hub-Signature-256: sha256=<hex>, an HMAC of the raw body with the secret you configured for the webhook. Recompute it and compare in constant time.
import { createHmac, timingSafeEqual } from 'node:crypto';
function verifyGithub(rawBody, header, secret) {
if (!header?.startsWith('sha256=')) return false;
const expected = Buffer.from(
'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex'),
);
const received = Buffer.from(header);
return received.length === expected.length && timingSafeEqual(received, expected);
}
const secret = "It's a Secret to Everybody";
const body = '{"action":"opened"}';
const header = 'sha256=' + createHmac('sha256', secret).update(body).digest('hex');
console.log(verifyGithub(body, header, secret));
console.log(verifyGithub('{"action":"closed"}', header, secret));
console.log(verifyGithub(body, undefined, secret));true
false
falseCompare the whole header text, prefix included, so the length check and timingSafeEqual see two equal-length buffers whenever the signature is the right size. Use the raw body: a re-serialized object can differ in spacing and fail.
The older X-Hub-Signature header uses SHA-1 and is kept only for compatibility; use the 256 version. With Express, mount express.raw({ type: 'application/json' }) on the route to get a Buffer. See GitHub's guide to validating webhook deliveries.