Stripe webhooks done right: signatures, idempotency and retries

How to handle Stripe webhooks in a Next.js or Node.js SaaS so payments can't be faked, events aren't processed twice, and access always matches billing.

Samed Škulj

Samed Škulj
· 3 min read

Billing bugs are the worst kind: they either give your product away for free or lock out paying customers. Most of them come from how webhooks are handled. Here is a setup that avoids the common mistakes.

Rule 1: grant access from the webhook, not the redirect

After Stripe Checkout, the user is sent to your success URL. It's tempting to mark the account as paid on that page. Don't. The redirect can be visited without paying, can fail to load, or can happen before the payment settles.

The source of truth is the webhook Stripe sends to your server: checkout.session.completed, then customer.subscription.created, customer.subscription.updated and customer.subscription.deleted, and invoice.payment_failed. The success page should only show "we're setting up your account" and poll your own backend.

Rule 2: verify the signature on every request

Your webhook URL is public. Without signature verification, anyone can POST a fake "payment succeeded" event. Stripe signs each request; verify it with the raw request body:

// app/api/stripe/webhook/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(); // raw body, not parsed JSON
  const signature = req.headers.get("stripe-signature");

  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 handleEvent(event);
  return new Response("ok");
}

The most common way this breaks is a framework parsing the body as JSON before your handler sees it. Verification needs the exact bytes Stripe sent.

Rule 3: process each event once

Stripe retries events that don't get a 2xx response, and can occasionally deliver the same event more than once. Your handler must be idempotent.

Store processed event IDs and skip duplicates:

create table stripe_events (
  id text primary key,
  type text not null,
  processed_at timestamptz not null default now()
);

Insert the event ID in the same transaction as the changes it causes. If the insert fails because the ID exists, the event was already handled.

Rule 4: read the state from Stripe, not the event order

Events can arrive out of order. A subscription.updated might arrive before subscription.created. Instead of applying each event as a delta, use the event as a signal: fetch the current subscription from Stripe (or use the full object in the event) and write the current state to your database.

Store at least: Stripe customer ID, subscription ID, status, price or plan ID, and current period end. Derive access from those fields.

Rule 5: respond fast, work later

Stripe expects a quick response. If handling an event involves slow work (provisioning, emails, syncing to other systems), record the event and do the work in a background job. Return 200 once the event is safely stored.

Rule 6: handle the unhappy paths

  • invoice.payment_failed: tell the user, and decide your grace period.
  • customer.subscription.deleted: remove access at the right time.
  • Plan downgrades: what happens to data above the new plan's limits?
  • Refunds and disputes: who gets notified?

Test it properly

  • Use the Stripe CLI to forward events to your local server and trigger each event type.
  • Send a request with a wrong signature and confirm it's rejected.
  • Send the same event twice and confirm nothing happens the second time.
  • Run a full checkout with a test card that fails.

Fake-able upgrades are finding #3 in the sample audit report, and they come up in many AI-built app rescues. See the production readiness checklist for the rest of what to check before launch.

Written by Samed Škulj

Senior Full-Stack Engineer since 2021. I have shipped with teams at Deel, HTEC Group (for Zoox), Ministry of Programming, and now help SaaS teams add AI features and get AI-built apps ready for production. LinkedIn