DEV Community

Syncoders Labs
Syncoders Labs

Posted on Edited on

7 ways Stripe webhooks break in production (and the code that fixes each)

TL;DR

  • Check the signature on the raw request body, never on re-built JSON.
  • Stripe can send the same event twice. Save each event ID first and skip repeats.
  • Return 200 only when the work is really done. Use a short "lease" so a slow or crashed attempt can't swallow an event.
  • Events can arrive out of order. Ask Stripe for the current state instead of trusting the event.
  • Guest buyers' emails are in customer_details.email, not customer_email.
  • Grant access from the webhook, never from the success page.
  • A failed renewal should start reminder emails, not an instant downgrade.

A few words first

  • Webhook: an HTTP POST that Stripe sends to your server when something happens, like a payment succeeding.
  • Endpoint: the URL on your server that receives it, e.g. /api/webhooks/stripe.
  • Event: the JSON inside that POST. Each one has a unique id (like evt_123) and a type (like checkout.session.completed).
  • Status code: the number you answer with. 2xx (e.g. 200) means "got it, done". Anything else means "that didn't work".

How a healthy endpoint works

Flowchart: Stripe sends a POST, the endpoint reads the raw body, checks the signature (400 if invalid), claims the event ID (200 if already done, 409 if another attempt is running), does the work (release and 500 on failure), then marks the event done and returns 200.

Every request should go through these five steps. Three facts about Stripe explain why:

  • Stripe may send an event more than once. If your endpoint is slow, returns an error, or the connection drops before Stripe sees your 200, Stripe sends the event again. In live mode it keeps retrying, with growing gaps, for up to three days. You can also resend any event by hand from the Dashboard.
  • Stripe doesn't promise any order. An older event can arrive after a newer one.
  • Your status code is the only thing Stripe listens to. A 2xx stops the retries. Anything else schedules another try.

Each of the seven bugs below breaks one of the five steps. The code uses a Next.js App Router route handler, but the ideas work the same in Express, FastAPI or anything else that speaks HTTP.

1. Checking the signature on parsed JSON

What goes wrong: every webhook fails signature verification, even though your secret is correct.

Everyday example: you deploy, the first real payment comes in, and your logs fill with 400 errors. Nobody gets what they paid for.

Why it happens. Stripe signs each webhook so you can prove it really came from Stripe. The signature is a code computed from the request body and your webhook secret (whsec_...), sent in the Stripe-Signature header. The method is HMAC-SHA256, a standard way to prove a message came from someone who knows the secret and wasn't changed on the way.

The signature covers the exact bytes Stripe sent. Many frameworks parse the JSON before your code runs. If you then rebuild it with JSON.stringify(), the spacing and line breaks no longer match what Stripe sent. Different bytes give a different HMAC, so the check fails every time.

The tempting "fix" is to switch verification off. That lets anyone on the internet send your server a fake "payment succeeded" event.

Two paths. Right: keep the bytes exactly as sent, compute the HMAC of the same bytes, it matches. Wrong: JSON.parse then JSON.stringify changes spacing and line breaks, so the HMAC never matches and you return 400.

The fix: read the body as raw text and hand that to Stripe's library.

// 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 raw = await req.text();                    // the exact bytes Stripe sent
  const sig = req.headers.get("stripe-signature");
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(raw, sig!, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch {
    return new Response("bad signature", { status: 400 });
  }
  return handle(event);                            // steps 3 to 5, shown below
}
Enter fullscreen mode Exit fullscreen mode

Other frameworks:

  • Express: put express.raw({ type: "application/json" }) on the webhook route only.
  • FastAPI: use await request.body().
  • Django: use request.body.

Keep the five-minute window. By default the library rejects a signature more than 300 seconds old. That stops someone who captured one real request from replaying it next week. Stripe signs every retry again with a fresh timestamp, so this never blocks a real retry.

2. Doing the work twice

What goes wrong: one purchase triggers two of everything.

Everyday example: Stripe sends the same event twice, and the customer gets two welcome emails and two licence keys.

Why it happens. Stripe would rather send an event twice than lose it. If your 200 gets lost on the way back, Stripe never sees it and sends the event again. Your handler runs a second time.

Sequence: Stripe sends evt_123, the endpoint claims it, sends the welcome email and marks it done, but the 200 is lost. Stripe sends evt_123 again; the claim says already done, so the endpoint returns 200 duplicate and sends no second email.

The fix: make the handler idempotent. Idempotent means that running it twice has the same effect as running it once.

The standard way is to save each event.id in a table where the ID is the primary key. That is a unique constraint: the database refuses a second row with the same ID. Before doing any work, try to insert the ID. If a finished row is already there, skip the event and return 200.

The order matters: save the ID first, then do the work. If you first ask "have I seen this ID?" and only save it at the end, two copies arriving at the same moment both see "no" and both run. With the insert first, the database lets exactly one of them win.

There's one more case to handle before this is safe, and it's in the next section, together with the code.

3. Telling Stripe "done" when the work isn't done

What goes wrong: Stripe is told an event succeeded, so it stops retrying, but the work never happened.

Everyday example 1: your database is down for a minute. The handler logs the error and returns 200 anyway. The customer paid, and their plan never updates.

// Don't do this: a failure looks like success to Stripe
try { await dispatch(event); } catch (e) { console.error(e); }
return new Response("ok");
Enter fullscreen mode Exit fullscreen mode

Everyday example 2: your handler is waiting on a slow API, so Stripe gives up on it and retries. The retry sees the event ID is already saved, answers 200 "duplicate", and Stripe stops. Then the first attempt fails. Again, the customer paid and got nothing.

Why it happens. Your status code is the only thing Stripe listens to. In example 2, a plain "seen it" row can't tell "finished" apart from "still running" or "crashed halfway".

The fix: return an error whenever the work isn't finished, and use a claim with a lease. A lease is a claim with an expiry time: "I'm working on evt_123 until 12:01:00". Each row gets a status (processing or done) and a locked_until time. When an event arrives:

  • No row yet: insert one. This attempt owns the event.
  • done: it's a duplicate. Return 200.
  • processing, lease still valid: another attempt is working on it. Return 409, so Stripe tries again later.
  • processing, lease expired: the earlier attempt crashed. Take the event over.

Sequence: attempt 1 claims evt_123 with a 60 second lease and makes a slow API call. Stripe gives up and retries; the claim says busy, so the retry returns 409. Attempt 1 fails and releases the lease. Stripe's later retry claims the event, does the work, marks it done and gets a 200. If attempt 1 had crashed, its lease would run out after 60 seconds and the next retry would take over.

In Postgres, a single statement makes the claim. It either inserts a new row or takes over an expired lease, with no gap where two attempts can both win:

CREATE TABLE processed_events (
  id           text PRIMARY KEY,                     -- the Stripe event id
  status       text NOT NULL DEFAULT 'processing',   -- 'processing' or 'done'
  locked_until timestamptz NOT NULL                  -- when the lease runs out
);

-- Claim: returns a row only if this attempt now owns the event
INSERT INTO processed_events (id, locked_until)
VALUES ($1, now() + interval '60 seconds')
ON CONFLICT (id) DO UPDATE
  SET locked_until = now() + interval '60 seconds'
  WHERE processed_events.status = 'processing'
    AND processed_events.locked_until < now()
RETURNING id;
Enter fullscreen mode Exit fullscreen mode

If no row comes back, read the row's status: done means duplicate, anything else means busy. The handler then looks like this:

async function handle(event: Stripe.Event) {
  const claim = await db.claimEvent(event.id);     // "claimed" | "duplicate" | "busy"
  if (claim === "duplicate") return new Response("duplicate", { status: 200 });
  if (claim === "busy") return new Response("in progress", { status: 409 });

  try {
    await dispatch(event);                         // update the DB, send the email
    await db.markDone(event.id);                   // status = 'done'
    return new Response("ok", { status: 200 });
  } catch (err) {
    await db.releaseEvent(event.id);               // locked_until = now(), so a retry can run it
    console.error("webhook failed", event.type, event.id, err);
    return new Response("retry", { status: 500 });
  }
}
Enter fullscreen mode Exit fullscreen mode

Two rules keep this safe:

  • Make the lease longer than your slowest run. Give your Stripe client a timeout, e.g. new Stripe(key, { timeout: 8000, maxNetworkRetries: 2 }), so one hung call can't outlast the lease.
  • Keep the handler short. If provisioning takes 20 seconds, write what you need to the database, put the slow part on a queue keyed by event.id, and return.

Return 200 only when the work is committed, or when you're deliberately ignoring an event type you don't handle.

4. Trusting the order events arrive in

What goes wrong: a customer who cancelled gets their paid plan back.

Everyday example: a customer cancels at 12:00:05. An older "subscription updated, status active" event from 12:00:01 was delayed by a retry and arrives after the cancel. Your code applies it, and the cancelled customer has Pro again.

Why it happens. Stripe doesn't guarantee delivery order. A retried event arrives whenever its retry runs, which can be after newer events.

Sequence: Stripe creates event A (updated, active) at 12:00:01 and event B (deleted) at 12:00:05. B arrives first and the plan becomes Free. A arrives late and, trusting the payload, the plan becomes Pro, which is wrong. The fix: retrieve the subscription from the Stripe API, which says canceled, so the plan stays Free.

The fix: treat the event as a nudge, not as the truth. When a subscription event arrives, ask Stripe for the subscription as it is right now and save that:

case "customer.subscription.updated":
case "customer.subscription.deleted": {
  const sub = event.data.object as Stripe.Subscription;
  const current = await stripe.subscriptions.retrieve(sub.id);  // the state right now
  await db.saveSubscription(current);   // "active", "past_due", "canceled", ...
  break;
}
Enter fullscreen mode Exit fullscreen mode

A cheaper option is to compare event.created with the timestamp of the last event you applied and skip older ones. But event.created is in whole seconds, so two events in the same second tie. Re-fetching costs one API call and always gives the current state, so it's the one I'd pick.

5. Looking up the buyer by customer_email

What goes wrong: some buyers pay and get nothing, with no error anywhere.

Everyday example: you share a Payment Link on social media and ten people buy. Your code looks for customer_email, finds null every time, and none of them get access.

Why it happens. A Payment Link is a checkout page you create in the Stripe Dashboard without writing code. The checkout.session.completed event has two email fields, and they mean different things:

  • customer_email is the email you passed in when your code created the session. For Payment Links, pricing tables and most guest checkouts it's null.
  • customer_details.email is the email the buyer typed on the Checkout page.

Code that reads only customer_email passes every test where you created the session yourself, then silently drops every Payment Link order in production.

The fix: identify the buyer by your own ID first, then fall back to the email they typed. client_reference_id is an ID you can attach when you create a session, such as your user ID.

case "checkout.session.completed": {
  const s = event.data.object as Stripe.Checkout.Session;
  if (s.payment_status !== "paid" && s.payment_status !== "no_payment_required") break;
  const userId = s.client_reference_id ?? s.metadata?.userId;
  const email = s.customer_details?.email ?? s.customer_email;
  await provision({ userId, email, customerId: s.customer as string | null });
  break;
}
Enter fullscreen mode Exit fullscreen mode

Also check payment_status. With delayed payment methods, like bank debits, the session completes before the money arrives. The money is confirmed later by a separate checkout.session.async_payment_succeeded event, so provision there too.

6. Granting access on the success page

What goes wrong: people get access without paying, or paid customers land on a broken page.

Everyday example: your /thanks page turns on Pro when it loads. Someone posts the link in a Discord server, and everyone who opens it gets Pro for free.

Why it happens. The success_url is just the page the buyer's browser goes to after Checkout. Anyone can open it, and anyone can share it.

Flowchart: after the buyer pays, Stripe sends the webhook, which grants access in your database. Separately the browser opens your success_url, which only asks whether the payment is done. Anyone with the link can open that page too.

The fix: grant access only from the webhook. Treat the success page as a status screen: show "Thanks, we're confirming your payment" and ask your own API whether the webhook has run yet.

The success page still needs to know which checkout it belongs to. Stripe replaces the literal text {CHECKOUT_SESSION_ID} in your success_url with the real session ID. That's where a sneaky bug lives. In a JavaScript template literal (a backtick string), ${...} inserts a variable:

// Bug: ${CHECKOUT_SESSION_ID} is a JavaScript variable lookup
success_url: `${base}/thanks?session_id=${CHECKOUT_SESSION_ID}`,

// Correct: no $, so Stripe sees the literal text and fills it in
success_url: `${base}/thanks?session_id={CHECKOUT_SESSION_ID}`,
Enter fullscreen mode Exit fullscreen mode

The buggy line throws a ReferenceError, or produces session_id=undefined if a variable with that name happens to exist. Building the URL with new URL() and searchParams.set() breaks it a third way: the braces get encoded to %7BCHECKOUT_SESSION_ID%7D, and Stripe no longer recognises them. Searching your code for success_url takes a minute.

7. Cutting access on the first failed renewal

What goes wrong: good customers get locked out over a card problem that would have fixed itself.

Everyday example: a customer's card expired last month. The renewal fails at 3 a.m., your code downgrades them on the spot, and they wake up locked out, even though Stripe was going to retry the charge.

Why it happens. invoice.payment_failed fires when a renewal charge is declined. It's tempting to treat it as "they stopped paying". But Stripe retries the card on its own schedule (Smart Retries), and the customer can still update their card.

The fix: use the event to start dunning, the process of reminding a customer to fix a failed payment. Email them a link to update their card. Let access follow the subscription's status as Stripe moves it from past_due to unpaid or canceled, depending on your settings.

case "invoice.payment_failed": {
  const invoice = event.data.object as Stripe.Invoice;
  await sendUpdateCardEmail(invoice.customer as string);  // a reminder, not a downgrade
  break;
}

// Access comes from the subscription status, not from the failed invoice.
// Including "past_due" gives a grace period while Stripe retries; leave it out if you don't want one.
const hasAccess = (status: Stripe.Subscription.Status) =>
  status === "active" || status === "trialing" || status === "past_due";
Enter fullscreen mode Exit fullscreen mode

Testing all of this without a Stripe account

You can test every case offline, because Stripe's library can sign test payloads for you:

import Stripe from "stripe";
const stripe = new Stripe("sk_test_dummy");
const secret = "whsec_test_secret";

const payload = JSON.stringify(event);   // a fixture shaped like a real Stripe event
const header = stripe.webhooks.generateTestHeaderString({ payload, secret });
// POST the payload with this "stripe-signature" header to your handler
Enter fullscreen mode Exit fullscreen mode

Then write one test per case:

  • Duplicate. Send the same signed event twice. Expect two 200s and one side effect.
  • Slow attempt. Make the work slow and send a second copy while it runs. Expect 409, then a 200 on a later copy, and one side effect.
  • Crash. Claim an event, then stop before finishing. After the lease runs out, a new copy should process it.
  • Failure. Make the database throw. Expect 500, and the event not marked done.
  • Out of order. Send deleted, then the older updated (active). Expect the subscription to stay canceled.
  • Old signature. Sign with a timestamp an hour old (timestamp: now - 3600). Expect 400.
  • Tampered. Change one byte of the body after signing. Expect 400.
  • Wrong secret. Sign with a different whsec_. Expect 400.
  • Guest checkout. Send client_reference_id: null, customer_email: null and customer_details.email: "a@b.com". Expect the buyer to get access.

Before going live, also run stripe listen --forward-to localhost:3000/api/webhooks/stripe, trigger each event type, and resend one old event from the Dashboard to confirm nothing happens twice.

The short version

  • Verify the raw body. Keep the five-minute window.
  • Save event.id first, under a unique constraint.
  • Return 200 only when the work is done. Use a lease, answer 409 while busy, and release the claim on failure.
  • Don't trust arrival order. Re-fetch the subscription.
  • Find buyers by your own ID, then customer_details.email.
  • Grant access from the webhook, never from the success page. Keep {CHECKOUT_SESSION_ID} literal.
  • A failed renewal starts reminder emails, not a downgrade.

Before you go live, I keep a free Stripe Webhooks Go-Live Checklist (pay what you want, $0 is fine) that covers what to check before you trust your endpoint with live money.

If you'd rather not build the event ledger, leases and retries yourself, Webhook-Proof Stripe is my paid kit that does them for Next.js and FastAPI.

If you'd rather start from a Next.js billing module with this built in, there's RetrySafe Billing for Next.js ($39, 42 tests).

Top comments (1)

Collapse
 
challan116ux profile image
challan116-ux •

The lease idea is the one I wish more webhook guides included. Saving the event ID stops the exact duplicate, but a handler that claims an event, crashes halfway, and leaves it marked processed has swallowed it just as completely — the lease turns 'processed' into something that expires unless the work actually finished. Returning 200 only when the work is really done pairs with that: the fast-acknowledge pattern is right for slow work, but only if the queued job's failure is as visible as the webhook failure would have been.