Skip to main content
0 reactions

Better Auth Tutorial — Part 4: Protect Pages, Server Actions and API Routes

A dark purple card titled Protect Pages, Server Actions and API Routes, labelled Better Auth Tutorial Part 4, with a shield and padlock and three facts: getSession() on pages, proxy.ts redirects early and 401 from API routes.
Better Auth Tutorial, Part 4: protect pages, server actions and API routes.

In Part 3, Lena Park signed up and signed in. Hiding a page in the browser doesn’t make it private, though: the check has to happen on the server. In this part you protect pages, server actions and API routes with Better Auth in Next.js, so only signed-in people get in.

By the end of this part, you’ll have:

  • a private account page at /account that shows the signed-in person’s name and email address
  • proxy.ts, which sends signed-out visitors to the sign-in page before the page even starts
  • a header that reads the session on the server, with Sign out as a server action
  • an API route at /api/account that returns your account data, and an error with status 401 to anyone who isn’t signed in

This is Part 4 of the Better Auth Tutorial. The parts in Module B, Sessions and Users:

  • Part 4: Protect Pages, Server Actions and API Routes (you are here)
  • Part 5: Sessions: Expiry, Cookie Cache and Signing Out Everywhere
  • Part 6: Users and Accounts: Custom Fields, Change Email and Delete Account
All parts of the Better Auth Tutorial

Module A: Start Here

Module B: Sessions and Users

Module C: Email and Passwordless

  • Part 7: Email Verification and Password Reset
  • Part 8: Passwordless Sign-In: Magic Links and Email Codes

Module D: Social Sign-In

  • Part 9: Sign In with GitHub
  • Part 10: Account Linking and OAuth Access Tokens

Module E: Stronger Sign-In

  • Part 11: Two-Factor Authentication (2FA)
  • Part 12: Passkeys
  • Part 13: Rate Limits, Captcha and Breached Passwords

Module F: Roles and Organizations

  • Part 14: Admin Plugin: Roles, Bans and Impersonation
  • Part 15: Custom Roles and Permissions
  • Part 16: Organizations and Teams

Module G: Customize

  • Part 17: Hooks, Database Hooks and the Server API
  • Part 18: Database Adapters and Secondary Storage
  • Part 19: Write Your Own Better Auth Plugin

Module H: APIs and Identity Provider

  • Part 20: API Keys
  • Part 21: JWT, Bearer and One-Time Tokens
  • Part 22: Be an OAuth 2.1 and OpenID Connect Provider
  • Part 23: MCP Servers and CLI Sign-In

Module I: Enterprise and Payments

  • Part 24: Single Sign-On with OIDC and SAML
  • Part 25: Subscriptions with Stripe

Module J: Ship It

  • Part 26: Production Security Checklist
  • Part 27: Deploy to Vercel with a Free Neon Database
  • Part 28: Migrate from Auth.js (NextAuth) to Better Auth
  • Part 29: Final Project, Cheat Sheet and What to Learn Next

Cost: free. Everything in this part runs on your own computer.

Every command and output on this page is real, run on Better Auth 1.7 with Next.js 16.

Get the Source Code

Get the complete source code of Next.js Authentication with Better Auth and PostgreSQL on Dewiride Store → (opens in a new tab)
It’s the finished Bookshop app with everything this part protects: the account page, the sign-out action and the account data route, plus a settings check and a README.

Prerequisites

  • the Bookshop project from Part 3, with Lena Park’s account. Parts 2 and 3 take you there from an empty folder.

Where Your Project Is Now

Your project is the Bookshop as Part 3 left it: sign-up and sign-in pages, a header that shows who’s signed in, and Lena’s account in PostgreSQL. So far only the browser asks who’s signed in: the header uses useSession. In this part the server checks the session before it shows anything private. You start with no changes.

Step 1: Start the Database and the App

Open Terminal (PowerShell on Windows) in the bookshop folder. Start the PostgreSQL database from Part 2 in the background:

TerminalBash
docker compose up -d

Then start the app, and leave it running while you work:

TerminalBash
npm run dev

When Terminal shows ✓ Ready, open http://localhost:3000 and sign in as Lena.

Step 2: Protect a Page on the Server

The account page shows Lena’s name and email address, so only Lena may see it. A page that’s rendered on the server can ask Better Auth for the session before it shows anything:

app/account/page.tsx (excerpt)TypeScript
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    redirect("/sign-in");
  }
  • auth.api.getSession is Better Auth’s way to read the session on the server. It takes the request’s headers, which carry the session cookie, and returns the session with its user, or null.
  • headers() comes from Next.js. It returns the headers of the request the page is answering.
  • redirect("/sign-in") sends anyone without a session to the sign-in page, so the rest of the page never runs for them.
  • After the check, session.user is the signed-in person, with session.user.name and session.user.email.

In the app folder, create a folder named account, and in it a file named page.tsx:

app/account/page.tsxTypeScript
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { auth } from "@/lib/auth";

export default function AccountPage() {
  return (
    <main className="mx-auto w-full max-w-3xl flex-1 px-6 py-12">
      <h1 className="text-3xl font-semibold">Your account</h1>
      <Suspense fallback={<p className="mt-4">Loading your account…</p>}>
        <AccountDetails />
      </Suspense>
    </main>
  );
}

async function AccountDetails() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    redirect("/sign-in");
  }

  return (
    <div className="mt-4">
      <p>Name: {session.user.name}</p>
      <p>Email: {session.user.email}</p>
      <a href="/api/account" className="mt-6 inline-block underline">
        Your account data as JSON
      </a>
    </div>
  );
}

The page has two parts. AccountPage shows the heading at once. AccountDetails reads the session, and <Suspense> shows “Loading your account…” until it’s done. Next.js 16 needs this split: with Cache Components, which a new app turns on, anything that reads the request has to sit inside <Suspense>. Without it, npm run build stops with “Next.js encountered uncached or runtime data during prerendering”.

The link at the bottom opens your account data, which you add in Step 6. Open http://localhost:3000/account while you’re signed in as Lena:

The Bookshop account page with the heading Your account, the lines Name: Lena Park and Email: lena@example.com, and the link Your account data as JSON.
Only a signed-in person sees this page.

Click Sign out in the header and open /account again: you get the sign-in page instead.

Step 3: Redirect Early with proxy.ts

Next.js runs proxy.ts before it starts on a page, so it’s a fast place to turn away visitors who aren’t signed in. Better Auth’s docs recommend a quick check there, one that only looks for the session cookie and doesn’t ask the database:

proxy.ts (excerpt)TypeScript
  const sessionCookie = getSessionCookie(request);

  if (!sessionCookie) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }
  • getSessionCookie(request) returns Better Auth’s session cookie from the request, or null when there isn’t one. It doesn’t check that the session is real.
  • NextResponse.redirect answers with a redirect to /sign-in. new URL("/sign-in", request.url) builds that address from the request’s own one.
  • NextResponse.next() lets the request carry on to the page.
  • matcher lists the paths the proxy runs on: here only /account.

In the bookshop folder, next to package.json, create a file named proxy.ts:

proxy.tsTypeScript
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";

export function proxy(request: NextRequest) {
  const sessionCookie = getSessionCookie(request);

  if (!sessionCookie) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/account"],
};

Anyone can send a made-up cookie, so this check alone protects nothing. That’s why the account page keeps its own getSession check. The proxy only turns away visitors who clearly aren’t signed in, before the page does any work.

Open /account while signed in. The line Next.js prints for the request in Terminal now includes the time the proxy took:

Output (the lines that matter)Plain text
 GET /account 200 in 64ms (next.js: 23ms, proxy.ts: 3ms, application-code: 38ms)

Signed out, the proxy sends you to the sign-in page before the account page starts.

Advertisement

Step 4: Sign Out with a Server Action

A server action is a function that runs on the server when a form is sent. Next.js gives each one an address of its own, so anyone can call it, not only your form. The Next.js docs say to treat server actions like public API endpoints: every one checks the session itself.

First, let Better Auth set cookies from server actions. Open lib/auth.ts, import nextCookies from better-auth/next-js, and add it after emailAndPassword:

lib/auth.ts (excerpt)TypeScript
  plugins: [nextCookies()],
  • Signing out clears the session cookie. A server action can only change cookies through Next.js’s own cookies helper, and nextCookies() passes Better Auth’s cookies to it.
  • Keep it last in the plugins list, as the Better Auth docs ask.

The complete file:

lib/auth.tsTypeScript
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";
import { Pool } from "pg";

export const auth = betterAuth({
  database: new Pool({
    connectionString: process.env.DATABASE_URL,
  }),
  emailAndPassword: {
    enabled: true,
  },
  plugins: [nextCookies()],
});

Next, the sign-out action. In the app folder, create a file named actions.ts:

app/actions.tsTypeScript
"use server";

import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";

export async function signOutAction() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    redirect("/sign-in");
  }

  await auth.api.signOut({
    headers: await headers(),
  });

  redirect("/");
}
  • "use server" at the top makes every function in the file a server action.
  • signOutAction checks the session first, and sends anyone without one to the sign-in page.
  • auth.api.signOut ends the session in the database, and nextCookies clears the cookie in the browser.
  • redirect("/") takes Lena back to the home page.

Now the header. In Part 3 it asked for the session from the browser, with useSession. That hook only notices changes the auth client makes in the browser, so after a sign-out on the server it would still show Lena’s name. Reading the session on the server, like the account page, keeps the header right. Replace everything in components/user-menu.tsx with this file:

components/user-menu.tsxTypeScript
import { headers } from "next/headers";
import Link from "next/link";
import { signOutAction } from "@/app/actions";
import { auth } from "@/lib/auth";

export async function UserMenu() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    return (
      <nav className="flex gap-4 text-sm">
        <Link href="/sign-in">Sign in</Link>
        <Link href="/sign-up">Sign up</Link>
      </nav>
    );
  }

  return (
    <div className="flex items-center gap-4 text-sm">
      <Link href="/account">Signed in as {session.user.name}</Link>
      <form action={signOutAction}>
        <button
          type="submit"
          className="rounded border border-zinc-300 px-3 py-1 dark:border-zinc-700"
        >
          Sign out
        </button>
      </form>
    </div>
  );
}
  • The menu is now a server component: there’s no "use client", and it reads the session with auth.api.getSession.
  • Lena’s name links to her account page.
  • Sign out is a form whose action is signOutAction, so it works even before the page’s JavaScript has loaded.

The menu reads the request too, so it needs <Suspense> as well. Open app/layout.tsx and wrap it:

app/layout.tsx (excerpt)TypeScript
          <Suspense>
            <UserMenu />
          </Suspense>

Suspense is imported from react. The complete file:

app/layout.tsxTypeScript
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import Link from "next/link";
import { Suspense } from "react";
import { UserMenu } from "@/components/user-menu";
import "./globals.css";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Bookshop",
  description: "A bookshop with sign-in by Better Auth.",
};

export default function RootLayout({ children }: LayoutProps<"/">) {
  return (
    <html
      lang="en"
      className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
    >
      <body className="min-h-full flex flex-col">
        <header className="flex items-center justify-between border-b border-zinc-200 px-6 py-4 dark:border-zinc-800">
          <Link href="/" className="font-semibold">
            Bookshop
          </Link>
          <Suspense>
            <UserMenu />
          </Suspense>
        </header>
        {children}
      </body>
    </html>
  );
}

Click Sign out in the header. The home page opens with the sign-in links:

The right end of the Bookshop header after signing out, with the links Sign in and Sign up.
Signed out by the server action.

In Terminal, Next.js shows the server action it ran:

Output (the lines that matter)Plain text
 POST / 200 in 64ms (next.js: 1.0ms, application-code: 64ms)
  └─ ƒ signOutAction() in 25ms app/actions.ts

Step 5: Refresh the Header After Signing In

The sign-in and sign-up pages from Part 3 run in the browser and sign people in through the auth client. The header is now rendered on the server, and Next.js doesn’t render a layout again when you move to another page, so the header needs a nudge to show who just signed in. In app/sign-in/page.tsx, add router.refresh() after router.push("/"):

app/sign-in/page.tsx (excerpt)TypeScript
    router.push("/");
    router.refresh();

router.refresh() asks the server to render the page’s server components again, the header included. Make the same change in app/sign-up/page.tsx. The complete files:

app/sign-in/page.tsxTypeScript
"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { type FormEvent, useState } from "react";
import { authClient } from "@/lib/auth-client";

export default function SignInPage() {
  const router = useRouter();
  const [errorMessage, setErrorMessage] = useState("");
  const [isPending, setIsPending] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setErrorMessage("");
    setIsPending(true);

    const { error } = await authClient.signIn.email({
      email: String(form.get("email")),
      password: String(form.get("password")),
    });

    setIsPending(false);
    if (error) {
      setErrorMessage(error.message ?? "Sign-in failed. Please try again.");
      return;
    }
    router.push("/");
    router.refresh();
  }

  return (
    <main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
      <h1 className="text-2xl font-semibold">Sign in</h1>
      <form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm">
          Email
          <input
            name="email"
            type="email"
            required
            autoComplete="email"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Password
          <input
            name="password"
            type="password"
            required
            autoComplete="current-password"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        {errorMessage && (
          <p role="alert" className="text-sm text-red-600">
            {errorMessage}
          </p>
        )}
        <button
          type="submit"
          disabled={isPending}
          className="rounded bg-zinc-900 px-4 py-2 text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
        >
          {isPending ? "Signing in…" : "Sign in"}
        </button>
      </form>
      <p className="mt-6 text-sm">
        New to the Bookshop?{" "}
        <Link href="/sign-up" className="underline">
          Create an account
        </Link>
      </p>
    </main>
  );
}
app/sign-up/page.tsxTypeScript
"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { type FormEvent, useState } from "react";
import { authClient } from "@/lib/auth-client";

export default function SignUpPage() {
  const router = useRouter();
  const [errorMessage, setErrorMessage] = useState("");
  const [isPending, setIsPending] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setErrorMessage("");
    setIsPending(true);

    const { error } = await authClient.signUp.email({
      name: String(form.get("name")),
      email: String(form.get("email")),
      password: String(form.get("password")),
    });

    setIsPending(false);
    if (error) {
      setErrorMessage(error.message ?? "Sign-up failed. Please try again.");
      return;
    }
    router.push("/");
    router.refresh();
  }

  return (
    <main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
      <h1 className="text-2xl font-semibold">Create your account</h1>
      <form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm">
          Name
          <input
            name="name"
            required
            autoComplete="name"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Email
          <input
            name="email"
            type="email"
            required
            autoComplete="email"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Password
          <input
            name="password"
            type="password"
            required
            minLength={8}
            autoComplete="new-password"
            className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
          />
        </label>
        {errorMessage && (
          <p role="alert" className="text-sm text-red-600">
            {errorMessage}
          </p>
        )}
        <button
          type="submit"
          disabled={isPending}
          className="rounded bg-zinc-900 px-4 py-2 text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
        >
          {isPending ? "Creating account…" : "Sign up"}
        </button>
      </form>
      <p className="mt-6 text-sm">
        Already have an account?{" "}
        <Link href="/sign-in" className="underline">
          Sign in
        </Link>
      </p>
    </main>
  );
}

Sign in as Lena again. The header shows her name, which now links to her account page:

The right end of the Bookshop header showing Signed in as Lena Park and a Sign out button.
The header, rendered on the server after signing in.

Step 6: Protect an API Route

An API route answers with data instead of a page. In Next.js it’s a route handler: a route.ts file that exports a function for each HTTP method. A program can’t use a sign-in page, so a protected API route answers with the status code 401, Unauthorized, instead of a redirect.

In the app/api folder, create a folder named account, and in it a file named route.ts:

app/api/account/route.tsTypeScript
import { auth } from "@/lib/auth";

export async function GET(request: Request) {
  const session = await auth.api.getSession({
    headers: request.headers,
  });

  if (!session) {
    return Response.json(
      { error: "Sign in to see your account data." },
      { status: 401 },
    );
  }

  return Response.json({
    name: session.user.name,
    email: session.user.email,
    createdAt: session.user.createdAt,
  });
}
  • GET answers GET requests to /api/account.
  • A route handler receives the request itself, so request.headers goes straight to auth.api.getSession.
  • Without a session, Response.json sends an error message with status: 401.
  • With one, it sends Lena’s name, her email address and the date her account was created.

On the account page, click Your account data as JSON:

A browser showing the JSON reply name Lena Park, email lena@example.com and createdAt 2026-11-19T05:22:19.700Z, under a Pretty print checkbox.
The account data, for the signed-in person only.

Sign out, then open http://localhost:3000/api/account again:

A browser showing the JSON reply error: Sign in to see your account data.
Without a session, the route refuses with status 401.

Terminal shows both answers, the second with the status 401:

Output (the lines that matter)Plain text
 GET /api/account 200 in 40ms (next.js: 23ms, application-code: 18ms)
 GET /api/account 401 in 5ms (next.js: 0.7ms, application-code: 4ms)

Your project now has these new and changed files:

Project filesPlain text
bookshop/
├── app/
│   ├── account/
│   │   └── page.tsx        (new)
│   ├── actions.ts          (new)
│   ├── api/
│   │   └── account/
│   │       └── route.ts    (new)
│   ├── layout.tsx          (changed)
│   ├── sign-in/
│   │   └── page.tsx        (changed)
│   └── sign-up/
│       └── page.tsx        (changed)
├── components/
│   └── user-menu.tsx       (changed)
├── lib/
│   └── auth.ts             (changed)
└── proxy.ts                (new)

Clean Up When You’re Done

Part 5 carries on with this project and Lena’s account, so keep both. To stop for now:

  1. In the Terminal where npm run dev runs, press Ctrl+C to stop the app.
  2. Stop the database and keep its data with docker compose stop. Next time, docker compose up -d starts it again.

Common Mistakes

MistakeWhat happensDo this instead
Checking the session only in proxy.tsAnyone who sends a made-up session cookie gets past itAlso check with auth.api.getSession in the page, server action or route
Reading the session outside <Suspense>npm run build stops with “Next.js encountered uncached or runtime data during prerendering”Read it in a component inside <Suspense>, as in Step 2
A server action with no session checkAnyone can call it, signed in or notCheck the session at the start of every server action
Leaving out nextCookies()A server action can’t change the browser’s cookies, so signing out there doesn’t clear the session cookieAdd nextCookies() as the last plugin in lib/auth.ts
Redirecting API requests to the sign-in pagePrograms that call the API get a web page instead of an errorAnswer with Response.json and status: 401

Troubleshooting

Message or problemCauseFix
Error: Route "/account": Next.js encountered uncached or runtime data during prerendering.The session is read outside <Suspense>Move the session read into a component inside <Suspense> (Step 2)
The header still shows the old state after signing inThe header is rendered on the server, and the layout wasn’t rendered againAdd router.refresh() after router.push("/") (Step 5)
{"error":"Sign in to see your account data."}Nobody is signed in in this browserSign in, then open /api/account again
/account always opens the sign-in pageThe browser has no session cookie, or the cookie has another nameSign in first. If you changed the cookie name or prefix in lib/auth.ts, pass the same settings to getSessionCookie

FAQ

Is proxy.ts enough to protect a page?

No. getSessionCookie only sees that a cookie is there, not whether it’s real. Better Auth’s docs say this check isn’t secure on its own, and recommend checking the session in every page and route, as the account page does.

Can proxy.ts check the full session?

Yes. In Next.js 16, proxy.ts runs on Node.js, so it can call auth.api.getSession. That adds a database query to every request it matches, so Better Auth’s docs recommend the cookie check there and the full check in the page.

Why do I see “Loading your account…”?

That’s the <Suspense> fallback. Next.js sends the page’s heading at once, then streams in the part that reads the session. On your own computer it’s usually too quick to notice.

Do I still need useSession?

In client components, yes: authClient.useSession() reads the session in the browser. Server components, server actions and route handlers read it with auth.api.getSession.

Conclusion

The Bookshop now checks the session on the server. The account page and the header read it with auth.api.getSession, proxy.ts turns away visitors without a session cookie, signing out is a server action that checks the session first, and the account data route answers 401 to anyone who isn’t signed in. Next, you decide how long those sessions last.

← Previous: Part 3: Sign Up and Sign In with Email and Password

Coming next: Part 5: Sessions: Expiry, Cookie Cache and Signing Out Everywhere.

Additional Resources

Better Auth, Next.js and other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by Better Auth, Inc. or Vercel.

0 comments