Billing Tutorial
Add subscription billing to your app with AuthGate and Stripe. By the end you will have a pricing page, Stripe Checkout and feature gating, tested with Stripe's test cards.
What you will build
- A Stripe connection for your AuthGate project
- Pro and Enterprise plans, with monthly and yearly prices
- A pricing page that sends users to Stripe Checkout
- Features that appear only on the plans that include them
- A webhook handler that hears when subscriptions start, change and end
Everything runs in Stripe test mode, so no real money moves while you build.
Prerequisites
- An AuthGate project with sign-in working (see the Quickstart)
- A Stripe account
@auth-gate/reactin your app, and the AuthGate route handler mounted at/api/auth:createCatchAllHandlerorcreateAuthGatein Next.js,createAuthRouteselsewhere
The billing components call your app's own /api/auth/billing/* routes, which that handler answers for the signed-in user.
Step 1: Connect Stripe
1a. Copy your API keys
Open the Stripe API keys page in test mode and copy the secret key (sk_test_...) and the publishable key (pk_test_...).
1b. Connect them in AuthGate
- Open your project in the AuthGate dashboard and click the Billing tab.
- Click Connect Stripe, enter both keys and pick a default currency.
- Click Connect.
AuthGate checks the keys and adds a webhook endpoint to your Stripe account, so subscriptions reach AuthGate as soon as Stripe starts them. You don't set up a webhook in Stripe yourself.
1c. Turn on the customer portal
Your users will change plans and cancel in Stripe's customer portal. Open Customer portal settings in test mode, allow plan switching, updating payment methods and canceling, and save. You will add your products to the portal's plan list after step 2.
Step 2: Create your plans
Users without a subscription are on your free tier, so you only create the paid plans.
2a. Create the products
Go to Billing → Products in the AuthGate dashboard and click New Product:
| Product | Features |
|---|---|
| Pro | advanced_analytics, priority_support |
| Enterprise | advanced_analytics, priority_support, custom_integrations, sla |
The features are flags that you will check in step 5.
2b. Add prices
Open each product and click Add Price:
| Product | Amount | Interval |
|---|---|---|
| Pro | $29 | Monthly |
| Pro | $290 | Yearly |
| Enterprise | $99 | Monthly |
| Enterprise | $990 | Yearly |
The dashboard takes amounts in dollars and stores them in cents. Each product and price you save also appears in your Stripe account. You can define the same plans in code instead; see Billing as Code.
2c. List the plans in the customer portal
Back in Stripe's customer portal settings, add Pro and Enterprise to the products users can switch between, and save.
Step 3: Add a pricing page
<PricingTable /> shows your active plans. Here each price gets a <CheckoutForm /> button, which sends the user straight to Stripe Checkout:
app/pricing/page.tsx
"use client";
import { PricingTable, CheckoutForm } from "@auth-gate/react";
export default function PricingPage() {
return (
<main className="max-w-5xl mx-auto py-16 px-4">
<h1 className="text-4xl font-bold text-center mb-12">Pricing</h1>
<PricingTable
renderAction={(plan, priceId) => (
<CheckoutForm priceId={priceId} successUrl="/dashboard?subscribed=1" cancelUrl="/pricing" />
)}
/>
</main>
);
}
The table reads your plans from GET /api/auth/billing/products.
Step 4: Start subscriptions
<CheckoutForm /> does the whole job in the browser:
- It posts the price to your app's
/api/auth/billing/checkout. - Your server asks AuthGate, with your API key, for a Checkout page for the signed-in user.
- The browser goes to Stripe Checkout, where the user enters their card. The card never touches your server.
- Stripe starts the subscription and sends the user to
successUrl. - Stripe reports the subscription to AuthGate, usually within seconds, and AuthGate records it.
From then on Stripe renews the subscription and retries failed payments.
To start Checkout from your server instead, for example in a Next.js server action, call client.billing.checkout and redirect:
app/pricing/actions.ts
"use server";
import { redirect } from "next/navigation";
import { client, session } from "@/lib/auth"; // the result of createAuthGate()
export async function subscribe(plan: string) {
const user = await session.getSession();
if (!user) redirect("/login");
const { url } = await client.billing.checkout({
userId: user.id,
plan,
interval: "monthly",
successUrl: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard?subscribed=1`,
cancelUrl: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
});
redirect(url);
}
In test mode, pay with 4242 4242 4242 4242, any future expiry date and any CVC. See Stripe's testing docs for cards that fail.
Step 5: Gate features by plan
Option A: The <BillingGate> component
Wrap any UI that only some plans include:
components/analytics-panel.tsx
import { BillingGate } from "@auth-gate/react";
export function AnalyticsPanel() {
return (
<BillingGate
feature="advanced_analytics"
fallback={<a href="/pricing">Advanced analytics comes with Pro. Upgrade</a>}
>
<h2>Analytics</h2>
{/* your analytics UI */}
</BillingGate>
);
}
Option B: The useEntitlements hook
components/feature-list.tsx
import { useEntitlements } from "@auth-gate/react";
export function FeatureList() {
const { entitlements, loading } = useEntitlements();
if (loading) return <p>Loading...</p>;
const features = entitlements?.features ?? [];
return (
<ul>
{features.includes("priority_support") && <li>Priority support</li>}
{features.includes("sla") && <li>99.9% uptime SLA</li>}
</ul>
);
}
On the server
Hiding a button is not enough for paid features: check on the server too.
app/api/reports/route.ts
import { NextResponse } from "next/server";
import { createBillingHelpers } from "@auth-gate/nextjs";
import { session } from "@/lib/auth";
const billing = createBillingHelpers({
baseUrl: process.env.AUTHGATE_URL!,
apiKey: process.env.AUTHGATE_API_KEY!,
});
export async function GET() {
const user = await session.getSession();
if (!user) return NextResponse.json({ error: "Sign in first" }, { status: 401 });
if (!(await billing.checkEntitlement({ userId: user.id, feature: "advanced_analytics" }))) {
return NextResponse.json({ error: "Reports need the Pro plan" }, { status: 403 });
}
// ... build and return the report
}
Users in a trial, and users whose payment Stripe is retrying, keep their plan's features.
Step 6: Listen to billing events
6a. Add an endpoint
In the AuthGate dashboard, go to Billing → Webhooks, click Add Endpoint, enter your handler's URL, such as https://your-app.com/api/billing/webhook, and pick the events:
| Event | When it is sent |
|---|---|
subscription.created | Stripe has started a subscription |
subscription.updated | The subscription changed: plan, status, or a scheduled cancellation |
subscription.canceled | The subscription ended |
AuthGate shows the endpoint's signing secret once. Store it as AUTHGATE_BILLING_WEBHOOK_SECRET.
6b. Handle the events
Each delivery carries the event name in the X-AuthGate-Event header and is signed in X-AuthGate-Signature:
app/api/billing/webhook/route.ts
import crypto from "node:crypto";
import { NextResponse } from "next/server";
const SECRET = process.env.AUTHGATE_BILLING_WEBHOOK_SECRET!;
export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get("x-authgate-signature") ?? "";
const timestamp = request.headers.get("x-authgate-timestamp") ?? "";
const expected = `v1=${crypto.createHmac("sha256", SECRET).update(`${timestamp}.${body}`).digest("hex")}`;
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
// The timestamp is in milliseconds. Refuse old deliveries, which could be replays.
if (Date.now() - Number(timestamp) > 5 * 60 * 1000) {
return NextResponse.json({ error: "Event too old" }, { status: 400 });
}
const event = request.headers.get("x-authgate-event");
const data = JSON.parse(body); // { subscriptionId, endUserId, status, cancelAtPeriodEnd, currentPeriodEnd }
switch (event) {
case "subscription.created":
// e.g. send a welcome email
break;
case "subscription.canceled":
// e.g. send a win-back email
break;
}
return NextResponse.json({ received: true });
}
6c. Send a test event
In Billing → Webhooks, click Test next to your endpoint. AuthGate sends a signed test event and shows your handler's response.
Step 7: Test the full flow
- Open your pricing page, pick Pro and pay on Stripe Checkout with
4242 4242 4242 4242. Stripe sends you back to/dashboard?subscribed=1. - In Billing → Subscriptions, the new subscription shows as
active. Stripe's own dashboard shows the payment and its invoice. - Pages behind
<BillingGate feature="advanced_analytics">now show their content. - Add
<SubscriptionManager />to an account page, click Manage subscription and switch to Enterprise in the portal. When you come back, the subscription shows Enterprise. - Cancel in the portal. The subscription stays
activeuntil the end of the period, marked as canceling.
Going live
- In Stripe, leave test mode and copy your live keys (
sk_live_...,pk_live_...). - In AuthGate, connect Stripe again with the live keys. AuthGate replaces its webhook endpoint and creates your plans in live mode.
- In Stripe's live mode, save the customer portal settings and list your products, as in steps 1c and 2c.
- To have Stripe handle sales tax and VAT as the merchant of record, see Managed Payments.
Go-live checklist
- Live keys connected in AuthGate
- Customer portal settings saved in live mode, with your products listed
- Pricing page shows the live prices
- A real card completes Checkout
- Gated features appear for each plan
- Plan change and cancellation tested in the portal
- Your webhook handler answers the test event
Next steps
- SDK Components: every billing component and its props
- Entitlements: more ways to gate features
- Webhooks: the billing events in detail
- Billing API Endpoints: the routes behind the components