Webhook HMAC-SHA256 Verifier · Stripe + Next.js

Stripe Webhook Verification in Next.js App Router (request.text() Guide)

Verify and generate Stripe + Next.js HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·Stripe-Signature

Stripe-Signature: t=1795378346,v1=199bdb9032015ddb5cb5138a2fa1120650b8baa76be7d06ba3cc3cb459f88dc1

// src/app/api/webhooks/stripe/route.ts (Next.js App Router — Node.js Runtime)
import crypto from 'node:crypto';
import { NextResponse } from 'next/server';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  // CRITICAL: Read raw text BEFORE parsing JSON so whitespace & key order stay intact
  const rawBody = await request.text();
  const secret = process.env.WEBHOOK_SECRET!;

  const sigHeader = request.headers.get('stripe-signature') ?? '';
  const items = Object.fromEntries(sigHeader.split(',').map((p) => p.split('=')));
  const timestamp = items.t ?? '';
  const v1 = items.v1 ?? '';

  if (!timestamp || Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) {
    return NextResponse.json({ error: 'Timestamp expired' }, { status: 400 });
  }

  const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
  const received = v1;

  const expectedBuf = Buffer.from(expected, 'utf8');
  const receivedBuf = Buffer.from(received, 'utf8');

  if (expectedBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(expectedBuf, receivedBuf)) {
    return NextResponse.json({ error: 'Invalid Stripe signature' }, { status: 400 });
  }

  const event = JSON.parse(rawBody);
  return NextResponse.json({ received: true, type: event.type ?? 'ok' });
}
1. Raw Body HMAC (HEX)Valid

199bdb9032015ddb5cb5138a2fa1120650b8baa76be7d06ba3cc3cb459f88dc1

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

88cd1b6a55b2ee39751c27a05bb3bf50e4d95cb75e149933dce5ea176eec88a7

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

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:

Server Exception / Webhook Delivery Log

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.

  1. 1Read Raw Text With await request.text() in Your Route Handler

    src/app/api/webhooks/stripe/route.ts

    Read 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.tstypescript
    import 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 });
    }
  2. 2Exclude /api/webhooks From Next.js Auth Middleware

    src/middleware.ts

    Stripe requests carry no session cookie or Clerk/Auth.js token. Exempt /api/webhooks from authentication redirects in middleware.ts.

    src/middleware.tstypescript
    export const config = {
      matcher: [
        '/((?!_next/static|_next/image|favicon.ico|api/webhooks).*)',
      ],
    };
  3. 3Avoid Trailing Slash 308 Redirects on Webhook URLs

    next.config.ts

    Match 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)
  4. 4Test Against Local Next.js Port 3000 With Stripe CLI

    terminal

    Forward events to localhost:3000 and verify 200 OK responses in both terminal and Next.js server logs.

    terminalbash
    stripe 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tools

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:

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.
Browse all 10 webhook guides →