Web frameworks · Intermediate · 28 min
Sign in librarians with Better Auth and protect actions
By Padding · Updated 18 Nov 2026
Next.js 16.4 · Better Auth 1.7 · Node.js 26 · node:26 image
You will add email and password sign-in for librarians to the community library app with Better Auth 1.7, store sessions in its SQLite database, and end with an app where only a signed-in librarian can add or edit books, even when someone calls a server action directly.
On this page
In part 4 you gave librarians forms to add and edit books. Anyone who can reach the app can use those forms too, because nothing yet asks who is calling. This part fixes that. Librarians get accounts and sign in with an email address and password; members keep browsing without an account and see a read-only catalogue.
You use Better Auth, an open-source authentication library for TypeScript. It hashes passwords, creates sessions and sets the session cookie, and with its Drizzle adapter it keeps users and sessions in the same SQLite file as your books. There is no separate service to pay for or call over the network.
The important lesson is where the check goes. Hiding the "Add a book" link is not protection: every server action is a public endpoint that anyone can call with a crafted request. So the session is checked inside each action and data function that changes data, and the pages and header only use it to decide what to show.
This tutorial continues in ~/community-library-demo from part 4. It expects these files from earlier parts: src/db/schema.ts and src/db/index.ts (which exports db) from part 2; the data module src/lib/books.ts with getBooks and getBook; and from part 4, src/lib/book-form.ts (the Zod schema and BookFormState), src/app/books/actions.ts with the createBook and updateBook server actions, which write to db directly, and the pages at /books/new, /books/[id] and /books/[id]/edit. This part moves those two writes into data functions in src/lib/books.ts, so the session is checked in both places. If your names differ, the changes are the same; only the names change.
Step 1 · Install Better Auth and create the secret
Install Better Auth at an exact version, and tsx, which runs the small TypeScript admin scripts you write later. If part 2 already installed tsx, the second command only pins it:
cd ~/community-library-demo
npm install better-auth@1.7.26
npm install --save-dev tsx@4.23.15
npm ls better-auth tsxBetter Auth signs its cookies and tokens with a secret. Anyone who has the secret can forge them, so it must be long, random and kept out of Git. Next.js reads .env.local for the dev server, the build and the production server, and the .gitignore that create-next-app wrote already ignores .env* files.
The commands below create .env.local readable only by you before anything goes into it, then add a 32-byte random secret and the address the app runs on. The if stops a second run from adding a second secret:
(
umask 077
touch .env.local
chmod 600 .env.local
if ! grep -q '^BETTER_AUTH_SECRET=' .env.local; then
node -e 'console.log("BETTER_AUTH_SECRET=" + require("node:crypto").randomBytes(32).toString("base64"))' >> .env.local
echo "BETTER_AUTH_URL=http://localhost:3000" >> .env.local
fi
)The parentheses run the commands in a subshell, so the strict umask does not stay set in your terminal. BETTER_AUTH_URL tells Better Auth its own public address; part 9 changes it to your real domain.
Check it worked
ls -l .env.local
grep -c '^BETTER_AUTH_SECRET=' .env.local
grep '^\.env' .gitignoreThe file mode starts -rw-------, so only your user can read it. The count is 1, and the last command prints .env*, the ignore rule that keeps the file out of commits. Do not print the secret itself into a shared terminal or paste it into chat; if it leaks, replace the line with a new value and every librarian signs in again.
Step 2 · Add the auth tables to the database
Better Auth stores four kinds of record: user (one per librarian), account (how a user signs in, holding the password hash for email sign-in), session (one row per signed-in browser) and verification (one-time tokens, unused until you add password resets). With the Drizzle adapter you own these tables in your schema, so Drizzle migrations create them like any other table.
Write them in their own file. This is what Better Auth's schema generator (npx auth@1.7.26 generate) writes for SQLite with this configuration, without the optional relations block:
cat > src/db/auth-schema.ts <<'TS'
// Tables Better Auth needs, in the shape `npx auth@1.7.26 generate`
// writes for SQLite with the Drizzle adapter.
import { sql } from "drizzle-orm";
import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core";
const now = sql`(cast(unixepoch('subsecond') * 1000 as integer))`;
export const user = sqliteTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: integer("email_verified", { mode: "boolean" }).default(false).notNull(),
image: text("image"),
createdAt: integer("created_at", { mode: "timestamp_ms" }).default(now).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" })
.default(now)
.$onUpdate(() => new Date())
.notNull(),
});
export const session = sqliteTable(
"session",
{
id: text("id").primaryKey(),
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
token: text("token").notNull().unique(),
createdAt: integer("created_at", { mode: "timestamp_ms" }).default(now).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" })
.$onUpdate(() => new Date())
.notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
},
(table) => [index("session_userId_idx").on(table.userId)],
);
export const account = sqliteTable(
"account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: integer("access_token_expires_at", { mode: "timestamp_ms" }),
refreshTokenExpiresAt: integer("refresh_token_expires_at", { mode: "timestamp_ms" }),
scope: text("scope"),
password: text("password"),
createdAt: integer("created_at", { mode: "timestamp_ms" }).default(now).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" })
.$onUpdate(() => new Date())
.notNull(),
},
(table) => [index("account_userId_idx").on(table.userId)],
);
export const verification = sqliteTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
createdAt: integer("created_at", { mode: "timestamp_ms" }).default(now).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" })
.default(now)
.$onUpdate(() => new Date())
.notNull(),
},
(table) => [index("verification_identifier_idx").on(table.identifier)],
);
TSThe user table is named for Better Auth, but in this app every row in it is a librarian: members never get accounts. The password column on account holds a scrypt hash, never the password itself.
drizzle-kit reads the schema from src/db/schema.ts, so re-export the new tables from there. Appending one line leaves the books, members and loans tables from part 2 untouched:
echo 'export * from "./auth-schema";' >> src/db/schema.tsNow generate a migration for the new tables, the same way you created the first tables in part 2. This only writes a SQL file; nothing changes in the database yet:
npx drizzle-kit generate --name authdrizzle-kit generate reports seven tables and names a new migration file ending in _auth.sql. List the tables that file creates:
cat drizzle/*_auth.sql | grep -o 'CREATE TABLE `[a-z]*`'The output should be four lines: account, session, user and verification, and nothing else. Check this before you go on: if the file also creates, alters or drops your books, members or loans tables, your schema had edits that were never migrated. Read the SQL and make sure you want those changes, because the next command applies everything in the file to data/library.db. Then apply it:
npx drizzle-kit migrateCheck it worked
migrate ends with a message such as migrations applied successfully. Confirm the new tables are in the database file:
node -e 'const db = require("better-sqlite3")("data/library.db"); console.log(db.prepare("SELECT name FROM sqlite_master WHERE type = ? AND name IN (?, ?, ?, ?) ORDER BY name").all("table", "account", "session", "user", "verification").map((t) => t.name).join(" "))'It prints account session user verification.
Step 3 · Configure Better Auth and mount its routes
Create the server-side configuration. It connects Better Auth to your Drizzle database, turns on email and password sign-in, and turns off sign-up, so nobody can create an account from the browser:
cat > src/lib/auth.ts <<'TS'
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { db } from "@/db";
import * as authSchema from "@/db/auth-schema";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "sqlite", schema: authSchema }),
emailAndPassword: {
enabled: true,
disableSignUp: true,
minPasswordLength: 12,
},
session: {
expiresIn: 60 * 60 * 24 * 7,
},
plugins: [nextCookies()],
});
TSWhat each setting does:
disableSignUp: truecloses the public sign-up endpoint. Librarian accounts are created by a script in the next step, by someone who already has access to the server.minPasswordLength: 12raises the default of 8. A long passphrase is easier to type on a phone keyboard than a short string of symbols, and harder to guess.expiresInkeeps a session for 7 days (Better Auth's default, written out so you can see it). Better Auth extends a session while it is in use.nextCookies()lets Better Auth set cookies when it runs inside a server action. Its documentation asks for it to be the last plugin in the list.
The secret and the URL come from .env.local through BETTER_AUTH_SECRET and BETTER_AUTH_URL, so they are not in the code. In production Better Auth refuses to start without the secret.
The browser talks to Better Auth through one catch-all route handler. Every auth endpoint, such as /api/auth/sign-in/email and /api/auth/get-session, goes through it:
mkdir -p "src/app/api/auth/[...all]"
cat > "src/app/api/auth/[...all]/route.ts" <<'TS'
import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/lib/auth";
export const { GET, POST } = toNextJsHandler(auth);
TSIn your second terminal, start the dev server:
npm run devCheck it worked
Ask Better Auth for the current session. Without a cookie there is none:
curl -s http://localhost:3000/api/auth/get-session; echoThe output is null. Now try to create an account from outside, the way an attacker would:
curl -s -X POST http://localhost:3000/api/auth/sign-up/email \
-H 'Content-Type: application/json' \
-H 'Origin: http://localhost:3000' \
-d '{"name":"Mallory","email":"mallory@example.org","password":"a-long-enough-password"}'; echoBetter Auth refuses with {"message":"Email and password sign up is not enabled","code":"EMAIL_PASSWORD_SIGN_UP_DISABLED"}.
Step 4 · Create the first librarian from the command line
With sign-up closed, accounts are made on the server. This script creates one librarian. It reads the password from standard input, so the password never appears in your shell history or in the list of running processes, and it hashes it the same way Better Auth does at sign-in.
The script cannot import src/lib/auth.ts, because that file gets db from src/db/index.ts, which starts with import "server-only" and refuses to load outside Next.js (part 2 showed this). So it opens the database with connect() from part 2, as the seed script does, and builds its own Better Auth instance with the same email and password settings:
mkdir -p scripts
cat > scripts/create-librarian.ts <<'TS'
// Creates one librarian account. The password is read from standard input,
// so it never appears in your shell history or the process list.
import { text } from "node:stream/consumers";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { connect } from "../src/db/connect";
import * as authSchema from "../src/db/auth-schema";
// The same database and email settings as src/lib/auth.ts.
const auth = betterAuth({
database: drizzleAdapter(connect(), { provider: "sqlite", schema: authSchema }),
emailAndPassword: { enabled: true, disableSignUp: true, minPasswordLength: 12 },
});
async function main() {
const [email, name] = process.argv.slice(2);
if (!email || !name) {
throw new Error('Usage: create-librarian.ts <email> "<name>", with the password on standard input');
}
const password = (await text(process.stdin)).trim();
if (password.length < 12) {
throw new Error("The password must be at least 12 characters.");
}
const ctx = await auth.$context;
const address = email.toLowerCase();
if (await ctx.internalAdapter.findUserByEmail(address)) {
throw new Error(`A librarian with the email ${address} already exists.`);
}
const user = await ctx.internalAdapter.createUser(
{ email: address, name, emailVerified: true },
{ method: "email-password" },
);
await ctx.internalAdapter.linkAccount({
userId: user.id,
providerId: "credential",
accountId: user.id,
password: await ctx.password.hash(password),
});
console.log(`Created librarian ${user.name} <${user.email}>`);
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
TSauth.$context is Better Auth's own internals: the database adapter and the password hasher. The script makes the same two calls Better Auth's admin plugin makes when an administrator creates a user: one user row, and one account row with the provider credential and the scrypt hash. Names are stored as UTF-8 text, so "Adébáyọ̀ Ọlọ́rùn" or "ተስፋዬ ገብሬ" work as well as any Latin name.
Run it. Replace the email address and name with your own; the first command prompts for the password without showing it:
printf 'New librarian password: '; read -rs LIBRARIAN_PASSWORD; echo
printf '%s\n' "$LIBRARIAN_PASSWORD" | npx tsx --env-file=.env.local scripts/create-librarian.ts amina@example.org "Amina Bello"
unset LIBRARIAN_PASSWORDprintf is built into the shell, so the password goes down the pipe without becoming a command-line argument. --env-file=.env.local gives the script the same secret the app uses.
Add a second script that lists the librarians and how many live sessions each has. You will use it to watch sessions appear and disappear:
cat > scripts/list-librarians.ts <<'TS'
// Lists librarian accounts and how many unexpired sessions each one has.
import { and, count, eq, gt } from "drizzle-orm";
import { connect } from "../src/db/connect";
import { session, user } from "../src/db/auth-schema";
const db = connect();
const rows = db
.select({ email: user.email, name: user.name, activeSessions: count(session.id) })
.from(user)
.leftJoin(session, and(eq(session.userId, user.id), gt(session.expiresAt, new Date())))
.groupBy(user.id)
.all();
console.table(rows);
TSCheck it worked
The create script prints Created librarian Amina Bello <amina@example.org>. Running it again with the same email prints A librarian with the email amina@example.org already exists. and changes nothing. Now list the accounts:
npx tsx scripts/list-librarians.tsA table shows one row with your email, your name and activeSessions at 0: the account exists, and nobody has signed in yet.
Step 5 · Add the sign-in page, the sign-out button and a session helper
Start with one server-only helper that every page and action uses to ask "who is calling?":
cat > src/lib/session.ts <<'TS'
import "server-only";
import { cache } from "react";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
// The signed-in librarian, or null for everyone else.
// cache() shares one lookup between the header and the page in a single render.
export const getLibrarian = cache(async () => {
const session = await auth.api.getSession({ headers: await headers() });
return session?.user ?? null;
});
// Call first in anything that changes data. Sends visitors to sign in.
export async function requireLibrarian() {
const librarian = await getLibrarian();
if (!librarian) redirect("/sign-in");
return librarian;
}
TSauth.api.getSession reads the session cookie from the request headers and looks the session up in the session table, so a cookie for a signed-out or expired session is rejected. import "server-only" makes the build fail if a client component ever imports this file.
The sign-in form runs in the browser and posts to Better Auth's own endpoint through its client library. Going through that endpoint matters: Better Auth's rate limiting, 3 sign-in attempts per 10 seconds from one address in production, applies to requests to its endpoints, not to calls made with auth.api on the server. Create the client and the form:
cat > src/lib/auth-client.ts <<'TS'
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();
TS
mkdir -p src/app/sign-in
cat > src/app/sign-in/sign-in-form.tsx <<'TSX'
"use client";
import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
export default function SignInForm() {
const router = useRouter();
const [error, formAction, pending] = useActionState(
async (_previous: string, formData: FormData) => {
const { error } = await authClient.signIn.email({
email: String(formData.get("email")),
password: String(formData.get("password")),
});
if (error) {
return error.status === 429
? "Too many attempts. Wait a few seconds and try again."
: "That email and password do not match a librarian account.";
}
router.replace("/books");
router.refresh();
return "";
},
"",
);
return (
<form action={formAction}>
<p>
<label htmlFor="email">Email</label>
<br />
<input id="email" name="email" type="email" autoComplete="username" required />
</p>
<p>
<label htmlFor="password">Password</label>
<br />
<input id="password" name="password" type="password" autoComplete="current-password" required />
</p>
{error && <p role="alert">{error}</p>}
<button type="submit" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</button>
</form>
);
}
TSX
cat > src/app/sign-in/page.tsx <<'TSX'
import type { Metadata } from "next";
import SignInForm from "./sign-in-form";
export const metadata: Metadata = { title: "Librarian sign in" };
export default function SignInPage() {
return (
<main>
<h1>Librarian sign in</h1>
<p>Members do not need an account to browse the catalogue.</p>
<SignInForm />
</main>
);
}
TSXThe error message is the same for an unknown email and a wrong password, so the form does not tell a stranger which librarian addresses exist. The autoComplete values let password managers fill the form. createAuthClient() with no options talks to the same site it is served from.
After a successful sign-in, router.refresh() asks the server to render the page again, so the header picks up the new session. Layouts do not re-render on their own when you move between pages.
Now the header. The account links read the session, which depends on each request's cookies, so they go in their own component inside <Suspense>. The rest of the header, and every page, can still be prepared ahead of time, with only this small part filled in per request. This is how Next.js 16 with Cache Components (on in this project since part 1) expects per-user parts to be written:
cat > src/components/sign-out-button.tsx <<'TSX'
"use client";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
export default function SignOutButton() {
const router = useRouter();
async function signOut() {
await authClient.signOut();
router.replace("/");
router.refresh();
}
return (
<button type="button" onClick={signOut}>
Sign out
</button>
);
}
TSX
cat > src/components/account-links.tsx <<'TSX'
import Link from "next/link";
import { getLibrarian } from "@/lib/session";
import SignOutButton from "./sign-out-button";
export default async function AccountLinks() {
const librarian = await getLibrarian();
if (!librarian) {
return <Link href="/sign-in">Librarian sign in</Link>;
}
return (
<>
<Link href="/books/new">Add a book</Link>
<span>Signed in as {librarian.name}</span>
<SignOutButton />
</>
);
}
TSX
cat > src/components/site-header.tsx <<'TSX'
import { Suspense } from "react";
import Link from "next/link";
import AccountLinks from "./account-links";
import styles from "./site-header.module.css";
export default function SiteHeader() {
return (
<header className={styles.header}>
<div className={styles.inner}>
<Link href="/" className={styles.name}>
Community Library
</Link>
<nav aria-label="Main" className={styles.nav}>
<Link href="/">Home</Link>
<Link href="/books">Books</Link>
<Suspense fallback={null}>
<AccountLinks />
</Suspense>
</nav>
</div>
</header>
);
}
TSX
cat >> src/components/site-header.module.css <<'CSS'
.nav {
flex-wrap: wrap;
align-items: center;
}
CSSThe new site-header.tsx replaces part 4's whole file: part 4's "Add a book" link, which everyone saw, now lives in AccountLinks and appears only for a signed-in librarian. The CSS rule added at the end lets the longer navigation wrap onto a second line on a narrow phone screen instead of pushing the page sideways. Signing out calls Better Auth's sign-out endpoint, which deletes the session row and clears the cookie.
Check it worked
curl -s http://localhost:3000/sign-in | grep -o '<h1>[^<]*</h1>'
curl -s http://localhost:3000/ | grep -o 'href="/sign-in"' | sort -uThe first command prints <h1>Librarian sign in</h1>; the second prints href="/sign-in", the header link a signed-out visitor sees. In the browser, click "Librarian sign in", enter a wrong password and see "That email and password do not match a librarian account." Then sign in with the real one. You land on the book list, and the header shows "Add a book", "Signed in as Amina Bello" and "Sign out". Run npx tsx scripts/list-librarians.ts again: activeSessions is now 1. In the browser's developer tools, under the stored cookies for localhost, the session cookie's name ends in session_token and it is marked HttpOnly, so scripts on the page cannot read it.
Step 6 · Move the writes into data functions that check the session
Everything so far changes what people see. The next two steps change what people can do.
In part 4 the two server actions write to db themselves. Move those writes into src/lib/books.ts, next to getBooks and getBook, and make each one start with await requireLibrarian();. The data module is the last code to run before SQLite, so the check there holds even if a future server action, route handler or script forgets its own. Part 6's lending actions start with the same line.
Open src/lib/books.ts. Add this import at the top, next to the ones already there:
import { requireLibrarian } from "@/lib/session";and add eq to the drizzle-orm import if it is not there yet (part 3's version already imports it for getBook). Then add this to the end of the file:
// What a valid book looks like after the Zod schema in book-form.ts has cleaned it up.
export type BookInput = { title: string; author: string; year: number; isbn: string | null };
export type SaveResult =
| { ok: true; id: number }
| { ok: false; problem: "duplicate-isbn" | "not-found" };
// SQLite refuses a second book with the same ISBN because the column is UNIQUE.
function isDuplicateIsbn(error: unknown): boolean {
return error instanceof Error && "code" in error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
}
export async function insertBook(input: BookInput): Promise<SaveResult> {
await requireLibrarian();
try {
const [row] = await db.insert(books).values(input).returning({ id: books.id });
return { ok: true, id: row.id };
} catch (error) {
if (isDuplicateIsbn(error)) return { ok: false, problem: "duplicate-isbn" };
throw error;
}
}
export async function saveBookChanges(id: number, input: BookInput): Promise<SaveResult> {
await requireLibrarian();
let changed: { id: number }[];
try {
changed = await db.update(books).set(input).where(eq(books.id, id)).returning({ id: books.id });
} catch (error) {
if (isDuplicateIsbn(error)) return { ok: false, problem: "duplicate-isbn" };
throw error;
}
return changed.length === 0 ? { ok: false, problem: "not-found" } : { ok: true, id };
}The insert, the update and the duplicate-ISBN handling are the ones from part 4's actions, moved here. Part 4 already uses the names createBook and updateBook for the server actions, so the data functions get their own names, insertBook and saveBookChanges, and the actions keep theirs, which the forms import. The data functions report a duplicate ISBN or a missing book as a result instead of a message, because wording for a form belongs to the action. requireLibrarian() sits before the try, so its redirect is never caught there.
The read functions, getBooks and getBook, stay open: the catalogue is public.
Check it worked
grep -c 'await requireLibrarian();' src/lib/books.tsIt prints 2: one check at the top of each write. The actions still do their own inserts, so nothing calls the new functions yet; the next step switches them over.
Step 7 · Check the session in both server actions
A server action is compiled into an endpoint with an ID that is sent to the browser in the page. Anyone who has once loaded a form page has that ID and can post to it with any tool they like, with or without your form. So the action checks the session too, before it reads a single field.
Part 4 left the comment // Part 5 adds the first check here at the top of both actions in src/app/books/actions.ts. Replace each comment with await requireLibrarian();, and replace the database code in both actions with calls to the new data functions. This is the whole file afterwards; the Zod checks, the messages and the revalidatePath and redirect calls are part 4's:
cat > src/app/books/actions.ts <<'TS'
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { bookInput, readBookFields, type BookFormState } from "@/lib/book-form";
import { insertBook, saveBookChanges } from "@/lib/books";
import { requireLibrarian } from "@/lib/session";
const duplicateIsbn = ["Another book in the catalogue already has this ISBN."];
export async function createBook(
_previous: BookFormState,
formData: FormData,
): Promise<BookFormState> {
await requireLibrarian();
const values = readBookFields(formData);
const parsed = bookInput.safeParse(values);
if (!parsed.success) {
return { errors: z.flattenError(parsed.error).fieldErrors, values };
}
const saved = await insertBook(parsed.data);
if (!saved.ok) return { errors: { isbn: duplicateIsbn }, values };
revalidatePath("/books");
redirect(`/books/${saved.id}`);
}
export async function updateBook(
bookId: number,
_previous: BookFormState,
formData: FormData,
): Promise<BookFormState> {
await requireLibrarian();
const values = readBookFields(formData);
const id = z.number().int().positive().safeParse(bookId);
if (!id.success) return { message: "That book does not exist.", values };
const parsed = bookInput.safeParse(values);
if (!parsed.success) {
return { errors: z.flattenError(parsed.error).fieldErrors, values };
}
const saved = await saveBookChanges(id.data, parsed.data);
if (!saved.ok) {
return saved.problem === "duplicate-isbn"
? { errors: { isbn: duplicateIsbn }, values }
: { message: "That book is no longer in the catalogue.", values };
}
revalidatePath("/books");
revalidatePath(`/books/${id.data}`);
redirect(`/books/${id.data}`);
}
TSChecking first means a signed-out caller learns nothing, not even which fields fail validation. For a caller with no valid session, requireLibrarian() redirects to /sign-in and the action stops there; nothing reaches the database. The data function then checks again, which costs one more session lookup per save and guards against the day someone adds an action without the first line.
A note on proxy.ts, the Next.js 16 file that runs before every request. Better Auth offers getSessionCookie() for it, and a proxy can send signed-out visitors to /sign-in early. But that function only checks that a cookie with the right name exists; it does not check it against the database, and an expired or made-up cookie passes. Use a proxy for convenience redirects if you like (see Redirect and rewrite requests with proxy in Next.js 16), never as the lock.
Check it worked
npx tsc --noEmit
grep -c 'await requireLibrarian();' src/app/books/actions.ts
grep -c 'db\.' src/app/books/actions.ts || truetsc prints nothing, the second command prints 2 and the third prints 0: the actions no longer touch the database themselves.
Then try the attack yourself in two browser tabs. In the first, signed in, open "Add a book" and type a title, author and year, but do not save. In the second tab, click "Sign out". Back in the first tab, click "Add book". The form you loaded while signed in still has the action's ID, but the request now carries no session: you land on the sign-in page, and the book is not in the list. Sign in again and add a book normally: it is saved and you are taken to its page.
Step 8 · Give members a read-only view
The pages should match the rules, so members are never shown a form they cannot use. Three files from part 4 change.
Under Cache Components, anything that reads the request's cookies has to sit inside <Suspense>, so the rest of the page can still be prepared ahead of time. Part 4's edit page already reads the database inside a component wrapped in <Suspense>, and the book page has part 3's loading.tsx next to it, which wraps the whole page in one, so the session check goes in those components. The add page has neither yet, so it gets a component of its own.
src/app/books/new/page.tsx. Replace the file. The back link, heading and form from part 4 move into NewBook, which checks the session first, so a signed-out visitor is sent to the sign-in page without seeing the form:
import type { Metadata } from "next";
import Link from "next/link";
import { Suspense } from "react";
import BookForm from "@/components/book-form";
import { requireLibrarian } from "@/lib/session";
import { createBook } from "../actions";
export const metadata: Metadata = { title: "Add a book" };
async function NewBook() {
await requireLibrarian();
return (
<>
<p>
<Link href="/books">Back to all books</Link>
</p>
<h1>Add a book</h1>
<BookForm action={createBook} submitLabel="Add book" />
</>
);
}
export default function NewBookPage() {
return (
<main>
<Suspense fallback={<p>Loading…</p>}>
<NewBook />
</Suspense>
</main>
);
}src/app/books/[id]/edit/page.tsx. Add the import, and make await requireLibrarian(); the first line of the EditBook component, before connection() and the query. EditBookPage itself stays as it is, a plain function that wraps EditBook in <Suspense>:
import { requireLibrarian } from "@/lib/session";
async function EditBook({ params }: { params: Promise<{ id: string }> }) {
await requireLibrarian();
// Read the row when the request arrives, never at build time:
// the form must start from what is in the database now.
await connection();
const { id } = await params;
// ...the rest of EditBook is unchanged from part 4
}Checking before the query means a signed-out visitor never causes a database read.
src/app/books/[id]/page.tsx. Part 4 put an "Edit this book" link straight after the <h1> in BookPage, and everyone sees it. Replace that link with one only librarians see. Use getLibrarian(), which returns null instead of redirecting, because everyone may read this page. Add the import at the top:
import { getLibrarian } from "@/lib/session";In BookPage, after the if (!book) notFound(); line, add:
const librarian = await getLibrarian();Then replace part 4's <p> with the edit link, the one straight after <h1>{book.title}</h1>, with:
{librarian && (
<p>
<Link href={`/books/${book.id}/edit`}>Edit this book</Link>
</p>
)}BookPage is already inside <Suspense>, the one part 3's loading.tsx puts around it, so the session read is in the right place. The header's AccountLinks and this component both call getLibrarian(), and cache() makes that one lookup per request.
Check it worked
Fetch a book page without a session, as a member would see it:
curl -s http://localhost:3000/books/1 | grep -o 'Librarian sign in\|Edit this book' | sort -uThe output is only Librarian sign in: no edit link. If Edit this book is also listed, part 4's link is still in BookPage; remove it so only the {librarian && ...} version is left. In a private browser window, open http://localhost:3000/books/new and you are sent to the sign-in page. In your signed-in window, the same book page shows "Edit this book". On a shared library desk computer, remind librarians to sign out at the end of a shift; a private window also drops the session cookie when it closes. Stop the dev server with Ctrl+C.
Step 9 · Build and run the production version
Lint and build. The build checks the types across the new files and decides which parts of each page can be prepared ahead of time:
npm run lint
npm run buildnpm run lint prints no errors. The build's route table now includes /api/auth/[...all] marked ƒ (rendered on demand) and /sign-in. Pages with the account links in the header are marked ◐, partial prerender: a shell prepared at build time, with the session-dependent parts filled in per request.
Start the production server:
npm run startIn production, Better Auth's rate limit is on: after three sign-in attempts within 10 seconds from one address, the form shows "Too many attempts". The counts are kept in the server's memory, which suits one server like this app's; part 9 runs it as a single process. Better Auth can keep the counts in the database instead if you ever run several copies.
Check it worked
Open http://localhost:3000 and go through the journey once more on the production build: sign in, add a book, open its page and see "Edit this book", then sign out and see "Librarian sign in" again. From the terminal, the session endpoint still answers null for a request with no cookie:
curl -s http://localhost:3000/api/auth/get-session; echoThe output is null. Stop the server with Ctrl+C. Keep ~/community-library-demo, .env.local and the librarian account: part 6 uses them for lending.
Next steps
- Continue the series: Lend and return books safely with database transactions adds lending, with
requireLibrarian()guarding every new action from the start. - Look back at Add and edit books with server actions and Zod validation to see the actions you protected here, and why every one of them validates its own input.
- For convenience redirects before a page renders, see Redirect and rewrite requests with proxy in Next.js 16, keeping the session check in your actions as the real lock.
- Compare another framework's built-in approach in Add sign-in to Rails with the authentication generator.
Part of these paths
Related tutorials
- Add and edit books with server actions and Zod validationYou will give the library app an add-a-book page and an edit page whose forms post to Next.js 16 server actions, are checked by a Zod 4 schema on the server, show each mistake next to its field and redirect to the saved book.
- Redirect and rewrite requests with proxy.ts in Next.js 16You will write a Next.js 16 proxy.ts that redirects old URLs from a map, rewrites one path to another route, adds a request header, picks a language from Accept-Language and sends signed-out visitors to a login page, then prove the redirect map with a curl script against a production build.
- Lend and return books safely with database transactionsYou will let librarians lend and take back books from each book's page, with the loan rules enforced inside one SQLite transaction so two clicks at once can never lend the same book twice or push a member past three books, plus an overdue list.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials