Cluster 14 · Full-Stack Framework · request.text() + Edge

Next.js App Router request.text() Webhook HMAC Verifier & Replay Protection

Handle webhooks safely in Next.js App Router (`app/api/webhooks/route.ts`) using `await request.text()`, WebCrypto `crypto.subtle` (Edge & Node compatible), and replay/429 headers.

100% Browser-Side · WebCrypto crypto.subtle · Strict CSP

1. Webhook Signature & Replay-Window Inputs

crypto.subtle HMAC-SHA256
Paste an incoming signature header to run constant-time verification.
Replay-Window & Clock-Skew Gate
42s age vs 300s max
PASS: WITHIN REPLAY WINDOW
Event age 42s is within <=300s tolerance window (258s remaining). Pair with Idempotency/Delivery ID cache. (126 UTF-8 bytes · Stripe signs `${t}.${rawBody}` with HMAC-SHA256 hex and enforces a 300-second default replay window.)
Computed HTTP Signature Header
Stripe-Signature: t=1795705200,v1=1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Hex
1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Base64
HGCmh0LAU7Pw4mLiAju36SWbDbjgU6F4V6Reef9a6jk=
Drop-In WebCrypto Verifier + Replay Guard (verifyWebhook.ts)
// Strict WebCrypto Webhook Verifier + Replay Guard (Cloudflare Workers / Node 20+)
const REPLAY_TOLERANCE_SEC = 300;

function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
  return diff === 0;
}

export async function verifyWebhookRequest(request: Request, secret: string): Promise<{ ok: boolean; reason: string; rawBody: string }> {
  const rawBody = await request.text();
  const sigHeader = request.headers.get("stripe-signature") || "";
  const parts = Object.fromEntries(sigHeader.split(",").map((p) => p.split("=")));
  const ts = Number(parts.t || 0);
  const nowSec = Math.floor(Date.now() / 1000);
  if (!ts || nowSec - ts > REPLAY_TOLERANCE_SEC || ts - nowSec > 30) return { ok: false, reason: "replay_window_rejected", rawBody };
  const signedInput = `${ts}.${rawBody}`;
  const providedHex = (parts.v1 || "").toLowerCase();
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(signedInput)));
  const expectedHex = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  const ok = timingSafeEqual(enc.encode(providedHex), enc.encode(expectedHex));
  return { ok, reason: ok ? "verified" : "invalid_signature", rawBody };
}
WebhookSLA Guard · Live Check $29 WebhookSLA Guard Kit

Verify Live Webhook Replay Defense, 429 Retry-After & DLQ SLA Readiness

Run a live webhook endpoint & SLA audit on WebhookSLA Guard (webhook.runglab.dev), grab the turnkey $29 WebhookSLA Guard Kit (WebCrypto HMAC verifiers, replay-window store, RFC RateLimit-* middleware & DLQ runbooks) on Creem, or audit webhook OpenAPI specs on SpecDiff (spec.runglab.dev). Need a PayPal invoice? Email [email protected].

Webhook SLA, Signature & Retry Specification Matrix

Control / Header Production Baseline Reliability & Security Rationale
Raw Body Method await request.text() App Router Web Request API gives direct raw string access without bodyParser config hacks
Universal Crypto crypto.subtle (Edge + Node 20+) Works identically on Vercel Edge, Cloudflare Pages, and Node runtime
Replay Window 300s timestamp + delivery cache Enforce clock skew + timestamp age before trusting JSON payload
Dynamic Rendering export const dynamic = 'force-dynamic' Ensure POST webhook routes never suffer accidental static/ISR caching

Next.js App Router WebCrypto Webhook Route (app/api/webhooks/route.ts)

route.ts
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const rawBody = await request.text();
  const sig = request.headers.get("stripe-signature") || "";
  const parts = Object.fromEntries(sig.split(",").map((kv) => kv.split("=")));
  const ts = Number(parts.t || 0);
  const now = Math.floor(Date.now() / 1000);
  if (!ts || now - ts > 300 || ts - now > 30) {
    return NextResponse.json({ error: "replay_window_rejected" }, { status: 400 });
  }
  const secret = process.env.WEBHOOK_SECRET || "";
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${ts}.${rawBody}`)));
  const expected = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  const provided = (parts.v1 || "").toLowerCase();
  if (provided.length !== expected.length) {
    return NextResponse.json({ error: "invalid_signature" }, { status: 401 });
  }
  let diff = 0;
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ provided.charCodeAt(i);
  if (diff !== 0) {
    return NextResponse.json({ error: "invalid_signature" }, { status: 401 });
  }

  return NextResponse.json({ ok: true }, { status: 200 });
}

Next.js 429 RateLimit-* + Retry-After Helper

ratelimit-headers.ts
return NextResponse.json(
  { error: "rate_limited", retryAfterSec: 17 },
  {
    status: 429,
    headers: {
      "RateLimit-Policy": '"webhook-ingest";q=100;w=60',
      "RateLimit": '"webhook-ingest";r=0;t=17',
      "Retry-After": "17",
      "Cache-Control": "no-store"
    }
  }
);

Implementation Steps & Key Insights

  1. Use App Router `route.ts` with `await request.text()` instead of legacy Pages Router `bodyParser: false` stream hacks.
  2. Use `crypto.subtle` so your webhook route works seamlessly across Node.js, Vercel Edge, and Cloudflare Pages Functions.
  3. Validate timestamp freshness (`300s`) and constant-time HMAC equality before calling `JSON.parse(rawBody)`.
  4. Offload heavy Prisma/email work to an asynchronous queue so serverless cold-starts + DB locks never break provider SLAs.
  • In Next.js App Router, calling `await request.json()` consumes the body stream and discards raw formatting — always call `await request.text()` first.
  • Using Web Crypto (`crypto.subtle`) keeps your handler portable across Edge and Node runtimes without conditional imports.
  • Combine Cluster 14 with Cluster 4 (`/security-headers/nextjs/`) to lock down CSP and CORS alongside your webhook route.

Common Production Pitfalls

  • Calling `await request.json()` first and passing `JSON.stringify(body)` into HMAC verification.
  • Checking `process.env.WEBHOOK_SECRET` lazily without failing closed if the secret env var is empty.
  • Running multi-second serverless cold-start DB migrations inside the synchronous webhook handler.
Ship Faster: Audit your live endpoint on webhook.runglab.dev or grab the $29 WebhookSLA Guard Kit.

More Enterprise Webhook SLA & Signature Guides

← Back to Webhook SLA Kit Hub · WebhookSLA Guard ($29 Kit) → · SpecDiff OpenAPI Audit → · Cluster 7B: CORS & HMAC → · Cluster 9: OpenAPI OWASP →

Frequently Asked Questions

Do I need `export const config = { api: { bodyParser: false } }` in Next.js App Router?

No — that config belonged to the legacy Pages Router. In App Router `route.ts`, simply call `await request.text()` directly.

Does `crypto.subtle` work in Next.js Node.js runtime as well as Edge runtime?

Yes — Node.js 20+ exposes global `crypto.subtle` identically to Edge runtimes and browsers.

How can I audit my Next.js webhook route and OpenAPI contracts?

Test live webhook verification & SLA checks at https://webhook.runglab.dev and OpenAPI security at https://spec.runglab.dev.