Webhook HMAC-SHA256 Verifier · GitHub + Express

GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express

Verify and generate GitHub + Express HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·X-Hub-Signature-256

X-Hub-Signature-256: sha256=1633328113ff57d3080d7de0a95e7e2ca03d5282f950c6643bea33d25631bd7f

// src/routes/webhooks.ts — Express Raw Buffer Verification
// Mount BEFORE app.use(express.json()) so express.raw() receives untouched bytes!
import crypto from 'node:crypto';
import express from 'express';

const app = express();

app.post(
  '/webhooks/github',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const rawBody = req.body as Buffer;
    const secret = process.env.WEBHOOK_SECRET!;

    const received = String(req.headers['x-hub-signature-256'] ?? '');
    const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');

    const expectedBuf = Buffer.from(expected, 'utf8');
    const receivedBuf = Buffer.from(received, 'utf8');

    if (expectedBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(expectedBuf, receivedBuf)) {
      res.status(400).send('Invalid GitHub webhook signature');
      return;
    }

    const payload = JSON.parse(rawBody.toString('utf8'));
    res.status(200).json({ received: true, id: payload.id ?? null });
  }
);

// Global JSON parser mounted AFTER raw webhook routes
app.use(express.json());
1. Raw Body HMAC (HEX)Valid

1633328113ff57d3080d7de0a95e7e2ca03d5282f950c6643bea33d25631bd7f

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

44bfd52f4592929e724ee763f503881c6e314c1f3de677a75349ab44645d4000

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (GitHub + Express)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in GitHub + Express, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

401 Unauthorized: Invalid GitHub X-Hub-Signature-256 — missing "sha256=" prefix or HMAC computed over JSON.stringify(req.body) instead of raw bytes.

Raw Request Stream Handling & Replay Protection in GitHub + Express

GitHub Apps, repository push hooks, and deployment bots sign every webhook delivery using HMAC-SHA256 over the exact raw HTTP body bytes and transmit the hex digest inside the X-Hub-Signature-256 header prefixed with "sha256=". Unlike Stripe or Slack, GitHub does not embed a timestamp prefix inside the signing base, it signs the raw payload directly, yet verifying GitHub webhooks in Express still fails routinely for three concrete reasons.

First, calling JSON.stringify(req.body) after express.json() strips indentation, alters escaped Unicode sequences (such as emojis in pull request titles or commit messages!), and immediately produces a mismatched SHA-256 digest. Always capture the raw Buffer via express.raw({ type: "application/json" }) or the express.json verify hook.

Second, developers frequently forget the literal "sha256=" prefix when comparing against crypto.createHmac("sha256", secret).update(rawBody).digest("hex"), or mistakenly inspect the deprecated SHA-1 header X-Hub-Signature instead of X-Hub-Signature-256.

Third, GitHub enforces a strict 10-second response timeout and marks deliveries as failed if your Express server spends too long cloning repos or calling external APIs synchronously. Always verify X-Hub-Signature-256 immediately with crypto.timingSafeEqual(), check X-GitHub-Delivery for idempotency, enqueue background work, and respond 202 Accepted.

Use the browser Web Crypto verifier above to generate exact X-Hub-Signature-256 headers for any GitHub event JSON and test both missing-prefix and re-serialized JSON failure diagnostics instantly.

When scaling GitHub App or CI/CD automation webhooks on Node.js Express, store incoming X-GitHub-Delivery GUIDs in Redis or PostgreSQL to guarantee idempotent processing across manual redeliveries from GitHub's Recent Deliveries tab. Combining express.raw(), constant-time crypto.timingSafeEqual(), and background BullMQ workers keeps your Express event loop responsive under bursty monorepo push events without hitting GitHub's 10-second timeout.

Step-by-Step GitHub + Express Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Capture Raw Buffer Bytes in Express for /webhooks/github

    src/routes/githubWebhook.ts

    Verify X-Hub-Signature-256 over the raw Buffer with the "sha256=" prefix and constant-time crypto.timingSafeEqual().

    src/routes/githubWebhook.tstypescript
    import crypto from 'node:crypto';
    import express from 'express';
    
    export const githubRouter = express.Router();
    
    githubRouter.post(
      '/github',
      express.raw({ type: 'application/json' }),
      (req, res) => {
        const signature = String(req.headers['x-hub-signature-256'] ?? '');
        const deliveryId = String(req.headers['x-github-delivery'] ?? '');
        const eventName = String(req.headers['x-github-event'] ?? '');
        const rawBody = req.body as Buffer;
        const secret = process.env.GITHUB_WEBHOOK_SECRET!;
    
        const expected =
          'sha256=' +
          crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
    
        const expectedBuf = Buffer.from(expected, 'utf8');
        const receivedBuf = Buffer.from(signature, 'utf8');
    
        if (
          expectedBuf.length !== receivedBuf.length ||
          !crypto.timingSafeEqual(expectedBuf, receivedBuf)
        ) {
          res.status(401).json({ error: 'Invalid X-Hub-Signature-256' });
          return;
        }
    
        const payload = JSON.parse(rawBody.toString('utf8'));
        res.status(202).json({ accepted: true, deliveryId, eventName, action: payload.action });
      }
    );
  2. 2Mount the GitHub Router Before Global express.json()

    src/server.ts

    Mount app.use("/webhooks", githubRouter) before app.use(express.json()) so req.body stays an untouched Buffer.

    src/server.tstypescript
    import express from 'express';
    import { githubRouter } from './routes/githubWebhook';
    
    const app = express();
    app.use('/webhooks', githubRouter);
    app.use(express.json());
  3. 3Configure GitHub Repository Webhook Content Type as application/json

    GitHub Repository Settings -> Webhooks

    Select "application/json" (not application/x-www-form-urlencoded) and generate a 32-byte random secret with openssl rand -hex 32.

    GitHub Repository Settings -> Webhooksbash
    openssl rand -hex 32
  4. 4Deduplicate Retries Using the X-GitHub-Delivery UUID Header

    src/services/deliveryStore.ts

    Every GitHub webhook event includes a unique X-GitHub-Delivery GUID. Record it in Redis with a 24-hour TTL (SET nx ex 86400) to ignore duplicate redeliveries safely.

    src/services/deliveryStore.tstypescript
    // Redis atomic idempotency check:
    // const isNew = await redis.set(`gh:delivery:${deliveryId}`, '1', 'EX', 86400, 'NX');

Common GitHub + Express Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Using Deprecated SHA-1 X-Hub-Signature Instead of X-Hub-Signature-256

GitHub still sends legacy SHA-1 X-Hub-Signature for backward compatibility, but SHA-1 is cryptographically deprecated. Always verify X-Hub-Signature-256 with HMAC-SHA256.

Pitfall 2

Omitting the "sha256=" Prefix When Comparing Hex Digests

GitHub formats the header as "sha256=<64 hex chars>". Comparing the raw 64-char hex digest directly against the full header always fails even when your secret and raw body are 100% correct.

Pitfall 3

GitHub Configured as x-www-form-urlencoded Instead of application/json

If the GitHub webhook UI is left on application/x-www-form-urlencoded, express.raw({ type: "application/json" }) skips the request and leaves req.body empty. Always set Content type to application/json in GitHub Settings.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Why did my GitHub webhook fail only on PRs containing emojis or non-ASCII text?
JSON parsers and serializers normalize Unicode escapes differently. Hashing the raw UTF-8 Buffer directly (rather than JSON.stringify(req.body)) guarantees byte-for-byte agreement with GitHub regardless of emojis or international characters.
What HTTP status code should Express return for GitHub ping events?
When you create a new webhook, GitHub sends a "ping" event (X-GitHub-Event: ping) signed with your secret. Verify X-Hub-Signature-256 as usual and return HTTP 200 or 202 OK.
Does GitHub enforce a timestamp replay header like Stripe?
No. GitHub signs only the raw payload bytes without a timestamp prefix, so storing seen X-GitHub-Delivery UUIDs in Redis or PostgreSQL is the recommended way to prevent replay processing.
Can I use @octokit/webhooks-methods instead of writing raw crypto code?
Yes. @octokit/webhooks-methods uses Web Crypto and constant-time comparison internally; though you still MUST pass the exact raw body string/Buffer from express.raw() into verify().
Browse all 10 webhook guides →