# Stripe Webhook Next.js: Verify Signatures, Dedupe, Queue

Build a Stripe webhook handler in Next.js App Router that verifies the signature on the raw body, ignores duplicate events and pushes the real work to a BullMQ queue.

By Waseem Anjum · Published 2026-11-17 · https://fabwaseem.com/blog/stripe-webhook-nextjs

> **TL;DR:** In the App Router, read the body with req.text(), pass it with the Stripe-Signature header and your whsec_ secret to stripe.webhooks.constructEvent, then enqueue the event in BullMQ with event.id as the jobId and return 200 straight away. A worker does the real work and must be safe to run twice.

A reliable Stripe webhook in Next.js does four things in order: read the raw request body, verify the `Stripe-Signature` header, hand the event to a queue and answer `200` quickly. Everything slow happens later in a worker that can safely run the same event twice. This guide builds that setup with a Next.js App Router route handler, the `stripe` Node SDK and BullMQ. If you search for a Stripe webhook Next.js setup that survives retries, duplicates and signature errors, this is the pattern.

Stripe's own documentation is the source for the rules below: it requires the raw body for verification, recommends returning a `2xx` before any complex logic and recommends processing events with an asynchronous queue.

## How should a Stripe webhook request flow through Next.js?

The route handler should stay thin. It verifies, enqueues and answers. The worker owns the business logic.

![Flow diagram: Stripe sends a POST to the Next.js route handler, which verifies the signature, enqueues the event in BullMQ using event.id as the jobId, and a worker processes it idempotently](https://res.cloudinary.com/wasicloudinary/image/upload/v1794888412/fabwaseem/projects/fve2px50ppq0ssrlookr.jpg)

A bad signature gets a `400`. A valid event that is safely queued gets a `200`. If enqueueing fails, return a `500` so Stripe retries instead of losing the event.

## How do I create the Stripe webhook route in Next.js?

Create `app/api/webhooks/stripe/route.ts`. The App Router does not parse the request body for you, so `req.text()` returns exactly the string Stripe sent. The official [stripe-node Next.js example](https://github.com/stripe/stripe-node/blob/master/examples/webhook-signing/nextjs/app/api/webhooks/route.ts) follows the same pattern.

```ts
// app/api/webhooks/stripe/route.ts
import { NextResponse } from "next/server"
import Stripe from "stripe"
import { stripeQueue } from "@/lib/queue"

export const runtime = "nodejs"

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET!

const HANDLED = new Set([
  "checkout.session.completed",
  "checkout.session.async_payment_succeeded",
  "checkout.session.async_payment_failed",
])

export async function POST(req: Request) {
  const signature = req.headers.get("stripe-signature")
  if (!signature) {
    return NextResponse.json({ error: "Missing signature" }, { status: 400 })
  }

  // Raw body: do not call req.json() before verifying.
  const body = await req.text()

  let event: Stripe.Event
  try {
    event = stripe.webhooks.constructEvent(body, signature, endpointSecret)
  } catch {
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 })
  }

  if (!HANDLED.has(event.type)) {
    return NextResponse.json({ received: true })
  }

  try {
    await stripeQueue.add(event.type, event, {
      jobId: event.id,
      attempts: 5,
      backoff: { type: "exponential", delay: 2000 },
      removeOnComplete: { age: 60 * 60 * 24 * 7 },
    })
  } catch {
    // Not queued: a non-2xx makes Stripe retry the delivery.
    return NextResponse.json({ error: "Queue unavailable" }, { status: 500 })
  }

  return NextResponse.json({ received: true })
}
```

`constructEvent` takes the three inputs Stripe documents: the raw request body, the `Stripe-Signature` header value and the endpoint secret. The SDK checks the `v1` HMAC-SHA256 signature and rejects events whose timestamp is outside the default 5 minute tolerance. Setting `runtime = "nodejs"` keeps the synchronous `constructEvent` on Node's crypto module; the SDK also offers `constructEventAsync` for runtimes without it.

Only subscribe the endpoint to the event types you need. Stripe advises against listening to everything. The three Checkout events above come from Stripe's [Checkout fulfillment guide](https://docs.stripe.com/checkout/fulfillment): it tells you to handle `checkout.session.completed` and `checkout.session.async_payment_succeeded`, and suggests also handling `checkout.session.async_payment_failed`.

## How do I deduplicate Stripe webhook events?

Stripe's documentation says endpoints might occasionally receive the same event more than once. It recommends logging the event IDs you have processed and skipping logged ones. In some cases two separate Event objects are generated; for those, compare the ID of `data.object` together with `event.type`.

Using `event.id` as the BullMQ `jobId` gives you the first layer for free. BullMQ [ignores a job whose id already exists](https://docs.bullmq.io/guide/jobs/job-ids) in the queue, so a duplicate delivery adds nothing. Three caveats matter here:

- Once a job is removed, for example through `removeOnComplete`, its id can be reused. That is why the route above keeps completed jobs for seven days, longer than Stripe's three day retry window. A manual resend after that point is caught only by the idempotent worker.
- BullMQ keeps failed jobs unless you configure `removeOnFail`. A job that used all its attempts stays in the failed set under the same `evt_` id, so a resend of that event is ignored as a duplicate. Retry it from the queue, or set `removeOnFail` if you want a resend to run it again.
- Ids containing `:` are split into separate values and digit-only ids throw. Stripe event ids such as `evt_...` are safe.

The second layer is an idempotent worker, covered next. If you would rather not run Redis, the same pattern works with a Postgres queue; see [pg-boss vs BullMQ](https://fabwaseem.com/blog/postgres-job-queue-pg-boss-vs-bullmq).

## How do I process Stripe events in a BullMQ worker?

Use two Redis connections in two modules. The producer side, used inside the request, should fail fast when Redis is unreachable so the route can answer `500` instead of hanging. BullMQ workers need `maxRetriesPerRequest: null` on their own connection.

```ts
// lib/queue.ts (used by the Next.js route)
import { Queue } from "bullmq"
import IORedis from "ioredis"

const producerConnection = new IORedis(process.env.REDIS_URL!, {
  enableOfflineQueue: false, // reject immediately when Redis is down
})

export const stripeQueue = new Queue("stripe-events", {
  connection: producerConnection,
})
```

```ts
// lib/worker-connection.ts (used only by the worker process)
import IORedis from "ioredis"

export const workerConnection = new IORedis(process.env.REDIS_URL!, {
  maxRetriesPerRequest: null, // required by BullMQ workers
})
```

Run the worker as a separate Node process, not inside the Next.js server:

```ts
// worker/stripe.ts
import { Worker } from "bullmq"
import type Stripe from "stripe"
import { workerConnection } from "../lib/worker-connection"
import { prisma } from "../lib/prisma"

const worker = new Worker(
  "stripe-events",
  async (job) => {
    const event = job.data as Stripe.Event
    const session = event.data.object as Stripe.Checkout.Session

    switch (event.type) {
      case "checkout.session.completed":
      case "checkout.session.async_payment_succeeded": {
        // Delayed payment methods complete the session before the money arrives.
        if (session.payment_status === "unpaid") break

        const res = await prisma.order.updateMany({
          where: { stripeSessionId: session.id },
          data: { status: "PAID" }, // same result when run twice
        })
        // Order row not written yet: throw so BullMQ retries with backoff.
        if (res.count === 0) throw new Error(`Order for ${session.id} not found`)
        break
      }
      case "checkout.session.async_payment_failed": {
        await prisma.order.updateMany({
          // Never overwrite PAID with a late failure event.
          where: { stripeSessionId: session.id, status: { not: "PAID" } },
          data: { status: "FAILED" },
        })
        break
      }
    }
  },
  { connection: workerConnection, concurrency: 5 },
)

worker.on("failed", (job, err) => console.error("stripe job failed", job?.id, err))
worker.on("error", (err) => console.error("stripe worker error", err))
```

The `payment_status` check matters because Checkout sessions paid with delayed methods fire `checkout.session.completed` before the money arrives. Stripe's fulfillment guide skips only the `unpaid` state, so a session with `no_payment_required` (a 100% coupon, for example) still gets fulfilled. For delayed methods, `checkout.session.async_payment_succeeded` marks the order paid later, and `checkout.session.async_payment_failed` marks it failed. A declined card on a normal Checkout attempt is not a failure of the session, because the customer can retry, so this guide does not react to `payment_intent.payment_failed`.

Write handlers so that running them twice has the same result as running them once: set a status instead of incrementing a counter, upsert instead of insert, and put a unique constraint on any row you create per event. Stripe also states that it does not guarantee event order, and snapshot events record `created` in seconds, so distinct events can share a timestamp. Do not use `created` to decide order or whether you processed something. That is why the failure branch above refuses to overwrite a paid order. For anything critical, retrieve the Checkout Session from the Stripe API inside the worker instead of trusting the payload, which is what Stripe's fulfillment example does. For a fuller queue-based pipeline see the [AI automation pipeline with BullMQ](https://fabwaseem.com/blog/ai-automation-pipeline-nodejs-bullmq) post.

## Why does Stripe webhook signature verification fail?

The classic error is:

```text
Webhook signature verification failed. Err: No signatures found matching the expected signature for payload.
```

Stripe says at least one of the three inputs is wrong.

![Checklist of three causes of Stripe webhook signature failures: modified raw body, wrong whsec secret for the endpoint, and a misread Stripe-Signature header](https://res.cloudinary.com/wasicloudinary/image/upload/v1794888415/fabwaseem/projects/eyxxmtxxf568kp3rugkc.jpg)

1. **The body was modified.** The body must be the exact string Stripe sent. Parsing it with `req.json()` and re-serialising changes key order, whitespace or encoding, and verification fails. In Next.js App Router, use `req.text()`. In the Pages Router, disable `bodyParser` and read the buffer. In Express, mount the webhook route before `express.json()`.
2. **The secret is for a different endpoint.** The secret printed by `stripe listen` differs from the secret of a Dashboard endpoint, and test and live mode secrets differ too. All start with `whsec_`. Trim stray whitespace from the environment variable.
3. **The header was read wrongly.** The header looks like `t=...,v1=...`. Your code must accept unknown entries and not depend on their order or count. During a secret roll there can be several `v1` entries.

The optional `payload` debug entry in the header is a suffix of the SHA-256 of the exact body Stripe signed, which helps you spot a modified body. It is unsigned, so never use it to authenticate a request.

## How do I test a Stripe webhook locally?

Use the Stripe CLI to forward events to your dev server:

```bash
stripe listen --forward-to localhost:3000/api/webhooks/stripe
```

Copy the `whsec_` secret it prints into `STRIPE_WEBHOOK_SECRET`, restart the dev server and trigger an event:

```bash
stripe trigger checkout.session.completed
```

If the endpoint was down, you can replay events with `stripe events resend <event_id> --webhook-endpoint=<endpoint_id>` within 30 days. The Dashboard's Resend button works for 15 days. A manual resend does not cancel Stripe's automatic retries, so your dedupe logic must handle the extra delivery.

## Snapshot or thin events: which should I handle?

This guide uses snapshot events, where the payload carries the object as it was at event time and you verify with `constructEvent`. Stripe's current docs recommend thin events for new integrations, which you verify with `parseEventNotification` and enrich with `fetchRelatedObject()`. Thin events need a separate endpoint and are registered as a separate event destination. The raw body, fast `2xx` and idempotency rules are identical for both. Pick snapshot when you need the full object or `previous_attributes` without another API call.

## What else should a production webhook endpoint do?

- Accept requests only from Stripe's published IP addresses in addition to checking signatures.
- Roll the signing secret periodically. Stripe lets the old secret stay active for up to 7 days while you deploy the new one.
- Keep the endpoint publicly reachable over HTTPS (TLS 1.2 or higher). Redirects count as failures, so register the final URL.
- Log the event ID and type on every request so you can match your logs with the Dashboard's Event deliveries tab.
- If you secure other routes with a proxy or auth layer, exclude the webhook path from it. The route authenticates itself with the signature. For API design patterns around this, see the [secure NestJS and Prisma API starter](https://fabwaseem.com/blog/secure-nestjs-prisma-api-starter), and for when to prefer route handlers over server actions, [Server Actions vs Route Handlers](https://fabwaseem.com/blog/server-actions-vs-route-handlers).

## Key takeaways

- Read `await req.text()` and verify with `constructEvent` before parsing anything.
- Answer `2xx` fast; do the real work in a queue worker.
- Use `event.id` as the BullMQ `jobId` and keep completed jobs longer than the retry window.
- Make workers idempotent and never depend on event order.
- Debug failed signatures by checking the body, the endpoint secret and the header, in that order.

Sources: [Stripe webhooks](https://docs.stripe.com/webhooks), [Resolve webhook errors](https://docs.stripe.com/events/manage-webhook-endpoints), [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment), [Stripe CLI listen](https://docs.stripe.com/cli/listen) and [BullMQ job ids](https://docs.bullmq.io/guide/jobs/job-ids).

## Questions

### How do I get the raw body for a Stripe webhook in Next.js App Router?

Call await req.text() in the route handler before anything else. The App Router does not parse the body for you, so the string you get is exactly what Stripe sent. Pass it to stripe.webhooks.constructEvent and only then work with the parsed event.

### Why do I get 'No signatures found matching the expected signature for payload'?

At least one of the three inputs is wrong: the body was modified before verification, the secret belongs to a different endpoint (the CLI and the Dashboard print different whsec_ secrets), or the Stripe-Signature header was read incorrectly.

### Does Stripe send the same webhook event twice?

It can. Stripe's docs say endpoints might occasionally receive the same event more than once, and in some cases two separate Event objects are generated. Track event IDs, and for the second case compare data.object.id together with event.type.

### How fast must a Stripe webhook endpoint respond?

Return a 2xx before any complex logic. Stripe lists a timeout as a delivery failure, so do the slow work in a queue worker instead of inside the request.

### How long does Stripe retry failed webhooks?

In live mode Stripe retries for up to three days with exponential backoff. Events created in a sandbox are retried three times over a few hours.

### How do I test a Stripe webhook locally?

Run stripe listen --forward-to localhost:3000/api/webhooks/stripe, copy the whsec_ secret it prints into STRIPE_WEBHOOK_SECRET, then fire events with stripe trigger checkout.session.completed.
