Subscriptions are the business model behind most SaaS products. Building them from scratch means dealing with recurring charges, failed payments, cancellations, and invoices, which is why most of us rely on Stripe. It gives us a hosted Checkout page, a Customer Portal where users can update their card or cancel their plan, and webhooks that notify our application every time something changes. Our job is to connect these pieces to our users.
In this tutorial, we will learn how to integrate Stripe subscriptions in a TanStack Start application. We will create a Checkout Session for the signed-in user, receive Stripe webhooks in a server route, store the subscription status in our database with Drizzle, protect a premium page, and let our users manage their plan through the Customer Portal.
Prerequisites
This tutorial is the second part of my TanStack Start series, and it builds on top of the project from TanStack Start Authentication with Better Auth and Drizzle. Here's a quick recap of what we will reuse:
- A Drizzle 1.0 (RC) instance connected to PostgreSQL, exported as
dbfromsrc/db/index.ts, with the Better Auth tables insidesrc/db/schema.ts. - An
authMiddlewareinsrc/lib/auth.functions.tsthat passes the current session to our server functions throughcontext.session. - A
_protectedpathless layout route that redirects signed-out users to/login.
Stripe Account Setup
Let's start by creating our Stripe account. Every account comes with a test mode (also called a sandbox), which lets us test our whole integration with fake cards and without moving real money.
Next, we will open the API keys page in the Developers section of our dashboard and copy our Secret key (sk_test_...), which authenticates our requests to Stripe's API from our server and must never be exposed to the browser. Since we will use Stripe's hosted Checkout page, we won't need the Publishable key.
Now, let's create the plan our users will subscribe to. We will go to the Product catalog page, click on Add product, give it a name (e.g. Pro), and add a Recurring price (e.g. $10 per month). Once it's saved, we will copy the ID of its price (price_...).
Finally, let's add our secret key and price ID to our .env file:
STRIPE_SECRET_KEY="sk_test_..."
STRIPE_PRICE_ID="price_..."
STRIPE_WEBHOOK_SECRET="whsec_..."We will get the value of STRIPE_WEBHOOK_SECRET later in this tutorial, when we set up the Stripe CLI.
Install and Configure Stripe
Let's install the official Stripe Node.js library:
npm install stripeNow, let's create a helper that returns our Stripe client inside a new file called src/lib/stripe.ts:
import Stripe from 'stripe';
let stripe: Stripe | null = null;
export function getStripe() {
if (!stripe) {
stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
}
return stripe;
}Instead of creating the client when the file is imported, we create it the first time we need it, so our environment variables are always read inside a request (some hosts like Cloudflare Workers require this). Each version of the Stripe library is pinned to a specific API version, so we don't need to pass one.
Subscription Schema
Next, we need to store two things in our database: which Stripe customer belongs to each user, and the current state of each subscription. We will keep our whole schema in a single file, so let's add two new tables at the bottom of our src/db/schema.ts file, below the code that the Better Auth CLI generated:
export const customer = pgTable('customer', {
userId: text('user_id')
.primaryKey()
.references(() => user.id, { onDelete: 'cascade' }),
stripeCustomerId: text('stripe_customer_id').notNull().unique(),
});
export const subscription = pgTable('subscription', {
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
stripePriceId: text('stripe_price_id').notNull(),
status: text('status').notNull(),
currentPeriodEnd: timestamp('current_period_end').notNull(),
cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
});Our new tables use the pgTable, text, timestamp, and boolean helpers, which the generated file already imports from drizzle-orm/pg-core, and they reference the user table defined in the same file.
Let's go through each table:
customerconnects each user with their Stripe customer, so we can reuse the same customer every time a user goes through Checkout.subscriptionstores a copy of each Stripe subscription. Itsidis the Stripe subscription ID (sub_...),statusis the Stripe status (e.g.active,past_due, orcanceled),currentPeriodEndis when the current billing period ends, andcancelAtPeriodEndtells us if the user scheduled a cancellation.
Since our Drizzle Kit config already points to src/db/schema.ts, we don't need to change it. Finally, let's create and apply our migration:
npx drizzle-kit generate
npx drizzle-kit migrateCreate the Checkout Session
Stripe Checkout is a payment page hosted by Stripe. To send a user there, we create a Checkout Session on our server and redirect the user to the URL it returns. Let's create a new file called src/lib/billing.functions.ts with our first server function:
import { createServerFn } from '@tanstack/react-start';
import { eq } from 'drizzle-orm';
import { authMiddleware } from '@/lib/auth.functions';
import { getStripe } from '@/lib/stripe';
import { db } from '@/db';
import { customer } from '@/db/schema';
async function getOrCreateCustomer(user: { id: string; email: string; name: string }) {
const [existing] = await db.select().from(customer).where(eq(customer.userId, user.id));
if (existing) return existing.stripeCustomerId;
const stripeCustomer = await getStripe().customers.create({
email: user.email,
name: user.name,
metadata: { userId: user.id },
});
await db.insert(customer).values({ userId: user.id, stripeCustomerId: stripeCustomer.id });
return stripeCustomer.id;
}
export const createCheckoutSession = createServerFn({ method: 'POST' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
const customerId = await getOrCreateCustomer(context.session.user);
const appUrl = process.env.BETTER_AUTH_URL;
const checkoutSession = await getStripe().checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }],
success_url: `${appUrl}/premium?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${appUrl}/pricing`,
});
return { url: checkoutSession.url! };
});The getOrCreateCustomer function looks for the user's Stripe customer in our customer table. If there isn't one, it creates it with customers.create and saves its ID (we also store our userId in its metadata, which helps when browsing the Stripe dashboard).
Let's go through each field of our Checkout Session:
modedefines the type of payment. Withsubscription, Checkout creates a recurring subscription instead of a one-time payment.customerattaches the session (and the subscription it creates) to our user's Stripe customer.line_itemsis the list of prices the user is subscribing to. Here, we use the price we created in our Product catalog.success_urlis the page where Stripe sends the user after a successful payment. Stripe replaces{CHECKOUT_SESSION_ID}with the ID of the session.cancel_urlis the page where Stripe sends the user if they go back without paying.
Handle Stripe Webhooks
When a user completes Checkout, Stripe creates the subscription on its side, and every change after that (a renewal, a failed payment, a cancellation) also happens there. Webhooks are how Stripe notifies us: it sends a POST request to our server with an event that describes what changed.
First, let's create a function that saves a Stripe subscription into our database. We will add it to a new file called src/lib/billing.server.ts:
import type Stripe from 'stripe';
import { eq } from 'drizzle-orm';
import { db } from '@/db';
import { customer, subscription } from '@/db/schema';
export async function syncSubscription(stripeSubscription: Stripe.Subscription) {
const customerId =
typeof stripeSubscription.customer === 'string'
? stripeSubscription.customer
: stripeSubscription.customer.id;
const [owner] = await db.select().from(customer).where(eq(customer.stripeCustomerId, customerId));
if (!owner) return;
const item = stripeSubscription.items.data[0];
const values = {
userId: owner.userId,
stripePriceId: item.price.id,
status: stripeSubscription.status,
currentPeriodEnd: new Date(item.current_period_end * 1000),
cancelAtPeriodEnd: stripeSubscription.cancel_at_period_end,
updatedAt: new Date(),
};
await db
.insert(subscription)
.values({ id: stripeSubscription.id, ...values })
.onConflictDoUpdate({ target: subscription.id, set: values });
}Our syncSubscription function finds the user that owns the Stripe customer and inserts the subscription, or updates it if it already exists (onConflictDoUpdate). Notice that we read current_period_end from the subscription item, since that's where current versions of Stripe's API return it. If no user owns the customer, we ignore the event.
Now, let's create the server route that receives our webhooks. We will create a new file called src/routes/api/stripe/webhook.ts:
import { createFileRoute } from '@tanstack/react-router';
import type Stripe from 'stripe';
import { getStripe } from '@/lib/stripe';
import { syncSubscription } from '@/lib/billing.server';
export const Route = createFileRoute('/api/stripe/webhook')({
server: {
handlers: {
POST: async ({ request }) => {
const stripe = getStripe();
const body = await request.text();
const signature = request.headers.get('stripe-signature');
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 'checkout.session.completed': {
const checkoutSession = event.data.object;
if (checkoutSession.mode === 'subscription' && checkoutSession.subscription) {
const subscriptionId =
typeof checkoutSession.subscription === 'string'
? checkoutSession.subscription
: checkoutSession.subscription.id;
await syncSubscription(await stripe.subscriptions.retrieve(subscriptionId));
}
break;
}
case 'customer.subscription.created':
case 'customer.subscription.updated':
case 'customer.subscription.deleted':
await syncSubscription(event.data.object);
break;
}
return Response.json({ received: true });
},
},
},
});Let's go through our webhook handler step by step:
- We read the body with
request.text(). Stripe signs the exact raw body, so we must not parse it as JSON before verifying it. constructEventchecks thestripe-signatureheader against our webhook secret. If the request didn't come from Stripe or the body was modified, it throws and we return a400response.checkout.session.completedis sent when a user finishes Checkout. We retrieve the full subscription from Stripe and save it.customer.subscription.created,updated, anddeletedare sent when a subscription starts, changes (e.g. a renewal or a scheduled cancellation), or ends (its status becomescanceled). Theirevent.data.objectis already the subscription, so we save it directly.- Finally, we return a
200response so Stripe knows we received the event (otherwise, it retries it).
Since Stripe can send the same event more than once, our upsert makes sure we never create duplicates.
Protect Premium Content
Now that our database knows the status of every subscription, let's use it to protect our premium features. We will create a middleware and a few server functions inside a new file called src/lib/subscription.functions.ts:
import { createMiddleware, createServerFn } from '@tanstack/react-start';
import { and, eq, inArray } from 'drizzle-orm';
import { authMiddleware } from '@/lib/auth.functions';
import { db } from '@/db';
import { subscription } from '@/db/schema';
async function getActiveSubscription(userId: string) {
const [activeSubscription] = await db
.select()
.from(subscription)
.where(
and(
eq(subscription.userId, userId),
inArray(subscription.status, ['active', 'trialing']),
),
);
return activeSubscription ?? null;
}
export const subscriptionMiddleware = createMiddleware({ type: 'function' })
.middleware([authMiddleware])
.server(async ({ next, context }) => {
const activeSubscription = await getActiveSubscription(context.session.user.id);
if (!activeSubscription) {
throw new Error('An active subscription is required');
}
return next({ context: { subscription: activeSubscription } });
});
export const getSubscriptionStatus = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
const activeSubscription = await getActiveSubscription(context.session.user.id);
return { isSubscribed: activeSubscription !== null };
});
export const getPremiumContent = createServerFn({ method: 'GET' })
.middleware([subscriptionMiddleware])
.handler(async ({ context }) => {
return {
message: 'Welcome to the premium area!',
renewsAt: context.subscription.currentPeriodEnd,
};
});Let's go through each function:
getActiveSubscriptionlooks for a user's subscription with the statusactiveortrialing. Statuses likepast_dueorcanceledwon't give access.subscriptionMiddlewarebuilds on ourauthMiddleware, so it first makes sure the user is signed in and then checks their subscription. If there isn't an active one, it stops the request; otherwise, it passes the subscription throughcontext.getSubscriptionStatustells our routes whether the user is subscribed.getPremiumContentis an example of a premium server function. Thanks tosubscriptionMiddleware, it can't be called without an active subscription, even directly.
Now, let's create our premium page inside a new file called src/routes/_protected/premium.tsx:
import { createFileRoute, redirect } from '@tanstack/react-router';
import { getPremiumContent, getSubscriptionStatus } from '@/lib/subscription.functions';
export const Route = createFileRoute('/_protected/premium')({
beforeLoad: async () => {
const { isSubscribed } = await getSubscriptionStatus();
if (!isSubscribed) {
throw redirect({ to: '/pricing' });
}
},
loader: () => getPremiumContent(),
component: Premium,
});
function Premium() {
const { message, renewsAt } = Route.useLoaderData();
return (
<div>
<h1>{message}</h1>
<p>Your plan renews on {new Date(renewsAt).toLocaleDateString()}.</p>
</div>
);
}Just like in our authentication tutorial, beforeLoad redirects users without an active subscription to our pricing page, while the real protection lives in our getPremiumContent server function.
Customer Portal
Our users also need a way to update their card, download invoices, or cancel their plan. Instead of building these screens, we can use Stripe's Customer Portal. First, we will open the Customer portal settings in our Stripe dashboard, choose which actions our users can perform (e.g. cancel their subscription), and save it.
Then, let's create our last server function inside a new file called src/lib/portal.functions.ts:
import { createServerFn } from '@tanstack/react-start';
import { eq } from 'drizzle-orm';
import { authMiddleware } from '@/lib/auth.functions';
import { getStripe } from '@/lib/stripe';
import { db } from '@/db';
import { customer } from '@/db/schema';
export const createPortalSession = createServerFn({ method: 'POST' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
const [existing] = await db
.select()
.from(customer)
.where(eq(customer.userId, context.session.user.id));
if (!existing) {
throw new Error('No billing account found');
}
const portalSession = await getStripe().billingPortal.sessions.create({
customer: existing.stripeCustomerId,
return_url: `${process.env.BETTER_AUTH_URL}/pricing`,
});
return { url: portalSession.url };
});The billingPortal.sessions.create method receives our user's Stripe customer and a return_url, the page Stripe sends them back to. Any change made inside the portal reaches us through the subscription webhooks we already handle.
Finally, let's create our pricing page inside a new file called src/routes/_protected/pricing.tsx:
import { createFileRoute } from '@tanstack/react-router';
import { createCheckoutSession } from '@/lib/billing.functions';
import { createPortalSession } from '@/lib/portal.functions';
import { getSubscriptionStatus } from '@/lib/subscription.functions';
export const Route = createFileRoute('/_protected/pricing')({
loader: () => getSubscriptionStatus(),
component: Pricing,
});
function Pricing() {
const { isSubscribed } = Route.useLoaderData();
const handleSubscribe = async () => {
const { url } = await createCheckoutSession();
window.location.href = url;
};
const handleManageBilling = async () => {
const { url } = await createPortalSession();
window.location.href = url;
};
return (
<div>
<h1>Pro plan</h1>
{isSubscribed ? (
<button onClick={handleManageBilling}>Manage billing</button>
) : (
<button onClick={handleSubscribe}>Subscribe</button>
)}
</div>
);
}When the user clicks on Subscribe, we call createCheckoutSession and redirect the browser to Checkout. Subscribed users see a Manage billing button instead, which opens the Customer Portal.
Test with the Stripe CLI
Stripe can't send webhooks to localhost, so we will use the Stripe CLI to forward them to our local server:
stripe login
stripe listen --forward-to localhost:3000/api/stripe/webhookThe stripe listen command prints a signing secret (whsec_...). We will copy it into the STRIPE_WEBHOOK_SECRET variable of our .env file and restart our development server.
Now, let's sign in and go to http://localhost:3000/pricing. When we click on Subscribe, we can pay with the test card 4242 4242 4242 4242, any future expiration date, and any CVC. Stripe will then redirect us to our premium page, and the terminal running stripe listen will show the events that reached our webhook (all with a 200 status).
We can also send test events with stripe trigger:
stripe trigger customer.subscription.updatedTriggered events use new test customers that aren't connected to our users, so syncSubscription ignores them, but they are useful to check that our endpoint responds correctly.
Conclusion
We have now completed our Stripe subscriptions integration with TanStack Start. Our users can subscribe through Checkout, our webhook keeps our database in sync, our premium content is protected by a typed middleware, and our users can manage their plan through the Customer Portal.
If you are using Better Auth, it also offers an official Stripe plugin that handles customers, subscriptions, and webhooks for you. Building it ourselves gives us full control over our data and helps us understand every piece. From here, you can add multiple plans, free trials (with subscription_data.trial_period_days), or handle invoice.payment_failed events to notify users when a payment fails.