HMAC SHA-256 Webhook Verification in Next.js App Router: Hardening Inbound Relays
HMAC SHA-256 Webhook Verification in Next.js App Router: Hardening Inbound Relays
Every public webhook endpoint is an exposed HTTP attack vector. Without cryptographic signature verification, malicious actors can forge payloads, poison CRM state databases, and launch denial-of-service replay attacks.
In enterprise environments governed by SOC 2 Type II and HIPAA standards, incoming third-party webhooks from Stripe, Meta, Twilio, or GoHighLevel must be verified cryptographically using HMAC SHA-256 before any application logic executes.
The Anatomy of an HMAC Webhook Attack
When webhook endpoints rely solely on secret query parameters (e.g., ?token=secret123), three vulnerabilities emerge:
1. Query Token Exposure: Secret tokens leak into access logs, browser history, and intermediate proxy headers.
2. Payload Tampering: Man-in-the-middle proxies can modify lead data or transaction amounts without detection.
3. Replay Attacks: A valid captured request can be re-transmitted thousands of times to exhaust backend capacity.
Implementing Cryptographic Verification in Next.js
In Next.js App Router (route.ts), signature verification must be executed against the raw, unparsed request buffer, not the deserialized JSON object:
import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
export async function POST(req: NextRequest) {
const signature = req.headers.get("x-webhook-signature");
const timestamp = req.headers.get("x-webhook-timestamp");
const rawBody = await req.text();
if (!signature || !timestamp) {
return NextResponse.json({ error: "Missing authentication headers" }, { status: 401 });
}
// Enforce 5-minute replay prevention window
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - parseInt(timestamp, 10)) > 300) {
return NextResponse.json({ error: "Timestamp drift exceeded" }, { status: 403 });
}
// Compute expected HMAC SHA-256 signature
const secret = process.env.WEBHOOK_SIGNING_SECRET!;
const expectedSignature = crypto
.createHmac("sha256", secret)
.update(${timestamp}.${rawBody})
.digest("hex");
// Constant-time comparison to prevent timing attacks
const isValid = crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
if (!isValid) {
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
}
// Enqueue verified payload to Redis / DLQ buffer
return NextResponse.json({ received: true }, { status: 200 });
}
Production Security Checkpoints
- Constant-Time Verification: Uses
crypto.timingSafeEqualto eliminate timing-side-channel analysis. - 5-Minute Replay Window: Drops requests with timestamp drift exceeding 300 seconds.
- Immediate DLQ Offload: Returns HTTP 200 within 25ms, offloading processing to asynchronous worker queues.