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:
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.
1Capture Raw Buffer Bytes in Express for /webhooks/github
src/routes/githubWebhook.tsVerify X-Hub-Signature-256 over the raw Buffer with the "sha256=" prefix and constant-time crypto.timingSafeEqual().
src/routes/githubWebhook.tstypescriptimport 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 }); } );2Mount the GitHub Router Before Global express.json()
src/server.tsMount app.use("/webhooks", githubRouter) before app.use(express.json()) so req.body stays an untouched Buffer.
src/server.tstypescriptimport express from 'express'; import { githubRouter } from './routes/githubWebhook'; const app = express(); app.use('/webhooks', githubRouter); app.use(express.json());3Configure GitHub Repository Webhook Content Type as application/json
GitHub Repository Settings -> WebhooksSelect "application/json" (not application/x-www-form-urlencoded) and generate a 32-byte random secret with openssl rand -hex 32.
GitHub Repository Settings -> Webhooksbashopenssl rand -hex 324Deduplicate Retries Using the X-GitHub-Delivery UUID Header
src/services/deliveryStore.tsEvery 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.
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.
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.
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.
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:
Validate CI/CD and GitHub Actions .env files locally in your browser. Fix POSIX source .env syntax errors, unquoted spaces, and accidental secret exposure.
Generate a production Nginx reverse proxy for Node.js Express and PM2 on port 4000 with trust proxy, real client IP headers, Certbot SSL, and rate-limit safety.
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().
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →GitHub Webhook X-Hub-Signature-256 Verification in Laravel (Queues & Raw Body)
Verify GitHub X-Hub-Signature-256 webhooks in Laravel 11/12 using $request->getContent(), hash_equals(), CSRF bypass, and async Redis queue job dispatch.
Stripe Webhook Verification in Node.js Express (express.raw() Order Fix)
Fix Stripe webhook signature mismatch in Express.js. Mount express.raw({ type: "application/json" }) before express.json() and verify with timingSafeEqual.
Slack Slash Command & Events Signature Verification in Next.js App Router
Verify Slack X-Slack-Signature (v0) and 5-minute replay timestamps in Next.js App Router using await request.text() and crypto.timingSafeEqual safely.
ASP.NET Core 8/9 Raw Body Webhook HMAC Verification (EnableBuffering Guide)
Verify Stripe, GitHub, and Shopify HMAC-SHA256 webhooks in ASP.NET Core 8/9 using EnableBuffering(), StreamReader, and FixedTimeEquals in C#.