> ## Documentation Index
> Fetch the complete documentation index at: https://supastack.dev/llms.txt
> Use this file to discover all available pages before exploring further.
> For the full documentation corpus in one file, fetch: https://supastack.dev/llms-full.txt

# Idempotent Stripe and Lemon Squeezy webhooks in Next.js

How to verify raw webhook signatures, deduplicate replayed deliveries at the database boundary, and keep overlapping subscriptions from revoking paid access.

_Published 2026-10-18._
_Updated 2026-10-18._

> **How do I handle Stripe and Lemon Squeezy webhooks idempotently in Next.js?**
> It depends on your billing providers, but the core architecture is identical: verify the raw payload signature before parsing JSON, normalize provider events into a shared internal contract, and enforce idempotency at the database boundary using the provider's event or order ID. Never grant product entitlements from a client-side checkout redirect; let the verified webhook transactionally update subscription state and entitlements once. supastack prewires this pipeline for Stripe, Lemon Squeezy, and mobile RevenueCat, though single-plan apps can start with a simpler handler.

## Verify the raw payload before touching JSON

Every payment provider signs the exact byte sequence it sends over the wire. If a route handler parses `await request.json()` and re-serializes the object before checking the signature, key ordering or whitespace differences will invalidate legitimate webhooks, or worse, tempt developers to skip verification in staging.

Read the raw body once with `await request.text()` in your Next.js App Router `POST` handler, verify the cryptographic signature against the server-only webhook secret, and reject anything that fails with HTTP 400 before running a single database query. The [billing module guide](https://supastack.dev/docs/modules/billing.md) shows how supastack isolates provider signature checks behind a single BFF entry point.

- Read the raw request body with `request.text()`, never re-stringify parsed JSON.
- Keep `STRIPE_WEBHOOK_SECRET` and Lemon Squeezy signing secrets in server-only configuration.
- Use constant-time comparison (`crypto.timingSafeEqual`) when verifying HMAC signatures manually.

```
export async function POST(request: Request) {
  const rawBody = await request.text();
  const signature = request.headers.get("stripe-signature");
  if (!signature) return new Response("Missing signature", { status: 400 });

  const event = stripe.webhooks.constructEvent(
    rawBody,
    signature,
    env.STRIPE_WEBHOOK_SECRET,
  );
  await handleNormalizedBillingEvent(event);
  return Response.json({ received: true });
}
```


## Deduplicate at the database boundary, not in memory

Stripe and Lemon Squeezy retry webhooks whenever a deployment restarts, a serverless function times out, or a network hop drops the response. Process-local sets or short-lived cache keys vanish across instances and will not stop two concurrent retries from granting duplicate licenses or sending two receipt emails.

Record the provider's event ID or order settlement state inside the same Postgres transaction that mutates subscription access. An atomic `INSERT ... ON CONFLICT DO NOTHING` or a conditional update on `status != 'paid'` turns a concurrent replay into a clean no-op. When designing the plans those webhooks fulfill, the [SaaS pricing generator](https://supastack.dev/tools/saas-pricing-generator) helps model tiers and seat rules upfront.

```
const settled = await db.transaction(async (tx) => {
  const [inserted] = await tx
    .insert(billingWebhookEvents)
    .values({ providerEventId: event.id, provider: "stripe" })
    .onConflictDoNothing({ target: billingWebhookEvents.providerEventId })
    .returning({ id: billingWebhookEvents.id });

  if (!inserted) return false; // Already processed
  await applyWorkspaceEntitlement(tx, event);
  return true;
});
```

- [SaaS Pricing Page Generator (Free Tool)](https://supastack.dev/tools/saas-pricing-generator)


## Handle out-of-order events and overlapping subscriptions

Webhooks are not guaranteed to arrive in the order the user clicked. `customer.subscription.updated` can land before `checkout.session.completed`, and a customer who accidentally opens two checkout tabs can briefly hold two subscriptions in the same workspace.

Scope cancellations and payment failures to the specific subscription ID that triggered the event. Before revoking a workspace's paid entitlement, check whether another active subscription still covers that workspace, otherwise canceling a duplicate subscription silently strips access the customer is still paying for. If you are evaluating how different starters isolate this billing pipeline, our [Next.js SaaS boilerplate comparison](https://supastack.dev/blog/best-nextjs-saas-boilerplates-2026.md) evaluates which codebases ship with replay-proof test harnesses out of the box.

- Key subscription state by `providerSubscriptionId`, not just `workspaceId`.
- Keep a workspace's paid entitlement active as long as at least one subscription is `active` or `trialing`.
- Verify that paid amount and currency match the expected SKU before fulfilling one-time orders.


## Common questions about SaaS billing webhooks

These questions come up whenever a team moves billing from sandbox checkout tests to production traffic.

- Can I unlock paid features on the checkout success redirect?, No. Redirect URLs can be bookmarked, shared, or visited before asynchronous payment methods settle. Use the success page to poll server state while the verified webhook grants access.
- What status code should a duplicate webhook return?, Return `200 OK` once your database confirms the event was already processed. Returning a `4xx` or `5xx` tells the provider to keep retrying.
- How do I test webhook retries locally?, Write deterministic unit tests that send the exact same signed payload twice and assert that only one license, entitlement, or transactional email is produced.
- How do mobile in-app purchases fit the same model?, Route RevenueCat server notifications through the same idempotent entitlement table so web and mobile purchases never overwrite each other. For the complete architecture coordinating web Stripe with iOS and Android App Store entitlements, see our deep-dive on building a [web and mobile SaaS with Next.js and Expo](https://supastack.dev/blog/web-and-mobile-saas-nextjs-expo.md).
