How to add subscriptions with Stripe: a Next.js walkthrough

Add Stripe subscriptions to a web app in seven steps: prices, customers, Checkout, webhooks, access checks, the portal and failed payments. With code.

By Sohail Hussain21 November 20266 min read

To add subscriptions with Stripe, create your plans as products and prices in the Stripe Dashboard, create a Stripe customer for each account in your app, send customers to a Stripe Checkout page in subscription mode, and listen for webhooks that tell your app when a subscription starts, changes, fails to renew or ends. Your app stores the subscription status and grants access based on it. The customer portal handles plan changes, card updates and cancellations, so you do not build those screens at all.

The code is short. The care goes into the webhook, because it is the part that decides who has access, and the part that fails quietly. The walkthrough below uses Next.js route handlers and the official stripe Node library, following Stripe's subscriptions integration guide. It is the same shape we use in our web app and SaaS development projects.

What do you need to decide before writing code?

Pricing model. Flat plans, per seat, or usage-based. Per seat means a quantity on the subscription item that changes as users are added. Usage-based means reporting usage to Stripe meters. Flat plans are simplest and right for most first versions; SaaS pricing page design covers how to present them.

Trial or no trial, card or no card. A trial with a card collected up front converts fewer sign-ups but more of them pay. A trial without a card gets more sign-ups and fewer payers. Checkout supports both.

Who pays: a user or an account. In a B2B product, the account (the company) subscribes, not the person. Attach the Stripe customer to the account.

Your margins. As of October 2026, Stripe Billing costs 0.7 percent of billing volume on its pay-as-you-go plan, according to Stripe's Billing pricing page, on top of card processing fees. Our Stripe fee calculator shows what you receive from a given plan price after processing fees in your region.

How do you set up plans and customers?

Step 1: create products and prices

In the Dashboard, create a product for each plan, such as Starter and Pro, with a recurring monthly price and, if you offer it, a yearly one. Give each price a lookup key: starter_monthly, pro_yearly. Your code asks for prices by lookup key, so you can change the amount later by creating a new price and moving the key, without a code change.

Step 2: create a Stripe customer for each account

When someone creates an account in your app, create a matching Stripe customer and save its ID on the account record. Keeping that link in your own database means you never have to search Stripe by email.

ts
// lib/billing.ts
import Stripe from "stripe";

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

export async function createStripeCustomer(account: { id: string; email: string; name: string }) {
  const customer = await stripe.customers.create({
    email: account.email,
    name: account.name,
    metadata: { accountId: account.id },
  });
  return customer.id; // save on the account row as stripeCustomerId
}

How do customers subscribe?

Step 3: send customers to Checkout

The pricing page posts the chosen lookup key to a route handler, which creates a Checkout Session in subscription mode and redirects to it. getCurrentAccount stands for your own session helper.

ts
// app/api/billing/checkout/route.ts
import { stripe } from "@/lib/billing";
import { getCurrentAccount } from "@/lib/auth";

export async function POST(request: Request) {
  const account = await getCurrentAccount();
  if (!account) return new Response("Unauthorized", { status: 401 });

  const form = await request.formData();
  const lookupKey = String(form.get("lookup_key"));
  const prices = await stripe.prices.list({ lookup_keys: [lookupKey], active: true });
  if (prices.data.length === 0) return new Response("Unknown plan", { status: 400 });

  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    customer: account.stripeCustomerId,
    line_items: [{ price: prices.data[0].id, quantity: 1 }],
    subscription_data: { trial_period_days: 14 },
    success_url: `${process.env.APP_URL}/billing?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/pricing`,
  });

  return Response.redirect(session.url!, 303);
}

Remove subscription_data if you do not offer a trial. To start a trial without collecting a card, add payment_method_collection: "if_required", and decide in the Dashboard what happens when the trial ends without one.

Do not grant access on the success page. A customer can close the tab before it loads, and the URL can be visited by anyone. Access comes from the webhook.

How does your app know who has paid?

Step 4: store subscription status from webhooks

Stripe sends events to an endpoint you register in the Dashboard. The handler must verify the signature using the raw request body, then update your database. Events can arrive more than once and out of order, so re-fetch the subscription rather than trusting the event's copy, and make the save an upsert keyed on the subscription ID.

ts
// app/api/billing/webhook/route.ts
import type Stripe from "stripe";
import { stripe } from "@/lib/billing";
import { saveSubscription } from "@/lib/subscriptions"; // your own database write

export async function POST(request: Request) {
  const body = await request.text();
  const signature = request.headers.get("stripe-signature");
  if (!signature) return new Response("Missing signature", { status: 400 });

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

  switch (event.type) {
    case "customer.subscription.created":
    case "customer.subscription.updated":
    case "customer.subscription.deleted": {
      const subscription = await stripe.subscriptions.retrieve(event.data.object.id);
      await saveSubscription({
        stripeCustomerId:
          typeof subscription.customer === "string" ? subscription.customer : subscription.customer.id,
        stripeSubscriptionId: subscription.id,
        status: subscription.status,
        lookupKey: subscription.items.data[0]?.price.lookup_key ?? null,
      });
      break;
    }
    case "invoice.payment_failed":
      // Email the account owner a link to the billing portal to update their card.
      break;
  }

  return new Response(null, { status: 200 });
}

Stripe's subscription webhooks guide lists every event. Two more are worth adding once the basics work: customer.subscription.trial_will_end, sent three days before a trial ends by default, and invoice.paid, if you extend access period by period rather than reading the status.

Step 5: gate access on your own stored status

Every request that needs a paid plan checks the status saved in your database, not Stripe's API. That keeps pages fast and keeps working if Stripe is briefly unreachable.

StatusMeaningWhat to do
trialingIn a free trialFull access
activePaid and in good standingFull access
past_dueLatest payment failed; retries continueKeep access, show a banner asking for a new card
canceledSubscription endedRemove paid features
unpaidRetries exhausted, if you chose this outcomeRemove paid features
incompleteFirst payment needs action or failedNo access until it succeeds

Decide how long past_due keeps access. A few days of grace avoids locking out a customer whose card simply expired.

How do customers manage billing, and how do you recover failed payments?

Step 6: add the customer portal

Stripe's hosted customer portal lets customers switch plans, update cards, see invoices and cancel. Configure what it allows in the Dashboard, then add a button that posts to this route.

ts
// app/api/billing/portal/route.ts
import { stripe } from "@/lib/billing";
import { getCurrentAccount } from "@/lib/auth";

export async function POST() {
  const account = await getCurrentAccount();
  if (!account) return new Response("Unauthorized", { status: 401 });

  const portal = await stripe.billingPortal.sessions.create({
    customer: account.stripeCustomerId,
    return_url: `${process.env.APP_URL}/billing`,
  });

  return Response.redirect(portal.url, 303);
}

Plan changes made in the portal arrive as customer.subscription.updated events, so the webhook from step 4 already handles them.

Step 7: set up failed payment recovery and test everything

In the Dashboard's subscription and email settings, turn on Smart Retries and the emails that ask customers to update a failing card, and choose what happens after the last retry: cancel the subscription, mark it unpaid, or leave it past due. Part of every subscription business's churn is expired or declined cards rather than decisions to leave, and it is the easiest part to win back.

Then test the whole flow locally with the Stripe CLI. stripe listen prints a signing secret to use as STRIPE_WEBHOOK_SECRET while it runs.

bash
stripe listen --forward-to localhost:3000/api/billing/webhook
stripe trigger customer.subscription.created
stripe trigger invoice.payment_failed

Use Stripe's test cards to try a successful payment, a decline and a card that requires authentication. Check that your database status changes each time, and that access follows it.

What about tax, India and other markets?

Tax. Subscriptions may need sales tax, VAT or GST depending on where your customers are. Stripe Tax can calculate and collect it in Checkout, but whether you must register and charge tax in a country is a question for your accountant.

India. As of October 2026, Stripe says new accounts for Indian businesses are invite-only, and recurring card payments in India follow RBI e-mandate rules. Indian SaaS companies billing in rupees often use Razorpay subscriptions; Razorpay vs Stripe vs PayU compares them. The pattern above, with a stored status driven by webhooks, applies to any provider.

Mobile apps. Digital subscriptions sold inside iOS and Android apps generally have to use the stores' in-app purchase systems. In-app purchases vs web payments covers when you can use Stripe instead.

Once subscriptions are live, revenue per customer and churn become measurable, and our LTV calculator turns them into what a customer is worth. The pillar guide on how to build a SaaS product covers what comes after billing.

Was this guide useful?

Questions

Frequently asked.

What does Stripe Billing cost?

As of October 2026, Stripe Billing's pay-as-you-go price is 0.7 percent of billing volume, on top of the normal card processing fee for each payment. Processing fees vary by country and card type. Check Stripe's Billing pricing page for your country before modelling margins, and include both fees in your plan prices.

Should I use Stripe Checkout or build my own payment form?

Start with Checkout. It handles card entry, local payment methods, authentication challenges, tax collection and trials with very little code, and Stripe keeps it compliant. Build a custom form with Stripe Elements only when the design or flow must sit entirely inside your app and you have time to test the edge cases.

Can I use Stripe for customers in India?

As of October 2026, new Stripe accounts for Indian businesses are invite-only, and recurring card payments in India follow RBI e-mandate rules. Many Indian SaaS companies use Razorpay subscriptions for rupee billing, and Stripe through an overseas entity for international customers. Check the current position with Stripe and your accountant.

Sohail Hussain

Founder, MSH Technologies

Sohail has designed and built websites, web apps and AI products for over 12 years, for clients from Singapore-based industrial groups to early-stage SaaS startups. He writes about what actually worked.

Keep reading

Related guides.

All posts

Your next move

Like what you see? Tell us about it.

A process that takes too long, a website that undersells you, or an idea ready to take shape. Tell us where you are and we will suggest a useful next step.

India · Working with clients worldwide

Sohail, Founder, replies within 1 working day (Mon–Sat, IST). Free and no obligation.