Verify GitHub webhooks
GitHub signs a delivery when the webhook has a secret, so you can confirm that it came from GitHub and wasn't changed on the way. The X-Hub-Signature-256 header holds sha256= followed by an HMAC-SHA256 hex digest of the request body, keyed with that secret. With no secret set, GitHub sends no signature. GitHub's Octokit SDK can verify one for you with @octokit/webhooks.
The facts
{raw body} The request body as sent, with no timestamp or other data added.
X-Hub-Signature HMAC-SHA1 hex digest of the raw body with the same secret, sent only for compatibility with existing integrations.
GitHub webhook secret
You choose the secret yourself when you create or edit a webhook, so GitHub doesn't generate one or show you one to copy. It isn't an API token. Keep it in an environment variable, not in source code.
- Repository and organization webhooks: type it in the Secret field when you create the webhook, or edit the webhook's settings to add or change it.
- GitHub Apps: type it under Webhook secret on the GitHub App registration page. An app has one webhook, so it has one secret.
- Format: any random string with high entropy. GitHub sets no format or prefix.
- One per webhook: each webhook has its own setting, so with several webhooks you need the matching secret for each.
- Lost or changed: if you don't know the value, set a new one in the webhook's settings. GitHub's docs describe no period when the old and new secrets both work.
Source: GitHub docs ↗
Code
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify GitHub webhook signature
* @param {Buffer} rawBody - Raw request body
* @param {string} signatureHeader - X-Hub-Signature-256 header value
* @param {string} secret - GitHub webhook secret
* @returns {boolean} - Whether signature is valid
*/
function verifyGitHubWebhook(rawBody, signatureHeader, secret) {
if (!signatureHeader) {
return false;
}
// Extract the signature from the header (format: sha256=<hex>)
const signature = signatureHeader.replace('sha256=', '');
// Compute expected signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
// Use timing-safe comparison to prevent timing attacks
try {
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedSignature, 'hex')
);
} catch {
return false;
}
}
// GitHub webhook endpoint - must use raw body for signature verification
app.post('/webhooks/github',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['x-hub-signature-256'];
const event = req.headers['x-github-event'];
const deliveryId = req.headers['x-github-delivery'];
// Verify webhook signature
if (!verifyGitHubWebhook(req.body, signature, process.env.GITHUB_WEBHOOK_SECRET)) {
console.error('Webhook signature verification failed');
return res.status(401).send('Invalid signature');
}
// Parse the payload after verification
const payload = JSON.parse(req.body.toString());
const action = payload.action;
console.log(`Received ${event} event (delivery: ${deliveryId})`);
// Handle the event based on type
switch (event) {
case 'ping':
console.log('Ping received:', payload.zen);
break;
case 'push':
console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
// Your code: Trigger CI/CD, run tests, deploy, etc.
break;
case 'pull_request':
console.log(`PR #${payload.number} ${action}:`, payload.pull_request.title);
// Your code: Run checks, notify reviewers, auto-merge, etc.
break;
case 'issues':
console.log(`Issue #${payload.issue.number} ${action}:`, payload.issue.title);
// Your code: Triage, label, notify, etc.
break;
case 'issue_comment':
console.log(`Comment on #${payload.issue.number} by ${payload.comment.user.login}`);
// Your code: Bot responses, command parsing, etc.
break;
case 'release':
console.log(`Release ${action}:`, payload.release.tag_name);
// Your code: Deploy, notify, update changelog, etc.
break;
case 'create':
console.log(`Created ${payload.ref_type}:`, payload.ref);
// Your code: Environment setup, branch protection, etc.
break;
case 'delete':
console.log(`Deleted ${payload.ref_type}:`, payload.ref);
// Your code: Cleanup, archive, etc.
break;
case 'workflow_run':
console.log(`Workflow "${payload.workflow_run.name}" ${payload.workflow_run.conclusion}`);
// Your code: Post-CI automation, notifications, etc.
break;
default:
console.log(`Unhandled event: ${event}`);
}
// Return 200 to acknowledge receipt
res.status(200).send('OK');
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = { app, verifyGitHubWebhook };
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/github`);
});
} import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify GitHub webhook signature
*/
function verifyGitHubWebhook(rawBody: string, signatureHeader: string | null, secret: string): boolean {
if (!signatureHeader) {
return false;
}
// Extract the signature from the header (format: sha256=<hex>)
const signature = signatureHeader.replace('sha256=', '');
// Compute expected signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
// Use timing-safe comparison to prevent timing attacks
try {
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedSignature, 'hex')
);
} catch {
return false;
}
}
export async function POST(request: NextRequest) {
// Get the raw body for signature verification
const body = await request.text();
const signature = request.headers.get('x-hub-signature-256');
const event = request.headers.get('x-github-event');
const deliveryId = request.headers.get('x-github-delivery');
// Verify webhook signature
if (!verifyGitHubWebhook(body, signature, process.env.GITHUB_WEBHOOK_SECRET!)) {
console.error('Webhook signature verification failed');
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 401 }
);
}
// Parse the payload after verification
const payload = JSON.parse(body);
const action = payload.action;
console.log(`Received ${event} event (delivery: ${deliveryId})`);
// Handle the event based on type
switch (event) {
case 'ping':
console.log('Ping received:', payload.zen);
break;
case 'push':
console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
// Your code: Trigger CI/CD, run tests, deploy, etc.
break;
case 'pull_request':
console.log(`PR #${payload.number} ${action}:`, payload.pull_request.title);
// Your code: Run checks, notify reviewers, auto-merge, etc.
break;
case 'issues':
console.log(`Issue #${payload.issue.number} ${action}:`, payload.issue.title);
// Your code: Triage, label, notify, etc.
break;
case 'issue_comment':
console.log(`Comment on #${payload.issue.number} by ${payload.comment.user.login}`);
// Your code: Bot responses, command parsing, etc.
break;
case 'release':
console.log(`Release ${action}:`, payload.release.tag_name);
// Your code: Deploy, notify, update changelog, etc.
break;
case 'workflow_run':
console.log(`Workflow "${payload.workflow_run.name}" ${payload.workflow_run.conclusion}`);
// Your code: Post-CI automation, notifications, etc.
break;
default:
console.log(`Unhandled event: ${event}`);
}
// Return 200 to acknowledge receipt
return NextResponse.json({ received: true });
} import os
import hmac
import hashlib
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
load_dotenv()
app = FastAPI()
github_secret = os.environ.get("GITHUB_WEBHOOK_SECRET")
def verify_github_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
"""Verify GitHub webhook signature."""
if not signature_header:
return False
# Extract the signature from the header (format: sha256=<hex>)
signature = signature_header.replace("sha256=", "")
# Compute expected signature
expected_signature = hmac.new(
secret.encode("utf-8"),
raw_body,
hashlib.sha256
).hexdigest()
# Use timing-safe comparison
return hmac.compare_digest(signature, expected_signature)
@app.post("/webhooks/github")
async def github_webhook(request: Request):
# Get the raw body for signature verification
raw_body = await request.body()
signature_header = request.headers.get("x-hub-signature-256")
event = request.headers.get("x-github-event")
delivery_id = request.headers.get("x-github-delivery")
# Verify webhook signature
if not verify_github_webhook(raw_body, signature_header, github_secret):
raise HTTPException(status_code=401, detail="Invalid signature")
# Parse the payload after verification
payload = json.loads(raw_body)
action = payload.get("action")
print(f"Received {event} event (delivery: {delivery_id})")
# Handle the event based on type
if event == "ping":
print(f"Ping received: {payload.get('zen')}")
elif event == "push":
head_commit = payload.get("head_commit", {})
print(f"Push to {payload['ref']}: {head_commit.get('message')}")
# Your code: Trigger CI/CD, run tests, deploy, etc.
elif event == "pull_request":
pr = payload["pull_request"]
print(f"PR #{payload['number']} {action}: {pr['title']}")
# Your code: Run checks, notify reviewers, auto-merge, etc.
elif event == "issues":
issue = payload["issue"]
print(f"Issue #{issue['number']} {action}: {issue['title']}")
# Your code: Triage, label, notify, etc.
elif event == "issue_comment":
issue = payload["issue"]
comment = payload["comment"]
print(f"Comment on #{issue['number']} by {comment['user']['login']}")
# Your code: Bot responses, command parsing, etc.
elif event == "release":
release = payload["release"]
print(f"Release {action}: {release['tag_name']}")
# Your code: Deploy, notify, update changelog, etc.
elif event == "workflow_run":
workflow_run = payload["workflow_run"]
print(f"Workflow \"{workflow_run['name']}\" {workflow_run['conclusion']}")
# Your code: Post-CI automation, notifications, etc.
else:
print(f"Unhandled event: {event}")
# Return 200 to acknowledge receipt
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=3000) Or install the GitHub webhooks skill:
npx skills add hookdeck/webhook-skills --skill github-webhooks
Common failures
No secret on the webhook
GitHub only sends X-Hub-Signature-256 if the webhook has a secret. If the header is missing, set one in the webhook's settings.
Body changed before verification
The signature covers the body as sent. Body parsers, proxies and load balancers that alter it break the match, and on the form content type you verify the encoded body, not the JSON inside it.
Wrong header or algorithm
X-Hub-Signature-256 uses HMAC-SHA256 and the legacy X-Hub-Signature uses HMAC-SHA1. Pair each header with its own algorithm, and remember the value starts with sha256=.
Wrong secret or encoding
Use the secret of this webhook, and set a new one if you don't know its value. If your server sets a character encoding, handle the payload as UTF-8.
Let Event Gateway verify GitHub signatures.
Event Gateway verifies the signature on each GitHub delivery before it reaches your service, then queues it and retries failures on your schedule.