AI SaaS Starter KitAI SaaS Starter KitProduction-ready SaaS boilerplate with Next.js 16, Auth.js, Stripe subscriptions, Prisma, dashboard, teams, admin CMS, and AI-ready API hooks.$29

Payment succeeded in Stripe Checkout, but your app still shows the free plan. The user refreshes the dashboard nothing changes until you manually run a script or wait for another event. In most SaaS apps built with Next.js and Prisma, the gap is not Stripe; it is thecheckout.session.completedhandlernever tying the new subscription to the logged-in user in your database.

This guide focuses on that one event: how toupdate user subscription state in Prismawhen Checkout completes, whymetadata.userIdis the reliable link, and how this handler fits alongsidecustomer.subscription.updatedin a production webhook route.


Whatcheckout.session.completedactually delivers

Stripe firescheckout.session.completedwhen a Checkout Session reaches a completed state. Forsubscriptionmode, that usually means:

  • The customer completed payment (or started a trial, depending on your price).

  • Stripe created or attached aSubscriptionobject (sessionsubscriptionis set).

  • The session may includemetadatayou set when creating the session.

The event payload is aCheckout.Session, not a fullSubscription. Your handler typically:

  1. Readssession.metadata.userId(or resolves the user another way—see pitfalls below).

  2. Retrieves the subscription withstripe.subscriptions.retrieve(session.subscription).

  3. UpsertsaSubscriptionrow in Prisma keyed bystripeSubscriptionId.

That is the core of acheckout.session.completed handler to update user subscription in Prismaeverything else is edge cases and hardening.

When this event is enough (and when it is not)

Scenariocheckout.session.completedAlso listen for First purchase after Checkout Primary sync pointcustomer.subscription.updatedfor later changes Plan upgrade via Checkout Yes, if you use Checkout for upgradessubscription.updatedCancel at period end in Portal Nocustomer.subscription.updatedFailed renewal →past_dueNocustomer.subscription.updated,invoice.paidSubscription deleted Nocustomer.subscription.deleted

Treat Checkout completion as thefast pathfor new paid access; keep subscription lifecycle events for ongoing truth.


Prerequisites

  • Working webhook route withsignature verification(request.text()+constructEvent).

  • Prisma models forUserandSubscription(see thefull sync guide).

  • Checkout sessions created insubscriptionmode withmetadata.userIdset server-side.


Step 1: PassuserIdwhen creating Checkout

Never trust the client to senduserIdin metadata without authentication. Create the session in aRoute Handleror Server Action after you know the session user:

// app/api/stripe/checkout/route.ts (example)
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

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

export async function POST(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { priceId } = await request.json();
  const user = await db.user.findUnique({
    where: { id: session.user.id },
  });

  if (!user) {
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  }

  let customerId = user.stripeCustomerId;

  if (!customerId) {
    const customer = await stripe.customers.create({
      email: user.email ?? undefined,
      metadata: { userId: user.id },
    });
    customerId = customer.id;
    await db.user.update({
      where: { id: user.id },
      data: { stripeCustomerId: customerId },
    });
  }

  const checkoutSession = await stripe.checkout.sessions.create({
    mode: "subscription",
    customer: customerId,
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard/billing?success=1`,
    cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
    metadata: {
      userId: user.id,
    },
    subscription_data: {
      metadata: {
        userId: user.id,
      },
    },
  });

  return NextResponse.json({ url: checkoutSession.url });
}

Why bothmetadataandsubscription_data.metadata?

  • Session metadata is on the Checkout Session easy to read incheckout.session.completed.

  • Subscription metadata copies to the Subscription object useful when later events only include the subscription, not the original session.


Step 2: Map Stripe status to your Prisma enum

Reuse the same mapper from your general sync handler:

import type { SubscriptionStatus } from "@prisma/client";
import type Stripe from "stripe";

function mapSubscriptionStatus(
  status: Stripe.Subscription.Status,
): SubscriptionStatus {
  const statusMap: Record<Stripe.Subscription.Status, SubscriptionStatus> = {
    active: "ACTIVE",
    canceled: "CANCELED",
    incomplete: "INCOMPLETE",
    incomplete_expired: "INCOMPLETE_EXPIRED",
    past_due: "PAST_DUE",
    trialing: "TRIALING",
    unpaid: "UNPAID",
    paused: "PAUSED",
  };
  return statusMap[status] ?? "INCOMPLETE";
}

Step 3: Upsert from a Stripe Subscription object

Keep one function used by Checkout and bycustomer.subscription.updated:

async function upsertSubscriptionFromStripe(
  userId: string,
  subscription: Stripe.Subscription,
) {
  const priceId = subscription.items.data[0]?.price.id;
  if (!priceId) {
    console.warn("Subscription missing price id", subscription.id);
    return;
  }

  await db.subscription.upsert({
    where: { stripeSubscriptionId: subscription.id },
    create: {
      userId,
      stripeSubscriptionId: subscription.id,
      stripePriceId: priceId,
      status: mapSubscriptionStatus(subscription.status),
      currentPeriodStart: new Date(subscription.current_period_start * 1000),
      currentPeriodEnd: new Date(subscription.current_period_end * 1000),
      cancelAtPeriodEnd: subscription.cancel_at_period_end,
    },
    update: {
      userId,
      stripePriceId: priceId,
      status: mapSubscriptionStatus(subscription.status),
      currentPeriodStart: new Date(subscription.current_period_start * 1000),
      currentPeriodEnd: new Date(subscription.current_period_end * 1000),
      cancelAtPeriodEnd: subscription.cancel_at_period_end,
    },
  });
}

UsingupsertonstripeSubscriptionIdmakes the handler safe if Stripe retries the samecheckout.session.completeddelivery—as long as you also guard side effects withevent.id(seeidempotent webhooks with event.idwhen that post is live; pattern below).


Step 4: Thecheckout.session.completedcase in your webhook

Insideapp/api/stripe/webhook/route.ts, after verification:

case "checkout.session.completed": {
  const session = event.data.object as Stripe.Checkout.Session;

  if (session.mode !== "subscription") {
    break;
  }

  const userId = session.metadata?.userId;
  const subscriptionId =
    typeof session.subscription === "string"
      ? session.subscription
      : session.subscription?.id;

  if (!userId) {
    console.error(
      "checkout.session.completed missing metadata.userId",
      session.id,
    );
    break;
  }

  if (!subscriptionId) {
    console.error(
      "checkout.session.completed missing subscription",
      session.id,
    );
    break;
  }

  const subscription = await stripe.subscriptions.retrieve(subscriptionId);
  await upsertSubscriptionFromStripe(userId, subscription);
  break;
}

Registercheckout.session.completedin the Stripe Dashboard webhook endpoint (Developers → Webhooks → select events).


Step 5: Resolve the user when metadata is missing

If you forgotmetadata.userIdon older sessions, fall back toStripe customer idon yourUserrow:

async function resolveUserIdFromCheckoutSession(
  session: Stripe.Checkout.Session,
): Promise<string | null> {
  if (session.metadata?.userId) {
    return session.metadata.userId;
  }

  const customerId =
    typeof session.customer === "string"
      ? session.customer
      : session.customer?.id;

  if (!customerId) return null;

  const user = await db.user.findFirst({
    where: { stripeCustomerId: customerId },
  });

  return user?.id ?? null;
}

This only works if you persistedstripeCustomerIdbeforeCheckout (as in Step 1). Creating the customer only inside the webhook without saving the id onUserleaves you with no join key.


Step 6: Idempotency and side effects

Stripe may deliver the same event more than once. Before running handlers:

const existing = await db.stripeEvent.findUnique({
  where: { eventId: event.id },
});

if (existing) {
  return NextResponse.json({ received: true });
}

await db.stripeEvent.create({
  data: { eventId: event.id, type: event.type },
});

Forcheckout.session.completed, duplicate upserts are usually harmless. Side effects—welcome emails, analytics, granting one-time credits—must be keyed byevent.idorsession.id, not fired blindly on every delivery.


Step 7: Test the handler end to end

  1. Fix verification first (Stripe webhook signature in Next.js).

  2. Runstripe listen --forward-to localhost:3000/api/stripe/webhookand set the CLIwhsecin.env.local.

  3. Complete test Checkout with card4242 4242 4242 4242.

  4. In Stripe Dashboard → Webhooks → recent deliveries, confirm200and inspect logs forcheckout.session.completed.

  5. Open Prisma Studio:Subscriptionrow should showACTIVE(orTRIALING) with correctuserId.

Optional:stripe trigger checkout.session.completedsends a fixture event—useful for plumbing, but real Checkout tests metadata and subscription ids more faithfully.


Common failures

Payment works; Prisma row never appears

  • Webhook not subscribed tocheckout.session.completed.

  • Handler returns 500 before upsert (check logs; Stripe retries).

  • session.modeispaymentbut you only handle subscription mode.

  • Missingmetadata.userIdand nostripeCustomerIdon user.

Wrong user gets the subscription

  • Client-supplieduserIdin metadata without server auth.

  • Shared Stripe customer across accounts (reuse customer id correctly per app user).

User sees Pro briefly, then loses access

  • You only handle Checkout; cancel orpast_dueupdates never run.

  • Fix:Also handlecustomer.subscription.updatedand gate onstatus, not “row exists.”

Duplicate welcome emails or credits

  • No idempotency onevent.idfor non-upsert side effects.


How this connects to the rest of your billing stack


Ship Checkout, metadata, and upserts without reinventing them

Wiring Checkout creation, customer ids, webhook verification, and Prisma upserts is repetitive and easy to get wrong on the first real payment.

Skryptix AI SaaS Starter Kitincludes:

  • Server-side Checkout withuserIdmetadata and customer creation

  • Webhook handler withcheckout.session.completedand subscription lifecycle events

  • Prisma models and upsert helpers shared across events

  • Billing UI and docs for test mode

Metadata, checkout, and subscription upserts are pre-wired inAI SaaS Starter Kit—Get it here.

AI SaaS Starter KitAI SaaS Starter KitProduction-ready SaaS boilerplate with Next.js 16, Auth.js, Stripe subscriptions, Prisma, dashboard, teams, admin CMS, and AI-ready API hooks.$29

FAQ

What should I do incheckout.session.completedfor a SaaS app?

Readmetadata.userId, retrieve the subscription id from the session, callstripe.subscriptions.retrieve, and upsert aSubscriptionrecord in Prisma with status, price id, and billing period fields. Return HTTP 200 from the webhook after processing.

Do I still needcustomer.subscription.updatedif I handle Checkout?

Yes. Checkout completion covers the first successful purchase; plan changes, renewals, failures, and cancellations arrive on subscription and invoice events later.

Where should I setuserIdfor Stripe Checkout metadata?

In your authenticated server-side Checkout session creation (app/api/stripe/checkout/route.tsor equivalent)—never from the browser alone.

Can I useclient_reference_idinstead of metadata?

Yes. Stripe supportsclient_reference_idon Checkout Sessions; readsession.client_reference_idin the webhook the same way you readmetadata.userId. Pick one convention and use it consistently.

Why retrieve the subscription instead of trusting the session object?

The session carries ids and metadata; the Subscription object has authoritative status, items, and period dates. One retrieve call keeps your Prisma row aligned with Stripe’s subscription API.