API Developmentintermediate
Create webhook endpoint with signature verification
Webhook Handler
Create webhook endpoint with signature verification
Create a webhook endpoint with signature verification.
Instructions
import crypto from 'crypto';
export async function POST(req: Request) {
const body = await req.text(); // raw body for signature verification
const signature = req.headers.get('x-webhook-signature');
// 1. Verify signature
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET!)
.update(body)
.digest('hex');
if (!signature || !crypto.timingSafeEqual(
Buffer.from(signature), Buffer.from(expected)
)) {
return new Response('Invalid signature', { status: 401 });
}
// 2. Parse and route by event type
const event = JSON.parse(body);
switch (event.type) {
case 'order.created':
await handleOrderCreated(event.data);
break;
case 'payment.completed':
await handlePaymentCompleted(event.data);
break;
default:
console.log('Unhandled webhook event:', event.type);
}
// 3. Return 200 quickly — do heavy work async
return new Response('OK', { status: 200 });
}
Rules
- Always verify signatures using timing-safe comparison
- Return 200 immediately — queue heavy processing
- Make handlers idempotent (same event delivered twice = same result)
- Store event ID to deduplicate:
if (await isProcessed(event.id)) return; - Log all received webhooks for debugging