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
/accountthat 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/accountthat 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
- Part 1: What Is Better Auth?
- Part 2: Set Up Better Auth in Next.js with PostgreSQL
- Part 3: Sign Up and Sign In with Email and Password
Module B: Sessions and Users
- Part 4: Protect Pages, Server Actions and API Routes
- Part 5: Sessions: Expiry, Cookie Cache and Signing Out Everywhere
- Part 6: Users and Accounts: Custom Fields, Change Email and Delete Account
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:
docker compose up -d
Then start the app, and leave it running while you work:
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:
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session) {
redirect("/sign-in");
}
auth.api.getSessionis 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, ornull.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.useris the signed-in person, withsession.user.nameandsession.user.email.
In the app folder, create a folder named account, and in it a file named page.tsx:
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:

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:
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, ornullwhen there isn’t one. It doesn’t check that the session is real.NextResponse.redirectanswers 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.matcherlists the paths the proxy runs on: here only/account.
In the bookshop folder, next to package.json, create a file named proxy.ts:
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:
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:
plugins: [nextCookies()],
- Signing out clears the session cookie. A server action can only change cookies through Next.js’s own
cookieshelper, andnextCookies()passes Better Auth’s cookies to it. - Keep it last in the
pluginslist, as the Better Auth docs ask.
The complete file:
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:
"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.signOutActionchecks the session first, and sends anyone without one to the sign-in page.auth.api.signOutends the session in the database, andnextCookiesclears 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:
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 withauth.api.getSession. - Lena’s name links to her account page.
- Sign out is a form whose
actionissignOutAction, 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:
<Suspense>
<UserMenu />
</Suspense>
Suspense is imported from react. The complete file:
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:

In Terminal, Next.js shows the server action it ran:
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("/"):
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:
"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>
);
}
"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:

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:
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,
});
}
GETanswersGETrequests to/api/account.- A route handler receives the request itself, so
request.headersgoes straight toauth.api.getSession. - Without a session,
Response.jsonsends an error message withstatus: 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:

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

Terminal shows both answers, the second with the status 401:
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:
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:
- In the Terminal where
npm run devruns, press Ctrl+C to stop the app. - Stop the database and keep its data with
docker compose stop. Next time,docker compose up -dstarts it again.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Checking the session only in proxy.ts | Anyone who sends a made-up session cookie gets past it | Also 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 check | Anyone can call it, signed in or not | Check 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 cookie | Add nextCookies() as the last plugin in lib/auth.ts |
| Redirecting API requests to the sign-in page | Programs that call the API get a web page instead of an error | Answer with Response.json and status: 401 |
Troubleshooting
| Message or problem | Cause | Fix |
|---|---|---|
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 in | The header is rendered on the server, and the layout wasn’t rendered again | Add router.refresh() after router.push("/") (Step 5) |
{"error":"Sign in to see your account data."} | Nobody is signed in in this browser | Sign in, then open /api/account again |
/account always opens the sign-in page | The browser has no session cookie, or the cookie has another name | Sign 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
- Next.js integration (opens in a new tab) in the Better Auth documentation: server components, server actions,
nextCookiesandproxy.ts - Session management (opens in a new tab) and Client (opens in a new tab) in the Better Auth documentation
- proxy.js (opens in a new tab) in the Next.js documentation
- Authentication (opens in a new tab) and Authentication with Cache Components (opens in a new tab) in the Next.js documentation
- headers (opens in a new tab), redirect (opens in a new tab) and useRouter (opens in a new tab) in Next.js
- Route Handlers (opens in a new tab) in the Next.js documentation
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