← Back to blog
BillingPublished 2026-03-21· 12 min read

Next.js Subscription Billing: Webhooks That Work

WangNan, author at Uncorne
Published by Uncorne · Updated 2026-10-09

Most subscription-billing tutorials stop at the happy path: create a checkout session, redirect the browser, and call it done. That works in a demo. It fails the first time a customer closes the tab mid-payment, a provider retries an event, or a test fires twice. Production billing lives in the parts those tutorials skip. This is the contract behind Uncorne's generated apps — five payment providers behind one verification and entitlement layer — and the reasoning for every rule below.

Next.js subscription billing webhook flow
Next.js subscription billing webhook flow

The browser is not the source of truth

A successful redirect is a hint, not a fact. The customer may close the tab after paying but before your success page loads. A webhook can arrive before the redirect, twice, or not at all if signature verification fails. Treat the redirect as a cosmetic thank-you screen and nothing more.

Your database is the single source of truth, and exactly one thing is allowed to write subscription state into it: a verified webhook from the provider. Everything else — the success page, a polling call to the provider API, a support agent's note — only reads from that database. Get this backwards and you will eventually grant access to someone who never paid, or revoke it from someone who did. The official Stripe subscriptions overview lists the lifecycle events worth handling; the practical rule is to handle fewer events, handle them correctly, and ignore the rest loudly instead of silently.

The verification contract, stated precisely

Signature verification must be the first thing your route does — before parsing a body, before touching the database, before logging anything that contains customer data. The contract is worth writing down because getting it backwards is a security bug, not a style preference:

  • Missing, invalid or malformed signature → throw. The route answers 400 and writes nothing.
  • Validly signed event that needs no handling → return an empty result and a 200 with an ignored flag.
  • Already-seen event id → skip before any write.
  • Valid, unseen, handled event → write, then record the event id in the same transaction.

An earlier version of the Uncorne adapters returned an empty list on verification failure. That meant a forged request was acknowledged with a 200. We changed it so a verification failure throws before the route can acknowledge anything. Do not make that trade — a 200 is a promise, and you should only make it after you have checked the signature described in the Stripe webhook signature guide.

export async function POST(req: Request) {
  const raw = await req.text();               // verify against the RAW body
  let event: ProviderEvent;
  try {
    event = verifyAndParse(raw, req.headers); // throws on a bad signature
  } catch {
    return new Response("invalid signature", { status: 400 });
  }
  if (shouldIgnore(event)) {
    return json({ ignored: true, handled: [] });
  }
  const fresh = await markSeen(event.id);     // atomic insert, false if duplicate
  if (!fresh) return json({ ignored: true, duplicate: true });
  await applyPlanChange(event);               // writes customer -> plan
  return json({ handled: [event.type] });
}

Verify against the raw request body, never against a re-serialised object. JSON key order and whitespace are not stable across providers or SDK versions, and re-serialising is a classic way to invalidate a perfectly good signature. Read the body once with req.text(), pass those exact bytes to the verifier, and only then parse to an object.

Webhook signature verification sequence
Webhook signature verification sequence

Idempotency is not optional

Providers retry. A webhook that grants a plan will be delivered again if your endpoint is slow, returns a 500, or times out. Without a deduplication step, the second delivery can reset a user's quota, extend a subscription twice, or send a second welcome email. Create a table that records every event id you have processed:

create table webhook_events (
  provider   text not null,
  event_id   text not null,
  type       text not null,
  received_at timestamptz not null default now(),
  primary key (provider, event_id)
);

The insert is the gate: use an atomic insert that returns false on conflict, and only continue when it returns true. In Supabase this is an upsert with onConflict and a conflict-resolution branch; in the local SQLite path it is an INSERT ... ON CONFLICT DO NOTHING followed by a changes check. Do the deduplication inside the same transaction as the plan write where your database supports it, so a crash cannot leave you with a recorded event and an unchanged plan. Keep the rows for at least as long as your provider's retry window — Stripe retries for up to three days, so a 30-day retention is a comfortable margin.

Gate on the server, never in the UI

Hiding a button is not access control. Read the plan from the session or the database on every protected route, and make the decision there. In the App Router this means a route handler or a server action that reads the session cookie with cookies() and looks up the entitlement — not a client component that checks a prop. If the plan is inactive, the AI endpoint returns 402 even if someone edits the DOM in devtools or calls the API directly with curl.

export async function POST(req: Request) {
  const session = await getSession();
  if (!session?.user) return new Response("unauthorized", { status: 401 });
  const entitlement = await getEntitlement(session.user.id);
  if (!entitlement.active) {
    return Response.json({ code: "no_entitlement" }, { status: 402 });
  }
  return streamAnswer(req, session.user.id);
}

The same applies to Server Actions and mutations: authorise inside the action, not in the component that renders the form. Client-side checks are for usability; server-side checks are for security. If you only do one, do the server one. A useful habit is to write the server check first and treat the UI as a reflection of a decision already made.

Server-side plan gating flow
Server-side plan gating flow

402 and 429 are different answers

Two failure modes get conflated constantly. A 402 says there is no entitlement — no valid license, no active subscription, no verified email claim. A 429 says the customer is entitled but has exhausted a usage quota. Mixing them makes dashboards misleading and support painful, because the fix for one is "buy a plan" and the fix for the other is "wait for the reset".

| Status | Code | Meaning | What the client should do | | --- | --- | --- | --- | | 402 | no_entitlement | No active license or subscription | Open the billing portal | | 402 | preview_limit_reached | Anonymous preview quota used up | Ask for sign-up | | 429 | quota_exceeded | Daily AI quota exhausted | Show the reset time | | 400 | invalid_signature | Webhook signature failed | Nothing — server-side only |

Subscription status is not the same thing as usage limits. The AI endpoint has its own per-user daily quota (AI_MESSAGES_PER_DAY, default 50) backed by a Supabase RPC or the local SQLite ai_usage table. When it is exhausted, return 429 with an X-AI-Quota-Reset header and a truthful Retry-After in seconds computed from the actual reset timestamp — not a hard-coded 86400. A fake retry hint is worse than none: it trains clients to ignore the header, and it makes your support team guess.

One checkout contract, five providers

Uncorne ships adapters for Waffo, Stripe, Creem, PayPal and Lemon Squeezy behind a single interface. Each adapter maps the provider's events into a small internal vocabulary — activated, renewed, cancelled, past due — and the entitlement layer only understands that vocabulary. Switching providers is then a configuration change plus a webhook URL update, not a rewrite of your product code. The Stripe Checkout Sessions API is a good reference for the fields you need to normalise: customer id, subscription id, price id and current period end.

The trade-off is honest: a common contract is a lowest common denominator. Provider-specific features such as metered billing or a Merchant of Record's tax handling need an escape hatch. Keep an adapter method for provider-specific data and document that it is intentionally not portable, so nobody assumes the abstraction is magic.

Five payment adapters behind one checkout contract
Five payment adapters behind one checkout contract

Refunds, cancellations and what "active" really means

A subscription can be active in one system and refunded in another. Listen for the refund and charge-dispute events as well as the subscription events, and treat a full refund as an immediate revocation rather than waiting for the period end. For cancellations, prefer cancel_at_period_end so the customer keeps access through the paid period and you avoid a support ticket about losing data on day one.

Store the raw status from the provider alongside your own normalised entitlement, and never infer "active" from a boolean that was set once at signup. Recompute it on read from the latest event you applied. That one change fixes a surprising class of bugs where a plan looks correct in the database but wrong in the product.

Test the security invariant offline

You do not need five provider sandboxes to validate the contract. Uncorne includes an offline signature probe — npm run probe:webhook — that sends four bodies to a running server: validly signed, missing signature, corrupted signature and malformed JSON. It asserts the status codes in the table above, so a regression that acknowledges a forged event with 200 fails in CI. The Stripe webhooks guide documents the event types a real sandbox will deliver; use that list to build your end-to-end cases.

The four layers, in increasing order of realism:

  1. Unit tests on the verification function with fixed fixtures.
  2. The offline probe against a running dev server — no credentials required.
  3. Sandbox end-to-end runs with each provider's test keys, including a real retry.
  4. A small live canary after deployment: one low-value subscription, refunded immediately.

Layers 1 and 2 belong in CI and should be fast. Layers 3 and 4 are a pre-launch gate. Skipping the offline layer is the common mistake: it is the only one that catches the "return 200 on failure" bug without depending on an external service.

Offline webhook probe output
Offline webhook probe output

Failure modes worth designing for

A few situations are rare enough to forget and common enough to hurt. A renewal webhook arrives late, after your cron has already revoked access — handle it by recomputing entitlement from the provider's current state rather than applying events in isolation. A customer upgrades and two subscription events arrive out of order — store the period end timestamp and ignore events older than the one you already applied. A webhook is signed correctly but references a customer id you do not have — queue it and retry after user creation instead of dropping it.

Observability matters here. Log the event id, type and the decision taken (handled, ignored, duplicate, failed) with a hashed customer id. Do not log the raw body; it contains personal data and possibly a payment method token. When a customer says "I paid but I am still locked out", you should be able to answer in one query which events arrived and what you did with them.

A short pre-launch checklist

  • Raw-body signature verification throws on failure and never returns 200.
  • Every handled event id is recorded atomically before the plan write.
  • Protected routes read entitlement on the server; no client-only gates.
  • 402 and 429 carry stable machine-readable codes and honest retry headers.
  • The offline probe runs in CI on every pull request.
  • At least one sandbox end-to-end run per provider before launch.

For the full walkthrough of creating products and the checkout route, read How to Add Stripe Subscriptions to Next.js. For where billing sits inside a starter, see What to Check in a Next.js SaaS Boilerplate with Stripe and Auth.

Subscription billing is not hard because the APIs are hard. It is hard because the edge cases stay invisible until a real customer hits them. Write down the contract, test the invariant offline, and let the webhook — not the browser — decide who gets access.

FAQ

Is a browser redirect enough to grant paid access?+

No. A redirect is a hint, not proof of payment. Only a verified webhook should write subscription state to your database; everything else, including the success page, reads from that database. This prevents access for users who close the tab before paying or replay a callback.

How do I make a webhook idempotent?+

Store the provider event id in a webhook_events table with a primary key on (provider, event_id), and use an atomic insert before writing any plan or license. Verification runs first; only verified, unhandled events reach the deduplication step. Stripe retries for up to three days, so keep rows at least 30 days.

What is the difference between 402 and 429 in a subscription app?+

402 means there is no entitlement — no valid license, active subscription or verified email claim. 429 means the customer is entitled but has exhausted the daily AI quota. Preview-quota exhaustion is a separate 402 with a preview_limit_reached code. The client fixes a 402 by buying a plan and a 429 by waiting for the reset.

How should I verify webhook signatures in Next.js?+

Read the raw request body once with req.text() and pass those exact bytes to the verifier before parsing to an object. Throw on a missing, invalid or malformed signature so the route answers 400 and writes nothing. Re-serialising JSON first can invalidate a correct signature because key order and whitespace vary.

Can I test subscription billing without sandbox accounts?+

You can validate the shared verification contract offline with npm run probe:webhook, which sends valid, missing, corrupted and malformed bodies to a running server and asserts the status codes. Each gateway's real checkout flow still needs its own sandbox credentials before launch; see docs/payment-testing.md for the four-layer strategy.

All frequently asked questions · Markdown version (for AI agents)