Skip to main content
Tutorials

Stripe webhooks in Next.js 16 App Router: signature, raw body and duplicate events

A Stripe webhook in the App Router that verifies the signature on the raw body, survives retries without double payments and doesn't depend on event order.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

Stripe Checkout is the easy part. The user pays, Stripe shows a success page and you redirect them to /dashboard?success=1. What actually decides whether that person gets what they paid for is something else: the webhook Stripe sends to your server a few seconds later, which your app has to receive, verify and store without getting it wrong.

In this post we build that endpoint in Next.js 16 with the App Router and Prisma, and we deal with the three failures we see over and over: the signature that never validates, the payment that gets saved twice, and the subscription stuck in a stale state because events arrived out of order.

The minimal endpoint that works

In the App Router a webhook is a route handler with a POST. The first thing to do is read the body exactly as it arrived, as text, before anything touches it:

// src/app/api/webhooks/stripe/route.ts
import Stripe from 'stripe';

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

export async function POST(req: Request) {
  const body = await req.text();
  const signature = req.headers.get('stripe-signature');

  if (!signature) {
    return new Response('Missing signature', { status: 400 });
  }

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }

  await handleStripeEvent(event);
  return Response.json({ received: true });
}

If you're coming from the Pages Router, you'll remember export const config = { api: { bodyParser: false } }. You don't need it in the App Router: the handler gets a standard Request and you decide how to read the body.

Why the signature fails

Stripe's docs are blunt about it: verification needs the raw body, and any manipulation makes it fail. This is the classic mistake:

// ❌ The signature no longer matches
const json = await req.json();
stripe.webhooks.constructEvent(JSON.stringify(json), signature, secret);

JSON.stringify doesn't give you back the bytes Stripe sent. Whitespace, the order of some keys or character escaping change, and the HMAC computed over that text no longer matches the one in the header. With req.text() (or Buffer.from(await req.arrayBuffer())) you verify exactly what arrived.

Two other causes are harder to track down:

  • The wrong secret. The whsec_... that stripe listen prints locally is not the one the dashboard gives you for the production endpoint. Copy one into the other environment and no signature will ever validate.
  • The server clock. Stripe's libraries reject, by default, events whose timestamp is more than five minutes away from the current time. A VPS with a drifting clock will reject legitimate webhooks. Stripe recommends syncing with NTP and warns that setting the tolerance to 0 disables the check entirely.

What your proxy shouldn't touch

Tutorials skip this because most of them are written on an empty project. In a real app, proxy.ts (what used to be middleware.ts before Next.js 16) usually has rules for the whole API: a rate limit, an Origin check against CSRF, locale redirects.

Stripe calls your webhook server to server. It sends no Origin or Referer header, and no cookies. If your proxy rejects POST requests to /api/* that arrive without Origin, the webhook gets a 403 in production while it works fine locally (because in development that check is usually relaxed). It's the kind of bug you don't see until a customer writes in saying they paid and have no access.

The rule is simple: webhook routes authenticate with their signature, so they're excluded from the Origin check. The rate limit can stay, with generous headroom, because a bulk resend from the Stripe dashboard is legitimate traffic.

// src/proxy.ts (excerpt)
const ORIGIN_CHECK_BYPASS = ['/api/webhooks/'];

if (isApiRoute && request.method !== 'GET') {
  const bypass = ORIGIN_CHECK_BYPASS.some((p) => pathname.startsWith(p));
  if (!bypass) {
    const originError = validateOrigin(request);
    if (originError) return originError;
  }
}

Stripe will send the same event more than once

Stripe retries any delivery that doesn't get a 2xx. In live mode it keeps going for up to three days with exponential backoff; in the test environment, three times over a few hours. It also warns that an endpoint may occasionally receive the same event twice even after responding successfully.

If your handler does a bare db.payment.create(), the second attempt fails on the unique constraint (Prisma's P2002) or, worse, creates a second row if you don't have that constraint. In the first case you return an error, Stripe retries, it fails again, and so on for three days.

There are two ways to protect yourself, and you want both.

Idempotent writes. Everything you store from an event goes through an upsert on a Stripe identifier with a unique index:

await db.payment.upsert({
  where: { provider_paymentId: { provider: 'STRIPE', paymentId: invoice.id } },
  update: { status: 'succeeded' },
  create: {
    provider: 'STRIPE',
    paymentId: invoice.id,
    amount: invoice.amount_paid,
    currency: invoice.currency,
    status: 'succeeded',
  },
});

A log of processed events. Stripe recommends storing the event.id and skipping events you've already handled. The key is doing it in the same transaction as the work. If you record the id first and the processing fails afterwards, the retry skips an event that was never applied.

model StripeEvent {
  id        String   @id // evt_...
  type      String
  createdAt DateTime @default(now())
}
import { Prisma } from '@/generated/prisma/client';

async function handleStripeEvent(event: Stripe.Event) {
  try {
    await db.$transaction(async (tx) => {
      await tx.stripeEvent.create({ data: { id: event.id, type: event.type } });
      await applyEvent(tx, event); // every write goes through `tx`
    });
  } catch (error) {
    if (
      error instanceof Prisma.PrismaClientKnownRequestError &&
      error.code === 'P2002'
    ) {
      return; // already processed: return 200 and Stripe stops retrying
    }
    throw error;
  }
}

If applyEvent throws, the transaction also rolls back the event create, the route handler returns a 500 and Stripe retries later. That's exactly what we want.

Event order is not guaranteed

A new subscription fires several events at almost the same time: customer.subscription.created, invoice.paid, checkout.session.completed… Stripe doesn't guarantee they reach you in that order, and it also advises against sorting them by the created field, which has one-second resolution and is shared by several events.

The typical bug is a customer.subscription.updated that arrives before created, finds an empty table and does nothing. Or the other way round: an old updated that shows up late and overwrites the good state.

The approach with the fewest surprises is to treat the event as a notice that something changed and ask the API for the truth. For subscriptions, we fetch the current state before opening the transaction (an HTTP call inside a Prisma interactive transaction keeps it open, and its default timeout is five seconds) and store that:

// Outside the transaction
const sub =
  event.type.startsWith('customer.subscription.')
    ? await stripe.subscriptions.retrieve((event.data.object as Stripe.Subscription).id)
    : null;

// Inside the transaction, from applyEvent
async function syncSubscription(tx: Prisma.TransactionClient, sub: Stripe.Subscription) {
  const item = sub.items.data[0];
  if (!item) return;

  const data = {
    status: sub.status,
    priceId: item.price.id,
    currentPeriodEnd: new Date(item.current_period_end * 1000),
    cancelAtPeriodEnd: sub.cancel_at_period_end,
  };

  await tx.subscription.upsert({
    where: { subscriptionId: sub.id },
    update: data,
    create: { subscriptionId: sub.id, customerId: sub.customer as string, ...data },
  });
}

It doesn't matter whether created or updated arrives first, or both at once: both end up storing whatever Stripe has at that moment. It costs one API call per event, which a small SaaS won't notice.

Note the item.current_period_end. Since API version 2025-03-31.basil, current_period_start and current_period_end moved from the subscription to each of its items. A lot of code copied from older tutorials reads subscription.current_period_end and gets undefined.

Respond fast, process later if you need to

Stripe asks you to return a 2xx before any logic that might take a while. In practice, two Postgres writes and one API call fit comfortably. What doesn't fit is sending the welcome email, generating a PDF invoice or calling three external services inside the handler.

For that, the webhook stores the minimum (the payment, the subscription) and hands the rest to a separate process: a queue, a cron job that picks up pending rows or, in the simplest case, a function you fire without awaiting its result. What matters is that a failed email doesn't make Stripe send the payment again.

Which events to listen to for a subscription

These cover the full lifecycle of a subscription SaaS:

Event What we do
checkout.session.completed Link the Stripe customer to the user (via client_reference_id)
customer.subscription.created / updated syncSubscription()
customer.subscription.deleted syncSubscription(): status becomes canceled and access ends
invoice.paid Record the payment (upsert)
invoice.payment_failed Record the attempt and notify the user

The fact that customer.subscription.updated also fires when the user schedules a cancellation is trickier than it looks, and it gets its own article: canceling doesn't mean you should cut their access today.

Testing locally with the Stripe CLI

stripe listen --forward-to localhost:3000/api/webhooks/stripe
# in another terminal
stripe trigger checkout.session.completed

stripe listen prints a whsec_... secret that goes in your .env.local. Two tests worth running before going to production:

  1. Resend the same event twice from the dashboard or with stripe events resend . The database must end up with a single payment.
  2. Call the production endpoint with an unsigned request. It must respond 400. If it responds 403, something in front of the handler (the proxy, a WAF) is blocking the request, and Stripe will hit the same wall.

If you use Polar

Polar sends its webhooks with Standard Webhooks headers (webhook-id, webhook-timestamp and webhook-signature), and its SDK ships validateEvent to verify them. Watch out for older endpoints: the signature format is a per-endpoint setting, and old ones may still use Polar's previous HMAC scheme, so if verification fails on one of them, start there. Reading the body as text applies here too.

There's one difference worth knowing. validateEvent doesn't hand you the JSON as-is: it runs it through the SDK's schemas, which convert keys to camelCase and dates to Date. If you read event.data.customer_id like in the JSON examples in the docs, you'll get undefined; the field is event.data.customerId. Best move: console.log(event.data) on your first deploy and write the handler against what you actually see.

Polar has its own delivery rules too: it retries up to 10 times with exponential backoff and disables the endpoint after 10 consecutive failed deliveries. With Stripe, a 403 costs you retries; with Polar it can leave you without webhooks until you re-enable the endpoint by hand. We covered the full integration in how to integrate Polar in Next.js.

Takeaways

  • Read the body with req.text() and verify it before parsing anything.
  • Webhook routes authenticate with their signature; take them out of the proxy's Origin check.
  • Every write as an upsert, and the event.id recorded in the same transaction as the work.
  • For subscriptions, ask the API for the current state instead of trusting event order.
  • Test a double resend and an unsigned request against production before trusting your payments.

In CREA.MBA, Stripe and Polar payments come wired up behind a single interface, with the customer, subscription and payment models already in the Prisma schema, so your work starts at your product's rules. If you're still picking a provider, the comparison is in Polar vs Stripe for an indie SaaS.

Which of the three has bitten you: the signature, the duplicate or the order?

Next.jsPrismaStripeWebhooksPayments

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI