# Build a Full SaaS Starter with Next.js: Auth, Postgres, Stripe and Email

Wire up the core of a paid Next.js app: users sign up, pay with Stripe Checkout, a verified webhook updates their plan in Postgres, and they get a welcome email. Each piece links to a focused guide.

*Advanced · 45 min · Updated Nov 18, 2026*

## What you'll build

- Email and Google sign-up with a session cookie and a Data Access Layer
- A `subscriptions` table in Postgres keyed by the Auth user id
- A Stripe Checkout button and a Customer Portal link
- A webhook that verifies Stripe's signature and keeps each user's plan in sync
- Welcome emails on sign-up and on upgrade

## Before you start

- A Next.js 16 app using the App Router (`npx create-next-app@latest`)
- A free CloudHike.dev account
- A Stripe account in test mode, with one recurring Price created
- The [Stripe CLI](https://docs.stripe.com/stripe-cli) for testing webhooks locally

## What you are building

A SaaS app needs the same four pieces almost every time. This guide connects them and keeps each step short. When a step needs more depth, it links to the guide that covers it in full.

| Piece | Service | Deep dive |
| --- | --- | --- |
| Sign-up, login, sessions | CloudHike Auth | [Email and Google login](https://cloudhike.dev/guides/nextjs-authentication-email-google), [Protect routes](https://cloudhike.dev/guides/protect-routes-nextjs-proxy) |
| App data and plans | CloudHike Postgres + Drizzle | [Postgres with Drizzle](https://cloudhike.dev/guides/postgres-nextjs-drizzle) |
| Payments | Stripe Checkout + webhooks | This guide |
| Transactional email | CloudHike Email | [Send email from Next.js](https://cloudhike.dev/guides/send-email-nextjs) |

1. A user signs up. Auth returns a token, which you keep in an HTTP-only cookie, and you send a welcome email.
2. They click **Upgrade**. A Server Action creates a Stripe Checkout Session and redirects them to Stripe.
3. They pay. Stripe calls your webhook. You verify the signature and set their plan to `pro` in Postgres.
4. Pages and Server Actions read the plan from Postgres to unlock paid features.

> **Note:** The webhook, not the redirect back from Checkout, is the source of truth. Users can close the tab before the redirect, and anyone can open your success URL by hand.

## Step 1: Deploy services and set environment variables

1. Sign in at [cloudhike.dev](https://cloudhike.dev/signup) and create a project.
2. Deploy **Postgres** and **Auth**. Deploy Postgres first if you'd like Auth to store users in its `auth` schema; your app's tables stay in `public`.
3. Deploy **Email**: tick the box to accept the email policy, then click **Deploy**.
4. Click **Copy as .env**, paste into `.env.local`, then add your Stripe keys and `APP_URL`.

*.env.local*

```bash
# CloudHike (from Copy as .env)
DATABASE_URL=postgresql://...
DIRECT_URL=postgresql://...
AUTH_URL=https://...
AUTH_PUBLISHABLE_KEY=...
AUTH_SECRET_KEY=...
EMAIL_API_URL=https://...
EMAIL_API_KEY=...

# Stripe (Dashboard → Developers → API keys, test mode)
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...   # printed by `stripe listen` in Step 5
STRIPE_PRICE_PRO=price_...        # the recurring Price for your Pro plan

APP_URL=http://localhost:3000
```

*Terminal*

```bash
npm install drizzle-orm pg stripe server-only
npm install -D drizzle-kit @types/pg
```

> **Warning:** None of these may start with `NEXT_PUBLIC_`. Every one of them is used only in server code.

## Step 2: Add auth and a welcome email

Follow [Add Email/Password and Google Login to Next.js](https://cloudhike.dev/guides/nextjs-authentication-email-google) for `lib/auth.ts`, the login and sign-up forms and the Google callback. Then follow [Protect Routes and Server Actions](https://cloudhike.dev/guides/protect-routes-nextjs-proxy) for `proxy.ts` and `lib/dal.ts`. You end up with these files:

| File | What it gives you |
| --- | --- |
| `lib/auth.ts` | Calls to `sign-up/email`, `sign-in/email`, `get-session` and `sign-out`, plus cookie helpers |
| `lib/dal.ts` | `getCurrentUser()` and `requireUser()`, cached per request |
| `proxy.ts` | Redirects visitors without a session cookie away from `/dashboard` |
| `lib/email.ts` | A server-only `sendEmail()` from the [email guide](https://cloudhike.dev/guides/send-email-nextjs#helper) |

Send a welcome email from the sign-up action. `after()` sends it once the response is on its way, so a slow email never slows down sign-up.

*app/(auth)/actions.ts (sign-up, with the welcome email)*

```ts
"use server";

import { after } from "next/server";
import { redirect } from "next/navigation";
import { AuthError, setSessionCookie, signUpWithEmail } from "@/lib/auth";
import { sendEmail } from "@/lib/email";

export type FormState = { error: string } | null;

export async function signUp(_prev: FormState, form: FormData): Promise<FormState> {
  const name = String(form.get("name") ?? "").trim();
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  const password = String(form.get("password") ?? "");

  if (!name || !/^\S+@\S+\.\S+$/.test(email)) return { error: "Enter your name and a valid email." };
  if (password.length < 8) return { error: "Use a password of at least 8 characters." };

  try {
    const { token } = await signUpWithEmail(name, email, password);
    await setSessionCookie(token);
  } catch (err) {
    if (err instanceof AuthError) return { error: err.message };
    console.error(err);
    return { error: "Something went wrong. Please try again." };
  }

  after(() =>
    sendEmail({
      to: email,
      subject: "Welcome to Acme",
      text: `Hi ${name},\n\nThanks for signing up! Your dashboard is ready: ${process.env.APP_URL}/dashboard`,
      replyTo: "support@example.com",
    }).catch(console.error),
  );

  redirect("/dashboard");
}
```

This text email is plain on purpose: `name` came from the form, so if you add an `html` version, escape it first as the [email guide](https://cloudhike.dev/guides/send-email-nextjs#contact-form) shows.

## Step 3: Store plans in Postgres

Users live in CloudHike Auth, so your database doesn't need its own `users` table. Key your rows by the Auth user id instead. One `subscriptions` row per user holds their Stripe ids and plan.

*db/schema.ts*

```ts
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";

export const subscriptions = pgTable("subscriptions", {
  // The CloudHike Auth user id (user.id from get-session).
  userId: text("user_id").primaryKey(),
  email: text("email").notNull(),
  stripeCustomerId: text("stripe_customer_id").unique(),
  stripeSubscriptionId: text("stripe_subscription_id").unique(),
  plan: text("plan", { enum: ["free", "pro"] }).notNull().default("free"),
  // Stripe's subscription status: active, past_due, canceled...
  status: text("status"),
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});

export type Plan = (typeof subscriptions.$inferSelect)["plan"];
```

Use the `db/index.ts` client and `drizzle.config.ts` from the [Drizzle guide](https://cloudhike.dev/guides/postgres-nextjs-drizzle#client). Migrations run over `DIRECT_URL`, and queries use the pooled `DATABASE_URL`.

*Terminal*

```bash
npx drizzle-kit generate
npx drizzle-kit migrate
```

Add a plan lookup to the Data Access Layer. A user with no row yet is on the free plan. Put the new imports at the top of the file, next to the existing ones.

*lib/dal.ts (additions)*

```ts
import { eq } from "drizzle-orm";
import { db } from "@/db";
import { subscriptions, type Plan } from "@/db/schema";

export const getAccount = cache(async () => {
  const user = await requireUser();
  const [row] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id));
  const plan: Plan = row?.plan ?? "free";
  return { user, plan, stripeCustomerId: row?.stripeCustomerId ?? null };
});
```

## Step 4: Start Stripe Checkout from a Server Action

*lib/stripe.ts*

```ts
import "server-only";
import Stripe from "stripe";

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

The action creates a Stripe Customer the first time, saves its id, and sends the user to Checkout. `client_reference_id` and the subscription's `metadata` carry the Auth user id, so the webhook knows whose plan to change.

*app/dashboard/billing/actions.ts*

```ts
"use server";

import { redirect } from "next/navigation";
import { db } from "@/db";
import { subscriptions } from "@/db/schema";
import { getAccount } from "@/lib/dal";
import { stripe } from "@/lib/stripe";

const billingUrl = `${process.env.APP_URL}/dashboard/billing`;

export async function startCheckout() {
  const { user, plan, stripeCustomerId } = await getAccount();
  if (plan === "pro") redirect("/dashboard/billing");

  let customerId = stripeCustomerId;
  if (!customerId) {
    const customer = await stripe.customers.create(
      { email: user.email, name: user.name, metadata: { userId: user.id } },
      { idempotencyKey: `customer-${user.id}` }, // a double click won't make two
    );
    customerId = customer.id;
    await db
      .insert(subscriptions)
      .values({ userId: user.id, email: user.email, stripeCustomerId: customerId })
      .onConflictDoUpdate({ target: subscriptions.userId, set: { stripeCustomerId: customerId } });
  }

  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    customer: customerId,
    client_reference_id: user.id,
    line_items: [{ price: process.env.STRIPE_PRICE_PRO!, quantity: 1 }],
    subscription_data: { metadata: { userId: user.id } },
    success_url: `${billingUrl}?checkout=success`,
    cancel_url: billingUrl,
  });

  if (!session.url) throw new Error("Stripe did not return a Checkout URL");
  redirect(session.url);
}

export async function openBillingPortal() {
  const { stripeCustomerId } = await getAccount();
  if (!stripeCustomerId) redirect("/dashboard/billing");

  const portal = await stripe.billingPortal.sessions.create({
    customer: stripeCustomerId,
    return_url: billingUrl,
  });
  redirect(portal.url);
}
```

*app/dashboard/billing/page.tsx*

```tsx
import { Suspense } from "react";
import { getAccount } from "@/lib/dal";
import { openBillingPortal, startCheckout } from "./actions";

async function Billing({ searchParams }: { searchParams: PageProps<"/dashboard/billing">["searchParams"] }) {
  const { plan } = await getAccount();
  const { checkout } = await searchParams;

  if (plan === "pro") {
    return (
      <>
        <p>You're on <strong>Pro</strong>. Thank you!</p>
        <form action={openBillingPortal}>
          <button>Manage billing</button>
        </form>
      </>
    );
  }

  return (
    <>
      {/* The webhook can land a second or two after the redirect. */}
      {checkout === "success" && <p>Payment received. Your plan updates in a moment, refresh to check.</p>}
      <p>You're on the <strong>Free</strong> plan.</p>
      <form action={startCheckout}>
        <button>Upgrade to Pro</button>
      </form>
    </>
  );
}

export default function BillingPage({ searchParams }: PageProps<"/dashboard/billing">) {
  return (
    <main className="grid gap-4 p-8">
      <h1>Billing</h1>
      <Suspense fallback={<p>Loading…</p>}>
        <Billing searchParams={searchParams} />
      </Suspense>
    </main>
  );
}
```

Turn on the Customer Portal once in the Stripe Dashboard (Settings → Billing → Customer portal). It lets users update cards, see invoices and cancel without you building any of it.

## Step 5: Verify the Stripe webhook and update the plan

Stripe signs every webhook. `stripe.webhooks.constructEvent()` checks that signature against the **raw** request body, byte for byte. Read the body with `request.text()`. If you call `request.json()` first, the signature check fails.

*app/api/stripe/webhook/route.ts*

```ts
import { eq } from "drizzle-orm";
import { after } from "next/server";
import type Stripe from "stripe";
import { db } from "@/db";
import { subscriptions, type Plan } from "@/db/schema";
import { sendEmail } from "@/lib/email";
import { stripe } from "@/lib/stripe";

// past_due keeps access while Stripe retries the card.
const planFor = (status: Stripe.Subscription.Status): Plan =>
  status === "active" || status === "trialing" || status === "past_due" ? "pro" : "free";

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

  let event: Stripe.Event;
  try {
    const rawBody = await request.text();
    event = stripe.webhooks.constructEvent(rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch (err) {
    console.error("Stripe signature check failed", err);
    return new Response("Invalid signature", { status: 400 });
  }

  try {
    switch (event.type) {
      case "checkout.session.completed": {
        const session = event.data.object;
        const userId = session.client_reference_id;
        if (session.mode !== "subscription" || !userId || typeof session.subscription !== "string") break;

        // Read the live subscription, so out-of-order events can't leave a stale status.
        const sub = await stripe.subscriptions.retrieve(session.subscription);
        const [before] = await db.select().from(subscriptions).where(eq(subscriptions.userId, userId));
        const plan = planFor(sub.status);

        await db
          .update(subscriptions)
          .set({ stripeSubscriptionId: sub.id, plan, status: sub.status, updatedAt: new Date() })
          .where(eq(subscriptions.userId, userId));

        // Stripe retries webhooks, so only email on the first switch to Pro.
        if (before && before.plan !== "pro" && plan === "pro") {
          after(() =>
            sendEmail({
              to: before.email,
              subject: "You're on Acme Pro",
              text: `Thanks for upgrading! Pro features are now unlocked.\n\nManage your plan and invoices any time: ${process.env.APP_URL}/dashboard/billing`,
            }).catch(console.error),
          );
        }
        break;
      }

      case "customer.subscription.updated":
      case "customer.subscription.deleted": {
        const sub = event.data.object;
        const userId = sub.metadata.userId; // set in subscription_data.metadata at Checkout
        if (!userId) break;

        await db
          .update(subscriptions)
          .set({ stripeSubscriptionId: sub.id, plan: planFor(sub.status), status: sub.status, updatedAt: new Date() })
          .where(eq(subscriptions.userId, userId));
        break;
      }
    }
  } catch (err) {
    console.error("Stripe webhook failed", event.type, err);
    // A 5xx tells Stripe to retry later.
    return new Response("Webhook handler failed", { status: 500 });
  }

  return Response.json({ received: true });
}
```

A canceled subscription ends with `customer.subscription.deleted` and status `canceled`, which sets the plan back to `free`. Stripe can email official receipts and invoices itself (Settings → Customer emails). Your CloudHike email is the friendly "welcome to Pro" note on top.

### Test it locally

*Terminal*

```bash
stripe login
stripe listen --forward-to localhost:3000/api/stripe/webhook
# Copy the whsec_... it prints into STRIPE_WEBHOOK_SECRET, then restart npm run dev
```

Sign up in your app, open `/dashboard/billing`, click **Upgrade to Pro** and pay with Stripe's test card `4242 4242 4242 4242`, any future date and any CVC. Watch the `stripe listen` output, then refresh the billing page: it shows Pro, and the welcome email arrives. You can check the row on the **Data** tab of **Open database**.

> **Warning:** Keep `/api/stripe/webhook` out of your `proxy.ts` matcher. Stripe has no session cookie, so a login redirect would make every webhook fail. The signature check is what protects this route.

## Step 6: Gate paid features on the server

Check the plan where the work happens, not only in the UI. Hiding a button is good UX, but the Server Action must refuse on its own, because anyone can call it.

*app/dashboard/reports/actions.ts*

```ts
"use server";

import { getAccount } from "@/lib/dal";

export type ExportState = { ok: boolean; message: string } | null;

export async function exportReport(_prev: ExportState, _form: FormData): Promise<ExportState> {
  const { user, plan } = await getAccount(); // redirects to /login when signed out
  if (plan !== "pro") return { ok: false, message: "Exports are a Pro feature. Upgrade on the Billing page." };

  // ...build the export for user.id here...
  return { ok: true, message: `Your export is ready, ${user.name}.` };
}
```

From here, add whatever your product needs. Common next steps are [rate limits with Redis](https://cloudhike.dev/guides/rate-limit-nextjs-redis), [file uploads to S3 storage](https://cloudhike.dev/guides/s3-file-upload-nextjs-presigned-url) and [background jobs](https://cloudhike.dev/guides/background-jobs-nextjs) for slow work like that export.

## Production checklist

- Add every variable from Step 1 to your host's environment settings, with `APP_URL` set to your real `https://` domain.
- In Stripe, switch to live mode, create the live Price, and add a webhook endpoint for `https://yourdomain.com/api/stripe/webhook` with `checkout.session.completed`, `customer.subscription.updated` and `customer.subscription.deleted`. Use that endpoint's signing secret in production.
- Run Drizzle migrations as a deploy step over `DIRECT_URL` before the new code goes live.
- Add your production domain under **Sites users can return to** on the Auth card, for Google sign-in.
- [Verify your sending domain](https://cloudhike.dev/docs/email#domains) so welcome emails come from your brand and stay out of spam.
- Check your CloudHike plan's Auth, Postgres and Email allowances on the [pricing page](https://cloudhike.dev/pricing) against your expected users.

## FAQ

### Why does my Stripe webhook signature verification fail in Next.js?

Usually the body was parsed before verification. constructEvent needs the raw body exactly as Stripe sent it, so read it with await request.text() in the Route Handler and pass that string. Also check that STRIPE_WEBHOOK_SECRET matches the endpoint or the stripe listen session you are using.

### Should I update the plan on the Checkout success page or in the webhook?

In the webhook. Users can close the tab before the redirect, and anyone can open the success URL by hand. The success page should only say that the payment is being confirmed.

### Do I need my own users table if I use CloudHike Auth?

No. Auth stores users and sessions. Keep app-specific data, such as plans or settings, in your own tables keyed by the Auth user id.

### How do users cancel or change their card?

Send them to the Stripe Customer Portal with stripe.billingPortal.sessions.create. Stripe handles cards, invoices and cancellation, and your webhook updates the plan when the subscription changes.

### Is this Next.js SaaS starter free to run?

You can build and test it on CloudHike's free plan and Stripe's test mode. In production, Stripe charges its own payment fees, and CloudHike usage depends on your plan. See the pricing page for current details.
