Skip to main content

Webhook Handler Example

Process incoming webhooks from external services.

Basic Webhook Handler

export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' })
}

const { event, data } = req.body
console.log('Webhook received:', { event, timestamp: new Date().toISOString() })

res.status(200).json({
success: true,
message: 'Webhook received',
eventId: crypto.randomUUID()
})
}

GitHub Webhook (HMAC verification)

import crypto from 'crypto'

function verifyGitHubSignature(payload, signature, secret) {
const hmac = crypto.createHmac('sha256', secret)
const digest = 'sha256=' + hmac.update(payload).digest('hex')
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest))
}

export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' })
}

const signature = req.headers['x-hub-signature-256']
const secret = process.env.GITHUB_WEBHOOK_SECRET

if (!signature || !verifyGitHubSignature(JSON.stringify(req.body), signature, secret)) {
return res.status(401).json({ error: 'Invalid signature' })
}

const { action, repository } = req.body
res.json({ success: true, action, repo: repository?.full_name })
}