Skip to content
← All posts

·

How to handle Stripe webhooks: raw body, retries and order

Raw body, signature check, retries and out-of-order events for Stripe webhooks: the manual steps, and what Launchfast already ships to handle them.

Short answer: read the raw body with request.text(), verify it with stripe.webhooks.constructEvent() and the stripe-signature header, and return 401 only for a bad signature. Make every database write safe to repeat, and don't trust an event's snapshot of a subscription: fetch the current subscription from the Stripe API, because Stripe doesn't guarantee delivery order. Launchfast already does this in src/lib/billing/stripe.ts.

What goes wrong with Stripe webhooks?

You add a route, paste the example from the docs, and Stripe's dashboard shows a failed delivery. The errors people search for:

  • No signatures found matching the expected signature for payload
  • Webhook payload must be provided as a string or a Buffer (you passed a parsed object)
  • Timestamp outside the tolerance zone
  • A 400 or 500 response on every attempt, so Stripe keeps retrying.

Most of these come from the body being changed before verification. Stripe signs the exact bytes it sent. If you call request.json() first and verify a re-serialised copy, the signature won't match.

The second class of bugs is silent. The route returns 200, but a customer who paid has no access, or a customer who cancelled still has it. That happens when events arrive twice, arrive in a different order than they happened, or are handled with a stale copy of the data.

How do you set it up by hand?

  1. Create the route handler. In the App Router that is src/app/api/webhooks/stripe/route.ts exporting POST. It has to run on the server and must not be behind your sign-in redirect, since Stripe has no session.
  2. Read the raw body. Use await request.text(). Don't call request.json() first.
  3. Verify the signature. Pass the body string, the stripe-signature header and your endpoint's signing secret to stripe.webhooks.constructEvent(). It throws if the signature is wrong or the timestamp is too old (the default tolerance is five minutes).
  4. Use the right secret. The dashboard endpoint and the Stripe CLI give different whsec_... values. For local work, stripe listen --forward-to localhost:3000/api/webhooks/stripe prints its own secret, and that is the one your local .env needs. Production uses the one from the dashboard endpoint. A mix-up gives the "No signatures found" error.
  5. Pick the events. Register the endpoint in the dashboard (Developers, Webhooks) and tick only the events your code handles. For a SaaS that usually means checkout completion, subscription changes, paid invoices and refunds.
  6. Return 401 for a bad signature and 500 for your own failures. A 2xx tells Stripe the event is done. If your database is down and you return 200, Stripe won't send it again and you lose the event. A 500 makes Stripe retry later.
  7. Make writes idempotent. Stripe can deliver the same event more than once, and retries repeat events. Key payments by the Stripe payment ID with a unique constraint and ON CONFLICT DO NOTHING. Key subscriptions by the Stripe subscription ID and upsert.
  8. Handle order. Stripe's docs say it doesn't guarantee events arrive in the order they were generated. customer.subscription.created and customer.subscription.updated can arrive swapped, so applying the event payload blindly can put an old state back over a new one. Either fetch the resource from the API when the event arrives, or compare timestamps, or both.
  9. Map the data to your own tables. Find the user through a customer record you created at checkout, never through an ID sent from the browser. Convert Stripe statuses (past_due, unpaid, trialing, canceled...) to the few states your app cares about.
  10. Handle the odd payments. A checkout session can complete before the money arrives with delayed payment methods, so check payment_status. A free trial produces a $0 invoice that isn't revenue. A partial refund is not a full refund.
  11. Test the loop. Run the Stripe CLI, trigger a real test checkout, and replay the same event twice. Then break the signature on purpose and confirm you get 401.

Each step is small. The trouble is that steps 6 to 10 are easy to get nearly right, and the failures only show up with real customers.

What does the webhook route look like in Launchfast?

The kit's route follows steps 1 to 6. This is the real file, src/app/api/webhooks/stripe/route.ts:

export async function POST(request: Request) {
  const body = await request.text();

  let event;
  try {
    event = verifyWebhook(body, request.headers);
  } catch (error) {
    if (error instanceof InvalidWebhookError) {
      return Response.json({ error: "Invalid signature" }, { status: 401 });
    }
    throw error;
  }

  // Errors here return 500, so Stripe retries the event later.
  const { userId } = await handleWebhookEvent(event);
  if (userId) await syncRepoAccess(userId);
  return Response.json({ received: true });
}

And verifyWebhook() in src/lib/billing/stripe.ts rejects a request with no signature header before it reaches the SDK:

export function verifyWebhook(body: string, headers: Headers): Stripe.Event {
  const secret = requireEnv("STRIPE_WEBHOOK_SECRET");
  const signature = headers.get("stripe-signature");
  if (!signature) throw new InvalidWebhookError("Missing Stripe signature.");
  try {
    return stripe().webhooks.constructEvent(body, signature, secret);
  } catch {
    throw new InvalidWebhookError("Invalid webhook signature.");
  }
}

Only InvalidWebhookError becomes a 401. Anything else, such as a failed query, throws and returns 500, so Stripe retries it.

How does Launchfast handle out-of-order events?

Subscription events don't use the event's payload. The handler reads the subscription from the API, then writes it only if the stored row isn't newer:

// Stripe doesn't guarantee delivery order, and "created" and "updated" often share the same
// second. Read the subscription as it is now instead of trusting this event's snapshot.
const sub = await stripe().subscriptions.retrieve(event.data.object.id);
// ...
await db
  .insert(subscription)
  .values({ userId, provider: PROVIDER, providerSubscriptionId: sub.id, ...fields })
  .onConflictDoUpdate({
    target: subscription.providerSubscriptionId,
    set: fields,
    setWhere: lte(subscription.providerUpdatedAt, eventTime),
  });

Reading the live subscription means a late created event can't undo a newer updated state. The setWhere guard on providerUpdatedAt is the second layer for the rest.

How does it avoid double-counting payments and handle the edge cases?

Payments go through recordPayment(), which ends in .onConflictDoNothing(). The payment is keyed by the Stripe PaymentIntent ID, so a repeated event inserts nothing the second time.

The handler covers the cases from step 10:

  • checkout.session.completed and checkout.session.async_payment_succeeded record one-time purchases, and only when payment_status is paid.
  • invoice.paid records subscription charges, and skips invoices with amount_paid of zero, like a free trial's.
  • charge.refunded marks a payment refunded only when charge.refunded is true, so a partial refund doesn't remove access.
  • An event for a customer that isn't in billing_customer logs a warning and does nothing, because the customer row is created on the server at checkout.

Stripe statuses are mapped to the same vocabulary the kit uses for Dodo: past_due and unpaid become on_hold, canceled becomes cancelled, trialing counts as active. Pages then call getBillingStatus() and read these tables, never the Stripe API.

How do you register the endpoint?

npm run setup creates the webhook endpoint for you when you choose Stripe. The event list lives in scripts/setup/stripe.mts:

export const webhookEvents = [
  "checkout.session.completed",
  "checkout.session.async_payment_succeeded",
  "customer.subscription.created",
  "customer.subscription.updated",
  "customer.subscription.deleted",
  "invoice.paid",
  "charge.refunded",
] as const;

If an endpoint for your URL already exists, setup switches on any missing events and keeps the ones you added. Stripe only shows a signing secret when the endpoint is created, so for an existing endpoint setup asks you to paste it from the dashboard.

The repository has tests for the event handling that run against an in-process Postgres (tests/stripe-events.test.ts), so duplicate and out-of-order events are covered. You run them with npm test.

What does this save you?

You skip the raw-body and secret mix-ups, the retry and ordering logic, and the endpoint registration. You still need your own Stripe account, and the billing portal has to be switched on once in the Stripe dashboard. Start from the Launchfast home page, or read how the same design works for Dodo Payments webhooks, the full payments walkthrough, and how to gate a feature behind a paid plan.