Start a project

Stripe subscriptions in Next.js: let the webhook decide

Most broken Stripe integrations we are asked to fix share one bug. The app upgrades the user's plan when the checkout page redirects back, not when Stripe confirms the payment. A closed tab, a failed card or a double click and the database no longer matches the bill.

The fix is a rule, not a library: the success page shows a message, and only the webhook changes what a customer can do.

1. Create the checkout session on the server

Send the customer to Stripe Checkout from a server action or route handler. Put your own user ID in the metadata so the webhook can find them later, and reuse one Stripe customer per user.

app/billing/actions.ts
"use server";
import Stripe from "stripe";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function startCheckout(priceId: string) {
  const user = await requireUser();
  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    customer: user.stripeCustomerId ?? undefined,
    customer_email: user.stripeCustomerId ? undefined : user.email,
    line_items: [{ price: priceId, quantity: 1 }],
    client_reference_id: user.id,
    subscription_data: { metadata: { userId: user.id } },
    success_url: `${process.env.APP_URL}/billing?status=processing`,
    cancel_url: `${process.env.APP_URL}/billing`,
  });
  redirect(session.url!);
}

2. Verify the webhook with the raw body

Stripe signs every event. The signature is computed over the exact bytes it sent, so read the body as text before anything parses it. In the App Router a route handler gives you that directly.

app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { syncSubscription } from "@/lib/billing";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const body = await req.text();
  const signature = req.headers.get("stripe-signature")!;

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch {
    return new Response("Bad signature", { status: 400 });
  }

  switch (event.type) {
    case "customer.subscription.created":
    case "customer.subscription.updated":
    case "customer.subscription.deleted":
      await syncSubscription(event.data.object as Stripe.Subscription, event.id);
      break;
  }
  return new Response(null, { status: 200 });
}

3. Make the handler safe to run twice

Stripe retries events and can deliver them out of order. Store the event ID you processed, and always write the subscription's current state rather than applying a change on top of the old one.

  • Save processed event IDs with a unique index and skip any you have seen.
  • Write status, price ID and current_period_end from the subscription object every time.
  • Map status to access in one function: active and trialing get the plan, past_due gets a grace period, everything else gets the free plan.

4. Hand plan changes to the billing portal

Upgrades, downgrades, card changes and cancellations all belong in Stripe's customer portal. Your app opens it and waits for the same subscription webhooks. One code path for every change is the whole point.

Testing it locally

Run the Stripe CLI with stripe listen --forward-to localhost:3000/api/stripe/webhook, then trigger events with stripe trigger customer.subscription.updated. Test a failed renewal and a cancellation before launch, not after the first customer finds them.