Typical Webhook Signature Verification Error (Stripe + Next.js)
When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in Stripe + Next.js, your server logs an exception matching the output below:
StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
Raw Request Stream Handling & Replay Protection in Stripe + Next.js
Migrating Stripe webhook endpoints from the legacy Next.js Pages Router (which required export const config = { api: { bodyParser: false } } and manual stream buffering) to the Next.js App Router simplifies raw-body extraction dramatically; yet one line of code still breaks hundreds of deployments every week. Calling await request.json() and then JSON.stringify(body) destroys Stripe's exact byte layout and immediately triggers StripeSignatureVerificationError.
In Next.js App Router Route Handlers (app/api/webhooks/stripe/route.ts), the standard Web Fetch Request object gives you untouched raw payload bytes directly via const rawBody = await request.text(). Passing that exact string alongside request.headers.get("stripe-signature") to stripe.webhooks.constructEvent(), or computing Node crypto.createHmac("sha256", secret) with crypto.timingSafeEqual(), verifies the signature deterministically every time.
Because Node's built-in crypto module and the official Stripe SDK perform best in the Node.js runtime (and avoid Edge Runtime Node-API incompatibilities), explicitly declare export const runtime = "nodejs" and export const dynamic = "force-dynamic" inside your webhook route handler so Next.js never attempts static optimization or Edge bundling.
Watch out for Next.js middleware.ts and Vercel Deployment Protection as well: if src/middleware.ts redirects unauthenticated requests to /login or modifies request bodies, Stripe receives HTTP 307/401 instead of 200 OK. Always exclude /api/webhooks/:path* from auth middleware matchers.
Finally, remember never to prefix STRIPE_WEBHOOK_SECRET with NEXT_PUBLIC_; keep it strictly server-side, validate it via our .env Checker, and test both valid and re-serialized signatures using the interactive Web Crypto debugger above.
When operating Next.js App Router Stripe webhooks on Vercel, Cloudflare, or self-hosted Docker containers, always isolate billing mutations behind an idempotent database transaction keyed by event.id so automatic Stripe retries never grant duplicate credits or send duplicate receipt emails. Testing your live route handler with both valid raw signatures and intentionally re-serialized JSON payloads catches body-parsing regressions in CI before releasing.
Step-by-Step Stripe + Next.js Webhook Verification Setup
Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.
1Read Raw Text With await request.text() in Your Route Handler
src/app/api/webhooks/stripe/route.tsRead the raw UTF-8 body using request.text() before parsing JSON, explicitly pin runtime = "nodejs", and verify the Stripe-Signature header using Stripe's official SDK or Node crypto.timingSafeEqual.
src/app/api/webhooks/stripe/route.tstypescriptimport Stripe from 'stripe'; import { NextResponse } from 'next/server'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!); export async function POST(request: Request) { const rawBody = await request.text(); const signature = request.headers.get('stripe-signature'); const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; if (!signature || !webhookSecret) { return NextResponse.json({ error: 'Missing signature or secret' }, { status: 400 }); } let event: Stripe.Event; try { event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret); } catch (err) { const message = err instanceof Error ? err.message : 'Invalid signature'; return NextResponse.json({ error: message }, { status: 400 }); } if (event.type === 'invoice.payment_succeeded') { // Handle idempotent fulfillment here } return NextResponse.json({ received: true, id: event.id }); }2Exclude /api/webhooks From Next.js Auth Middleware
src/middleware.tsStripe requests carry no session cookie or Clerk/Auth.js token. Exempt /api/webhooks from authentication redirects in middleware.ts.
src/middleware.tstypescriptexport const config = { matcher: [ '/((?!_next/static|_next/image|favicon.ico|api/webhooks).*)', ], };3Avoid Trailing Slash 308 Redirects on Webhook URLs
next.config.tsMatch the exact URL registered in your Stripe Dashboard with your Next.js trailingSlash setting so Stripe never hits a 308 redirect.
next.config.tstypescript// If trailingSlash: false (default), register: // https://app.example.com/api/webhooks/stripe (no trailing slash)4Test Against Local Next.js Port 3000 With Stripe CLI
terminalForward events to localhost:3000 and verify 200 OK responses in both terminal and Next.js server logs.
terminalbashstripe listen --forward-to http://localhost:3000/api/webhooks/stripe stripe trigger invoice.payment_succeeded
Common Stripe + Next.js Webhook Pitfalls
Avoid these three subtle production failure modes when verifying external webhook signatures.
Using await request.json() and Re-Stringifying With JSON.stringify()
Once request.json() parses the payload into a JS object, original whitespace and formatting are permanently lost. Re-stringifying yields a different HMAC digest and always triggers StripeSignatureVerificationError.
Leaving export const config = { api: { bodyParser: false } } in App Router
That config export belonged exclusively to the legacy Pages Router and is ignored (or causes build warnings) in App Router route.ts files. Simply call await request.text() directly.
Vercel Preview Authentication Returning 401 to Stripe Webhooks
On protected Vercel preview branches, Stripe POST requests get intercepted by Vercel Authentication before reaching route.ts. Configure a Protection Bypass secret or test against an unprotected staging domain.
Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers
Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:
Audit Next.js App Router .env.local and .env.production files in your browser. Catch NEXT_PUBLIC_ secret leaks, build-time inlining bugs, and missing keys.
Generate a production Nginx reverse proxy for Next.js App Router on port 3000 with Certbot SSL, _next/static caching, streaming responses, and WebSockets.
Frequently Asked Questions
- Does Next.js App Router require disabling bodyParser for Stripe webhooks?
- No. Unlike the old Pages Router, App Router Route Handlers expose the standard Web Request API, so calling await request.text() reads the raw unparsed HTTP body out of the box.
- Can I verify Stripe webhooks in the Next.js Edge Runtime?
- Yes, using constructEventAsync() (which uses Web Crypto crypto.subtle internally), or by pinning export const runtime = "nodejs" to use standard Node crypto and database drivers.
- Why does Stripe mark my Next.js webhook as timed out on serverless hosts?
- Stripe expects a 2xx response quickly (typically within a few seconds). Avoid running slow PDF rendering or third-party email loops synchronously; enqueue background work (Inngest, Trigger.dev, SQS, or waitUntil) and return 200 immediately.
- What if I accidentally named my secret NEXT_PUBLIC_STRIPE_WEBHOOK_SECRET?
- Anyone could read your signing secret from public browser JS chunks and forge fake paid checkout events. Immediately remove NEXT_PUBLIC_, rotate the webhook secret in Stripe Dashboard, and lint your .env with our .env Checker.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)
Fix Stripe SignatureVerificationException in Laravel 11/12 using $request->getContent(), CSRF exclusion in bootstrap/app.php, hash_equals, and async queues.
Slack Slash Command & Events Signature Verification in Next.js App Router
Verify Slack X-Slack-Signature (v0) and 5-minute replay timestamps in Next.js App Router using await request.text() and crypto.timingSafeEqual safely.
Stripe Webhook Verification in Node.js Express (express.raw() Order Fix)
Fix Stripe webhook signature mismatch in Express.js. Mount express.raw({ type: "application/json" }) before express.json() and verify with timingSafeEqual.
Stripe Webhook Signature Verification in FastAPI (request.body() Guide)
Fix Stripe webhook signature errors in Python FastAPI. Read raw bytes with await request.body() before Pydantic parsing and compare via hmac.compare_digest.