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_SECRETand 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 justworkspaceId. - Keep a workspace's paid entitlement active as long as at least one subscription is
activeortrialing. - 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 OKonce your database confirms the event was already processed. Returning a4xxor5xxtells 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.