Skip to content
All articles

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.

supastack team2 min read

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 shows how supastack isolates provider signature checks behind a single BFF entry point.

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 });
}
  • 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.

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 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;
});

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.

  • 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 — see the launch checklist for the pre-release checks.

Frequently asked questions

14 questions

What is supastack?

supastack is a modular foundation for building AI-powered SaaS products. It brings together common infrastructure so you can focus on product-specific features.

Does it support web and mobile?

Yes. supastack includes Next.js and Expo apps as starting points for web and mobile experiences.

What authentication is included?

Better Auth covers email OTP, magic-link, and social sign-in; email/password stays available at the API layer and through the Auth.js credentials engine for products that need it. Personal workspaces are provisioned with the account so product records stay scoped from day one.

How does it support AI?

supastack includes configurable multi-provider AI, usage tracking, budgets, and encrypted bring-your-own-key support.

How are subscriptions handled?

For products built on the kit, Stripe billing, subscriptions, and entitlements form the paid-access foundation. Provider secrets stay server-only.

Where does my product-specific code live?

Product-specific features remain in a separate codebase while the product configures and integrates supastack’s foundation modules.

How does supastack pricing work?

The kit is a one-time purchase with lifetime updates: Single Stack at $249 — your pick of Next.js (Web), Expo (iOS & Android), or Tauri (macOS & Windows Desktop) — Dual Stack at $398 with any two repos, or the Full Bundle at $399 with all three repos and the full monorepo, plus $75 per extra developer seat. No kit subscription. Checkout on this site delivers your license key by email, with repository access via GitHub invite.

How do workspaces scope my data?

User-owned records are scoped by workspaceId. Identity, entitlements, AI usage, billing events, and audit entries stay inside the personal workspace boundary.

How do background jobs work?

Trigger.dev is the explicit job runtime. The JobRunner contract only promises enqueue, status, and cancel—workflow semantics stay Trigger.dev-specific and explicit.

How is email different from outreach?

Transactional email covers product workflows such as completion notices. Cold outreach and campaigns are product concerns outside this kit’s email module.

How do mobile purchases work?

Mobile includes native purchases and restore through RevenueCat, with access verified by your server. Configure the store accounts and complete device testing before release. Web billing remains separate.

Where do AI provider keys live?

Bring-your-own-key credentials are encrypted and stay server-only. Keys are redacted from logs; usage and budgets remain visible at the workspace level.

Which payment methods does checkout accept?

The Stripe-hosted checkout accepts cards and can also offer Alipay and WeChat Pay once those wallets are enabled on the Stripe account — handy for buyers in China. Wallet authorizations confirm asynchronously, so the license page updates as soon as the payment clears.

Can I get a refund?

After you've got access to the repository, supastack is yours forever, so it cannot be refunded. But rest assured, you get the complete source code with lifetime updates to build and ship unlimited products for yourself or clients. You just cannot resell the code or redistribute the repository as a starter kit or template. One exception is the launch cashback — launch a live product built with supastack, share it, and reach 5,000 organic views or 50 organic likes within 60 days to get 50% of what you paid back; see the terms.

EN