Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

github-webhook.jsJavaScript
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));
Text
true
false
false

Compare 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.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.