Prevent spoofing and replay attacks on Next.js 15 webhook routes. Implement HMAC SHA-256 validation, raw body parsing, and constant-time comparisons. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.
Executive Summary & Key Takeaway (AEO)
Exposing unauthenticated webhook listeners to the public internet leaves backend databases vulnerable to unauthorized balance credits, fake order injections, and replay attacks. An enterprise-grade webhook handler in Next.js 15 enforces three non-negotiable security controls: cryptographic HMAC SHA-256 signature verification, raw unparsed request body buffering, and constant-time buffer comparisons (crypto.timingSafeEqual) to prevent timing side-channel attacks.
Anatomy of a Secure Webhook Handshake
[ Sender: Stripe / GitHub / WooCommerce ]
│
├── 1. Raw Payload String: {"event":"payment.succeeded", ...}
├── 2. Header: X-Webhook-Signature: t=1730000000,v1=9f8a3c...
│
▼
[ Next.js 15 Route Handler ]
│
┌────────┴───────────────────────────┐
▼ ▼
[ Check Timestamp Age (< 300s) ] [ Read Raw Buffer ]
(Mitigates Replay Attacks) │
│ ▼
└───────────────────────────▶ [ Compute Expected HMAC ]
│
▼
[ crypto.timingSafeEqual() ]
│
┌─────────────────────┴─────────────────────┐
▼ (Match: 200 OK) ▼ (Mismatch: 401 Unauthorized)
[ Enqueue Async Processing ] [ Reject & Log Threat ]
The Common Pitfall: JSON Body Parsing Alteration
Never run await req.json() before signature verification. JSON parsers re-order keys and strip insignificant whitespace, altering the exact byte representation that the sender signed. Always buffer raw bytes with await req.text().
Production Route Handler Implementation
// app/api/webhooks/incoming/route.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';
const WEBHOOK_SECRET = process.env.WEBHOOK_SIGNING_SECRET!;
const MAX_TOLERANCE_SECONDS = 300; // 5-minute replay window
export async function POST(req: Request) {
try {
// 1. Extract signature headers
const signatureHeader = req.headers.get('x-signature');
const timestampHeader = req.headers.get('x-timestamp');
if (!signatureHeader || !timestampHeader) {
return NextResponse.json(
{ error: 'Missing security headers' },
{ status: 401 }
);
}
// 2. Prevent Replay Attacks: Validate timestamp drift
const requestTimestamp = parseInt(timestampHeader, 10);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (isNaN(requestTimestamp) || Math.abs(currentTimestamp - requestTimestamp) > MAX_TOLERANCE_SECONDS) {
return NextResponse.json(
{ error: 'Webhook timestamp outside tolerance window' },
{ status: 401 }
);
}
// 3. Read Raw Request Body as text
const rawBody = await req.text();
// 4. Compute expected cryptographic HMAC
const signedPayload = `${timestampHeader}.${rawBody}`;
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(signedPayload, 'utf8')
.digest('hex');
// 5. Constant-time comparison to prevent timing attacks
const signatureBuffer = Buffer.from(signatureHeader, 'hex');
const expectedBuffer = Buffer.from(expectedSignature, 'hex');
if (
signatureBuffer.length !== expectedBuffer.length ||
!crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
) {
return NextResponse.json(
{ error: 'Invalid HMAC signature' },
{ status: 401 }
);
}
// 6. Safe to parse verified JSON
const payload = JSON.parse(rawBody);
// Hand off to internal asynchronous queue
console.log(`[Webhook Verified] Event: ${payload.event}`);
return NextResponse.json({ received: true });
} catch (err: any) {
console.error('Webhook processing failure:', err);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
Security Audit Checklist
| Attack Vector | Defense Mechanism | Implemented? |
|---|---|---|
| Payload Spoofing | HMAC SHA-256 verification | Yes (crypto.createHmac) |
| Replay Attack | Timestamp age tolerance (under 300s) | Yes (MAX_TOLERANCE_SECONDS) |
| Timing Side-Channel | crypto.timingSafeEqual | Yes (Buffer comparison) |
| Serialization Drift | Verifying raw text before JSON parse | Yes (await req.text()) |
Mission-Critical Webhooks by Dev Pattern Labs
Dev Pattern Labs engineers secure enterprise webhooks, payment infrastructures, and autonomous automation pipelines. Discover our Automation Consulting or launch a 14-Day Delivery Sprint.
Companion Architecture Tutorials
Written by Dev Pattern LabsCore Engineering
Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.
Recommended Companion Articles

n8n Production Error Handling: Retries, Dead-Letter Queues & Alerts
Build bulletproof enterprise workflows in n8n. Configure automatic node retries, PostgreSQL dead-letter queues, and real-time alert notifications.

Automating WooCommerce Order Fulfillment with n8n and Webhooks
Connect WooCommerce order webhooks to self-hosted n8n. Automate real-time Slack alerts, PDF invoices, and Google Sheets sync with zero monthly SaaS fees.

Next.js 15 Stripe Subscriptions & Billing Customer Portal Guide
Build a SaaS subscription engine in Next.js 15 with Stripe Billing, Checkout Sessions, Customer Portal redirects, and webhook lifecycle event handlers.
