Securing Webhooks in Production: Signature Verification & Idempotency (Signature Verification Idempotency)
The Vulnerabilities of Public Webhook Endpoints
Webhook endpoints are publicly accessible HTTP POST routes. Without authentication and idempotency mechanisms, endpoints are vulnerable to forged payloads, man-in-the-middle attacks, and duplicate event processing.
1. Cryptographic HMAC Signature Verification
Services like Stripe, Razorpay, and GitHub sign every outgoing request payload using a shared secret key and a cryptographic hash (HMAC SHA256).
import crypto from 'crypto';
export function verifyWebhookSignature(
rawBody: Buffer,
signatureHeader: string,
secret: string
): boolean {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signatureHeader),
Buffer.from(expectedSignature)
);
}
2. Enforcing Idempotency for Event Delivery
Webhook providers guarantee at-least-once delivery, meaning your server may receive the exact same event multiple times due to network retries. To prevent double billing or duplicate records:
- Extract the unique event ID from the payload (e.g.
evt_12345). - Store processed event IDs in Redis or your database with an atomic transaction lock.
- If an incoming event ID already exists in the cache, immediately return an HTTP 200 response without re-executing logic.