TL;DR: This guide demonstrates how to build an event-driven SaaS billing system using Next.js, Node.js, and Stripe Checkout. You will learn how to design a Prisma database schema that acts as a read-replica of Stripe's state, implement a
StripeEventtable for webhook idempotency, and generate Checkout sessions for the signed-in user withclient_reference_idand subscription metadata so webhooks map payments to internal users.
Key Takeaways
- Model your database (e.g., using Prisma) as a read-replica of Stripe's state with fields like
stripeCustomerIdandsubscriptionStatusto enable fast, local authorization checks. - Record each processed event ID in a
StripeEventtable inside the same database transaction as the updates, so a redelivered event is skipped and a failed one is retried. - Offload card collection to Stripe Checkout so card data never touches your servers, which keeps your PCI DSS scope small (you still have compliance obligations).
- Generate Checkout Sessions in a Node.js/Express backend using
mode: 'subscription', taking the user from your auth session and the price from an allowlist rather than trusting the request body. - Pass your internal user ID in
client_reference_idandsubscription_data.metadataso every webhook can map the subscription back to the correct user, whatever order the events arrive in.
Implementing SaaS billing seems straightforward when you first read the documentation. You grab a checkout snippet, hardcode a product ID, and redirect your user. A payment goes through, your database flags the user as a premium subscriber, and you deploy to production.
Fast forward three months. A user’s credit card expires. The payment processor tries to bill them and fails. Because you didn't handle the webhook events for payment failures, your database still reflects an active premium status. They continue using your paid features for free. Meanwhile, another user wants to upgrade from the ₹850/mo plan to the ₹4,300/mo plan, but since you built a rigid custom billing page, they have to email your support team to make the change.
You are losing money on failed payments, leaking revenue through edge cases, and spending engineering hours on manual customer support.
The solution is a decoupled, event-driven payment architecture. In this guide, we will implement a subscription flow using Next.js for the frontend, Node.js for the API layer, and Stripe’s hosted Checkout and Customer Portal so card data stays with Stripe. Your database is kept in sync by webhooks, upgrades and downgrades are handled by the portal, and billing management needs very little custom UI.
Modeling Your Database for Stripe Synchronization
Before writing any integration code, design your database schema to mirror the parts of Stripe's state you need. Stripe is the source of truth for billing. Your database acts as a local copy of that state so authorization checks are fast and do not call the Stripe API on every page load. Map Stripe IDs (customer, subscription, price) directly onto your user records.
Here is a Prisma schema for PostgreSQL. It uses Prisma ORM 7, where the client is generated into a path you choose and the database URL lives in prisma.config.ts:
// prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../server/generated/prisma"
moduleFormat = "cjs"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(uuid())
email String @unique
name String?
// Stripe Mapping
stripeCustomerId String? @unique
stripePriceId String?
// Subscription State
subscriptionId String? @unique
subscriptionStatus String @default("incomplete")
currentPeriodEnd DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model StripeEvent {
id String @id // Maps to Stripe's event.id
type String
processedAt DateTime @default(now())
}
Production Note: The
StripeEventtable provides idempotency. Stripe can deliver the same webhook event more than once, so you record each processed event ID and skip IDs you have already seen.
Prisma 7 also requires a driver adapter. Create the client once and share it:
// server/db.js
const { PrismaClient } = require('./generated/prisma/client');
const { PrismaPg } = require('@prisma/adapter-pg');
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });
module.exports = { prisma };
The generated client is TypeScript, so run the server with a TypeScript-aware runner such as tsx (or compile it as part of your build).
Initiating Stripe Checkout from Next.js
To keep card data off your servers and your PCI DSS scope small, offload card collection to Stripe Checkout.
Checkout Sessions are created with your secret key, so they must be created on the server. The browser asks our Node.js backend for a session URL. The backend decides who the customer is (from its own auth session) and which prices are allowed, rather than trusting values sent by the browser.
First, let's create the Express route in our Node.js backend to generate the Checkout Session.
// server/routes/billing.js
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { requireAuth } = require('../middleware/auth'); // your session or JWT check; sets req.user
const router = express.Router();
// Only prices you sell through this page; never accept an arbitrary price ID
const ALLOWED_PRICE_IDS = new Set([process.env.STRIPE_PRICE_PRO_MONTHLY]);
router.post('/create-checkout-session', requireAuth, async (req, res) => {
const { priceId } = req.body;
if (!ALLOWED_PRICE_IDS.has(priceId)) {
return res.status(400).json({ error: 'Unknown price' });
}
try {
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
// No payment_method_types: Checkout shows the methods enabled in your Dashboard
line_items: [{ price: priceId, quantity: 1 }],
customer_email: req.user.email, // Pre-fills the checkout form
// Your internal user ID, returned on checkout.session.completed
client_reference_id: req.user.id,
// Copied onto the Subscription, so every customer.subscription.* event carries it
subscription_data: { metadata: { userId: req.user.id } },
success_url: `${process.env.FRONTEND_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.FRONTEND_URL}/pricing`,
});
res.status(200).json({ url: session.url });
} catch (error) {
console.error('Stripe Session Error:', error);
res.status(500).json({ error: 'Failed to create checkout session' });
}
});
module.exports = router;
On your Next.js frontend, you call this endpoint when the user clicks the "Subscribe" button. Because Stripe redirects the user to a hosted page, the frontend code stays small. The request sends only the price; the session cookie identifies the user. If the API runs on a different origin, enable CORS with credentials for your frontend origin only.
// app/pricing/page.tsx
'use client';
import { useState } from 'react';
export default function PricingPage() {
const [loading, setLoading] = useState(false);
// The Price ID from your Stripe Dashboard (a public identifier, not a secret)
const PRICE_ID = process.env.NEXT_PUBLIC_STRIPE_PRICE_PRO_MONTHLY;
const handleSubscribe = async () => {
setLoading(true);
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/create-checkout-session`,
{
method: 'POST',
credentials: 'include', // send the session cookie to the API
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ priceId: PRICE_ID }),
},
);
if (!response.ok) throw new Error(`Checkout request failed: ${response.status}`);
const { url } = await response.json();
if (url) {
// Redirect the user to Stripe Checkout
window.location.href = url;
}
} catch (error) {
console.error('Subscription failed:', error);
} finally {
setLoading(false);
}
};
return (
<div className="flex flex-col items-center p-10">
<h2 className="text-2xl font-bold">Pro Plan - ₹2,499/month</h2>
<button
onClick={handleSubscribe}
disabled={loading}
className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-md disabled:opacity-50"
>
{loading ? 'Redirecting to secure checkout...' : 'Subscribe Now'}
</button>
</div>
);
}
Building a Verified Webhook Receiver in Node.js
The checkout session gets the user to pay, but how does your database know the transaction succeeded? You cannot rely on the success_url redirect, because users can close the tab or lose their connection right after paying, and the redirect never reaches your app.
Stripe sends POST requests (webhooks) to your Node.js server whenever billing state changes. Anyone can send a POST to a public URL, so before trusting an event we verify the signature Stripe puts in the Stripe-Signature header. If billing also has to feed other systems, such as an ERP or a second payment provider, the same webhook-first design applies, and it is the core of most payment gateway and API integration work.
Signature verification needs the raw request body, not the parsed JSON.
// server/routes/webhooks.js
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { processStripeEvent } = require('../services/billingService');
const router = express.Router();
// Notice: We use express.raw() instead of express.json() for this specific route
router.post('/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.headers['stripe-signature'];
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event;
try {
// Verify the signature against the raw body and your endpoint secret
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.error(`Webhook signature verification failed: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
try {
// A few short database writes; see the tip below for slow work
await processStripeEvent(event);
// Acknowledge only after the database transaction has committed
res.json({ received: true });
} catch (err) {
console.error('Failed to process Stripe event:', err);
// Returning a 500 ensures Stripe will retry the webhook later
res.status(500).send('Processing Error');
}
});
module.exports = router;
Mount this router before any global app.use(express.json()), otherwise the JSON parser consumes the body and verification fails.
Tip: Here the handler does a few quick database writes and then returns 2xx, and a 5xx response makes Stripe retry (in live mode, for up to three days with exponential backoff). Stripe's guidance is to return 2xx quickly, before any complex logic that might time out. If an event triggers slow work such as emails, PDFs or calls to other APIs, store the event and return 2xx, then process it from a queue. Our guide to high-throughput, idempotent webhook ingestion covers that design.
Mapping Subscription Lifecycle Events
With a verified webhook receiver in place, we handle the events that drive the subscription lifecycle: creation, updates (upgrades, downgrades, renewals, status changes such as past_due), and deletion (cancellation, or the end of failed-payment retries, known as dunning).
Two details shape the code. First, Stripe does not guarantee event order, so customer.subscription.created can arrive before checkout.session.completed. We find the user through the userId metadata we put on the subscription, which every subscription event carries. Second, the event ID is inserted in the same transaction as the updates. A duplicate delivery hits the primary key and is skipped, and if an update fails the whole transaction rolls back, so Stripe's retry processes it again instead of finding it already marked as done.
Here is the logic, using the Prisma schema defined earlier:
// server/services/billingService.js
const { prisma } = require('../db');
const { Prisma } = require('../generated/prisma/client');
async function processStripeEvent(event) {
try {
await prisma.$transaction(async (tx) => {
// The primary key rejects a second delivery of the same event.
// If anything below throws, this insert rolls back too.
await tx.stripeEvent.create({ data: { id: event.id, type: event.type } });
await applyEvent(tx, event);
});
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
console.log(`Event ${event.id} already processed. Skipping.`);
return;
}
throw err; // the route returns 500 and Stripe retries
}
}
async function applyEvent(tx, event) {
const object = event.data.object;
switch (event.type) {
case 'checkout.session.completed':
if (object.mode === 'subscription') {
await tx.user.update({
where: { id: object.client_reference_id },
data: { stripeCustomerId: object.customer, subscriptionId: object.subscription },
});
}
break;
case 'customer.subscription.created':
case 'customer.subscription.updated': {
const item = object.items.data[0];
await tx.user.update({
where: { id: object.metadata.userId },
data: {
stripeCustomerId: object.customer,
subscriptionId: object.id,
stripePriceId: item.price.id,
subscriptionStatus: object.status, // 'active', 'past_due', 'canceled', ...
// Since API version 2025-03-31.basil the billing period is on subscription items
currentPeriodEnd: new Date(item.current_period_end * 1000),
},
});
break;
}
case 'customer.subscription.deleted':
// The user canceled, or payment retries (dunning) ended without success
await tx.user.update({
where: { id: object.metadata.userId },
data: { subscriptionStatus: 'canceled', stripePriceId: null },
});
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
}
module.exports = { processStripeEvent };
Access decisions follow the synced subscriptionStatus, and customer.subscription.deleted marks the end. Avoid writing your own cron jobs that downgrade users when a period ends: Stripe already applies your retry schedule, grace periods and proration rules, and announces the result through these events. Decide in your app which statuses grant access (for example, active and trialing, and perhaps past_due during a grace period).
Because events can arrive out of order, an older customer.subscription.updated can occasionally land after a newer one. If that matters for your product, fetch the current object with stripe.subscriptions.retrieve(object.id) inside the handler and write that state instead of the event payload. Unit test processStripeEvent with recorded event payloads, including a duplicate delivery and a failing update.
Automating Upgrades and Cancellations with the Customer Portal
Historically, developers had to build settings pages that let users change credit cards, download invoices, or cancel their plans. For most products, that is no longer necessary.
Stripe provides the Customer Portal, a hosted page where users manage their subscriptions. First configure what customers may do (update payment methods, switch plans, cancel) in the Customer Portal settings in the Stripe Dashboard. Then your backend creates a short-lived portal session and redirects the user to it.
Here is the Node.js route to provision a portal session:
// server/routes/billing.js (continued)
const { prisma } = require('../db');
router.post('/create-portal-session', requireAuth, async (req, res) => {
try {
// Use the signed-in user, never a user ID from the request body
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
if (!user || !user.stripeCustomerId) {
return res.status(400).json({ error: 'No billing account found.' });
}
const portalSession = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${process.env.FRONTEND_URL}/dashboard/settings`,
});
res.status(200).json({ url: portalSession.url });
} catch (error) {
console.error('Portal Error:', error);
res.status(500).json({ error: 'Failed to generate portal link' });
}
});
From your Next.js application, an authenticated user clicks "Manage Billing", hits this endpoint, and is redirected to Stripe. When they are done updating their card or changing plans, the portal links back to your return_url. If they changed their plan, Stripe sends a customer.subscription.updated webhook and your handler updates the database.
Testing Webhooks Locally with the Stripe CLI
Testing this flow in a local development environment requires routing Stripe's webhooks from the internet to your localhost. Stripe provides the Stripe CLI specifically for this purpose.
Once installed, run stripe login and use the listen command to forward events to your local Node.js server:
# Forward the events this integration handles to your local API
stripe listen \
--events checkout.session.completed,customer.subscription.created,customer.subscription.updated,customer.subscription.deleted \
--forward-to http://localhost:8080/api/webhooks/stripe
# In a second terminal, trigger a test event
stripe trigger customer.subscription.created
The CLI will output a webhook signing secret (whsec_...). Put it in your local .env file as STRIPE_WEBHOOK_SECRET so constructEvent can verify signatures during local testing. In production, use the signing secret of the endpoint you create in the Dashboard, and keep both out of source control. Note that events created by stripe trigger will not carry your userId metadata, so expect your handler to reject them unless you add metadata with the CLI's --override flag; that is a useful test of the failure path.
Designing for Scale
When implementing recurring billing, your application’s logic shifts from imperative ("charge this user now") to reactive ("apply the state changes Stripe reports"). By using Stripe Checkout to capture payments, webhooks to synchronize your PostgreSQL database, and the Customer Portal for ongoing account management, you keep card handling, retries and plan changes out of your own codebase.
Before going live, check that the webhook endpoint in the Dashboard is subscribed only to the events you handle, that its API version matches the payload shape your code expects, that failed deliveries alert someone, and that the portal configuration matches your plans.
Sources
- Stripe Docs: Receive Stripe events in your webhook endpoint
- Stripe Docs: Build a subscriptions integration
- Stripe API reference: Create a Checkout Session
- Stripe changelog: current_period_start and current_period_end moved to subscription items
- Prisma: Upgrade to Prisma ORM 7
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
How should I model my database for Stripe subscriptions?
Treat Stripe as the source of truth for billing state. Your database keeps a local copy by mapping Stripe IDs (like stripeCustomerId and subscriptionId) and the subscription status onto your user records, so authorization checks are fast and do not call the Stripe API.
How do I prevent duplicate Stripe webhook events from breaking my app?
Stripe can deliver the same event more than once. Store processed event IDs in a StripeEvent table and insert the ID in the same database transaction as the updates it triggers. A duplicate then fails the primary key and is skipped, while a failed update rolls back and is retried.
What is the most secure way to initiate a Stripe Checkout session in Next.js?
Create the session on your Node.js backend with your secret key, for the user identified by your own auth session and a price from an allowlist. The browser only receives the session URL and redirects to Stripe's hosted checkout page, so card data never touches your servers.
How do I link a successful Stripe Checkout back to my internal user ID?
Pass your internal user ID as client_reference_id, which comes back on the checkout.session.completed event, and in subscription_data.metadata, which is copied onto the Subscription and appears on every customer.subscription.* event. That lets you find the right user record regardless of event order.
