Web frameworks · Intermediate · 30 min
Lend and return books safely with database transactions
By Padding · Updated 18 Nov 2026
Next.js 16.4 · Drizzle ORM 0.45 · better-sqlite3 13.2 · Node.js 26 · node:26 image
You 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.
On this page
Lending is the part of the library app where getting it wrong costs something real. If the app lets two librarians lend the last copy of a book to two members, one of them walks to the shelf and finds nothing. If it lets a member take a fourth book, the library's own rule from docs/data-model.md is gone.
The obvious code checks first and writes second: "is the book on the shelf? does the member hold fewer than three? then insert a loan". That code passes every test you write by clicking around on your own, and fails the first time two requests arrive together. In this part you watch it fail on purpose, with a script that lends twice at the same moment, then fix it the way databases are meant to be used: every check and the write inside one transaction that holds the write lock until it commits. You keep the partial unique index from part 2 as a second line of defence, add Lend and Return buttons to each book's page, build a loans page with an overdue list, and check it all with two browser tabs.
The code in this part uses the names from earlier parts. connect() in src/db/connect.ts returns a Drizzle database for data/library.db, and src/db/index.ts calls it once and exports the result as db: the app's only connection, marked server-only. src/db/schema.ts defines books, members and loans. getBook(id) in src/lib/books.ts loads one book (part 3). In src/lib/session.ts, getLibrarian() returns the signed-in librarian or null, and requireLibrarian() returns the librarian or sends the visitor to the sign-in page (part 5). If you named any of them differently, change the imports to match.
Step 1 · Watch two lends collide
Start with the version most people write first, and prove it is wrong. The script below makes a copy of your database in a temporary folder, so nothing it does touches the real catalogue, then runs two races on the copy:
- Race 1: two lending desks lend the same book on the shelf to two different members at the same moment.
- Race 2: a member holds two books, and two desks each lend them one more at the same moment.
Each desk calls lendNaive, which reads, checks and then inserts, with an await between each query. That is the shape of most server code: every await is a point where Node.js can run another request's code. The --drop-index flag removes part 2's partial unique index from the copy, so you see what the code alone does.
The safe mode loads a module you write in the next step. Leave it for now.
cd ~/community-library-demo
cat > scripts/race-lend.ts <<'TS'
// Lend books "at the same moment" on a copy of the library database.
// npx tsx scripts/race-lend.ts naive [--drop-index]
// npx tsx scripts/race-lend.ts safe [--drop-index]
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import Database from "better-sqlite3";
import { and, asc, count, eq, isNull, notExists, sql } from "drizzle-orm";
import { connect } from "../src/db/connect";
import { books, loans, members } from "../src/db/schema";
const DAY_MS = 24 * 60 * 60 * 1000;
const mode = process.argv[2] === "safe" ? "safe" : "naive";
const dropIndex = process.argv.includes("--drop-index");
async function main() {
// Work on a copy so the race never touches the real catalogue.
const copyPath = join(mkdtempSync(join(tmpdir(), "library-race-")), "library.db");
const source = new Database(process.env.DATABASE_FILE ?? "data/library.db");
await source.backup(copyPath);
source.close();
const db = connect(copyPath);
if (dropIndex) db.run(sql`DROP INDEX IF EXISTS loans_one_open_per_book`);
// The obvious version: check, then write, with awaits in between.
async function lendNaive(bookId: number, memberId: number) {
const out = await db
.select({ id: loans.id })
.from(loans)
.where(and(eq(loans.bookId, bookId), isNull(loans.returnedAt)));
if (out.length > 0) throw new Error("on-loan");
const [{ held }] = await db
.select({ held: count() })
.from(loans)
.where(and(eq(loans.memberId, memberId), isNull(loans.returnedAt)));
if (held >= 3) throw new Error("member-at-limit");
const now = new Date();
await db.insert(loans).values({ bookId, memberId, lentAt: now, dueAt: new Date(now.getTime() + 14 * DAY_MS) });
}
let lend = lendNaive;
if (mode === "safe") {
const rules = await import("../src/lib/loan-rules");
lend = async (bookId, memberId) => {
const result = rules.lendBook(db, { bookId, memberId });
if (!result.ok) throw new Error(result.reason);
};
}
const onShelf = db
.select({ id: books.id, title: books.title })
.from(books)
.where(notExists(db.select().from(loans).where(and(eq(loans.bookId, books.id), isNull(loans.returnedAt)))))
.orderBy(asc(books.id))
.all();
const people = db.select({ id: members.id, name: members.name }).from(members).orderBy(asc(members.id)).all();
const openFor = (column: typeof loans.bookId | typeof loans.memberId, id: number) =>
db.select({ n: count() }).from(loans).where(and(eq(column, id), isNull(loans.returnedAt))).get()!.n;
const report = (results: PromiseSettledResult<void>[]) =>
results.forEach((result, i) =>
console.log(` desk ${i + 1}: ${result.status === "fulfilled" ? "lent" : `refused (${(result.reason as Error).message})`}`),
);
console.log(`Mode: ${mode}${dropIndex ? ", without the partial unique index" : ""}`);
const book = onShelf[0];
console.log(`\nRace 1: two desks lend "${book.title}" to different members at once`);
report(await Promise.allSettled([lend(book.id, people[0].id), lend(book.id, people[1].id)]));
console.log(` open loans for this book: ${openFor(loans.bookId, book.id)}`);
const member = people[people.length - 1];
const spare = onShelf.slice(1);
while (openFor(loans.memberId, member.id) < 2) await lend(spare.shift()!.id, member.id);
console.log(`\nRace 2: ${member.name} holds 2 books; two desks lend one more each at once`);
report(await Promise.allSettled([lend(spare[0].id, member.id), lend(spare[1].id, member.id)]));
console.log(` books ${member.name} now holds: ${openFor(loans.memberId, member.id)} (limit 3)`);
}
main();
TS
npx tsx scripts/race-lend.ts naive --drop-indexsource.backup() is better-sqlite3's online backup, which copies a consistent snapshot even while the dev server has the database open.
Check it worked
The output looks something like this, with the first book on the shelf and the last member in your own data:
Mode: naive, without the partial unique index
Race 1: two desks lend "Things Fall Apart" to different members at once
desk 1: lent
desk 2: lent
open loans for this book: 2
Race 2: Chukwuemeka Obi holds 2 books; two desks lend one more each at once
desk 1: lent
desk 2: lent
books Chukwuemeka Obi now holds: 4 (limit 3)Both desks passed both checks, because each read the loans table before the other had written to it. Every check was correct at the moment it ran, and the result is still wrong. Now run the same race with part 2's partial unique index left in place:
npx tsx scripts/race-lend.ts naiveRace 1 changes: desk 2 is refused with a database error such as UNIQUE constraint failed: loans.book_id, and the book has one open loan. Race 2 does not change: the member still ends with four books. The index can say "at most one open loan per book", but no index can say "at most three open loans per member". That rule needs the code to be right.
Step 2 · Put the lending rules in one transaction
The fix is to make "check, then write" one indivisible unit. A database transaction does that, with one detail that matters in SQLite. A plain BEGIN (Drizzle's default, "deferred") starts as a reader and only asks for the write lock at its first write. Two deferred lends can both read "on the shelf"; when the second then tries to insert, SQLite sees that the data it read has changed since and fails it at once with a busy error (SQLITE_BUSY) instead of waiting, so the librarian gets an error page rather than a clear answer. BEGIN IMMEDIATE takes the write lock at the start. While one lend holds it, any other connection that wants to write waits (better-sqlite3 waits up to 5 seconds by default), and when its turn comes it reads the loans table as the first lend left it.
Drizzle exposes this as the behavior option on db.transaction(). With better-sqlite3 the transaction function must be synchronous: no async, no await, and every query ends with .get(), .all() or .run(). That restriction helps here, because nothing else in the Node.js process can run between your check and your insert.
Write the rules in their own module, src/lib/loan-rules.ts. It takes the database as its first argument instead of opening one, so the app passes its db from @/db and a script or test passes any connection it likes. It does not import server-only and uses relative imports, because the race script uses it now and part 8's tests use it later:
cat > src/lib/loan-rules.ts <<'TS'
// Rules 2 to 4 from docs/data-model.md. Nothing here knows about Next.js,
// sessions or caching, so scripts and tests can call it with any database.
import { and, count, eq, isNull } from "drizzle-orm";
import type { connect } from "../db/connect";
import { books, loans, members } from "../db/schema";
export type LibraryDb = ReturnType<typeof connect>;
export const LOAN_DAYS = 14;
export const MAX_OPEN_LOANS = 3;
const DAY_MS = 24 * 60 * 60 * 1000;
export type LendResult =
| { ok: true; loanId: number; dueAt: Date }
| { ok: false; reason: "no-such-book" | "no-such-member" | "on-loan" | "member-at-limit" };
export type ReturnResult = { ok: true; loanId: number } | { ok: false; reason: "not-on-loan" };
export function lendBook(
db: LibraryDb,
input: { bookId: number; memberId: number; now?: Date },
): LendResult {
const now = input.now ?? new Date();
// "immediate" takes SQLite's write lock before the first read. A second lend
// from another connection waits here, then sees the loan the first one wrote.
return db.transaction(
(tx): LendResult => {
const book = tx.select({ id: books.id }).from(books).where(eq(books.id, input.bookId)).get();
if (!book) return { ok: false, reason: "no-such-book" };
const member = tx
.select({ id: members.id })
.from(members)
.where(eq(members.id, input.memberId))
.get();
if (!member) return { ok: false, reason: "no-such-member" };
// Rule 2: a book can be out on only one loan at a time.
const open = tx
.select({ id: loans.id })
.from(loans)
.where(and(eq(loans.bookId, input.bookId), isNull(loans.returnedAt)))
.get();
if (open) return { ok: false, reason: "on-loan" };
// Rule 3: a member can hold at most three books at once.
const held = tx
.select({ total: count() })
.from(loans)
.where(and(eq(loans.memberId, input.memberId), isNull(loans.returnedAt)))
.get();
if ((held?.total ?? 0) >= MAX_OPEN_LOANS) return { ok: false, reason: "member-at-limit" };
const dueAt = new Date(now.getTime() + LOAN_DAYS * DAY_MS);
const [loan] = tx
.insert(loans)
.values({ bookId: input.bookId, memberId: input.memberId, lentAt: now, dueAt })
.returning({ id: loans.id })
.all();
return { ok: true, loanId: loan.id, dueAt };
},
{ behavior: "immediate" },
);
}
export function returnBook(db: LibraryDb, input: { bookId: number; now?: Date }): ReturnResult {
const now = input.now ?? new Date();
return db.transaction(
(tx): ReturnResult => {
const open = tx
.select({ id: loans.id })
.from(loans)
.where(and(eq(loans.bookId, input.bookId), isNull(loans.returnedAt)))
.get();
if (!open) return { ok: false, reason: "not-on-loan" };
tx.update(loans).set({ returnedAt: now }).where(eq(loans.id, open.id)).run();
return { ok: true, loanId: open.id };
},
{ behavior: "immediate" },
);
}
// Rule 4: overdue when now is after the due date and the book is still out.
export function isOverdue(loan: { dueAt: Date; returnedAt: Date | null }, now = new Date()): boolean {
return loan.returnedAt === null && now.getTime() > loan.dueAt.getTime();
}
TSFour things to notice:
- A broken rule is a return value, not an exception:
{ ok: false, reason: "on-loan" }. The caller turns the reason into a message for the librarian. An exception, such as a disk error or the unique index refusing an insert, means something really broke, and the transaction rolls back so a failed lend leaves no trace. - The book and member checks run inside the transaction too. A book deleted a moment ago cannot be lent.
returnBooktakes a book id, because that is what a librarian has in their hand at the desk. A second click on the same Return button finds no open loan and changes nothing.nowis a parameter with a default, so tests and back-dated entries can pass their own time.isOverduetakes it too, so the overdue list and part 8's tests agree on what "late" means.
Check it worked
Type-check the project, then load the module outside Next.js:
npx tsc --noEmit
npx tsx --eval 'console.log(Object.keys(require("./src/lib/loan-rules.ts")).sort().join(" "))'tsc prints nothing, and the second command prints LOAN_DAYS MAX_OPEN_LOANS isOverdue lendBook returnBook. If tsc reports Cannot find module '../db/connect', your database helper lives elsewhere: change the two imports at the top of loan-rules.ts to your paths. If it says it cannot find PageProps, run npx next typegen and try again.
Step 3 · Run the race against the rules
Run the same two races, this time through lendBook, and still without the index, so the transaction does all the work:
npx tsx scripts/race-lend.ts safe --drop-indexCheck it worked
This time one desk wins each race and the other gets the rule's reason:
Mode: safe, without the partial unique index
Race 1: two desks lend "Things Fall Apart" to different members at once
desk 1: lent
desk 2: refused (on-loan)
open loans for this book: 1
Race 2: Chukwuemeka Obi holds 2 books; two desks lend one more each at once
desk 1: lent
desk 2: refused (member-at-limit)
books Chukwuemeka Obi now holds: 3 (limit 3)Inside one Node.js process the synchronous transaction cannot be interleaved with another request. If you later run two copies of the app, or a script lends while the server runs, BEGIN IMMEDIATE makes the second writer wait for the first to commit, so the same result holds across processes.
So why keep the index? Because the transaction protects only code that goes through lendBook. A one-off import script, a fix typed into the sqlite3 shell, or a future developer's shortcut can insert into loans directly, and the index still refuses a second open loan for a book. The two layers do different jobs: the transaction gives librarians clear messages and covers rules an index cannot express; the index guards the one rule that would hurt most, whatever code runs.
If your src/db/schema.ts from part 2 has no loans_one_open_per_book index, add it to the loans table's index list (import sql from drizzle-orm and uniqueIndex from drizzle-orm/sqlite-core), then run npx drizzle-kit generate and npx drizzle-kit migrate:
uniqueIndex("loans_one_open_per_book").on(t.bookId).where(sql`returned_at is null`),The migration fails with a UNIQUE constraint failed error if a book already has two open loans. Close the extra one first.
Step 4 · Add lend and return server actions
Server actions are how the forms reach lendBook and returnBook. As in part 4, every server action is a public endpoint that anyone can POST to, so each one checks who is calling with requireLibrarian() and validates its input with Zod before it touches the database. Hiding the buttons from members is not enough.
First a small date formatter and the read queries the pages need. The queries module imports server-only and uses the app's one connection, db from @/db. Each function calls connection() first, as getBook does in part 3, because loans change all the time and Cache Components must not build them into the page ahead of time:
cat > src/lib/format.ts <<'TS'
const dateFormat = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric" });
export function formatDate(date: Date) {
return dateFormat.format(date);
}
TS
cat > src/lib/loans.ts <<'TS'
import "server-only";
import { connection } from "next/server";
import { and, asc, eq, isNull } from "drizzle-orm";
import { db } from "@/db";
import { books, loans, members } from "@/db/schema";
// Every book that is out, soonest due first.
export async function getOpenLoans() {
await connection();
return db
.select({
id: loans.id,
bookId: loans.bookId,
dueAt: loans.dueAt,
returnedAt: loans.returnedAt,
title: books.title,
memberName: members.name,
memberPhone: members.phone,
})
.from(loans)
.innerJoin(books, eq(loans.bookId, books.id))
.innerJoin(members, eq(loans.memberId, members.id))
.where(isNull(loans.returnedAt))
.orderBy(asc(loans.dueAt))
.all();
}
// The open loan for one book, or undefined if it is on the shelf.
export async function getOpenLoan(bookId: number) {
await connection();
return db
.select({ memberName: members.name, dueAt: loans.dueAt })
.from(loans)
.innerJoin(members, eq(loans.memberId, members.id))
.where(and(eq(loans.bookId, bookId), isNull(loans.returnedAt)))
.get();
}
export async function getMembers() {
await connection();
return db.select({ id: members.id, name: members.name }).from(members).orderBy(asc(members.name)).all();
}
TSDates show as 3 Dec 2026 whatever the visitor's language, which avoids the 03/12 versus 12/03 confusion. They use the server's time zone, so set the server's clock to the library's zone when you deploy in part 9.
Now the actions, in src/app/loans/actions.ts. They share their names with the rules, so the rules are imported as rules:
mkdir -p src/app/loans
cat > src/app/loans/actions.ts <<'TS'
"use server";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/db";
import * as rules from "@/lib/loan-rules";
import { requireLibrarian } from "@/lib/session";
const id = z.coerce.number().int().positive();
export async function lendBook(formData: FormData) {
await requireLibrarian();
const parsed = z
.object({ bookId: id, memberId: id })
.safeParse({ bookId: formData.get("bookId"), memberId: formData.get("memberId") });
if (!parsed.success) redirect("/books");
const { bookId, memberId } = parsed.data;
const result = rules.lendBook(db, { bookId, memberId });
// A refusal goes back to the book page with its reason, which the page turns into a message.
if (!result.ok) redirect(`/books/${bookId}?problem=${result.reason}`);
redirect(`/books/${bookId}`);
}
export async function returnBook(formData: FormData) {
await requireLibrarian();
const parsed = z.object({ bookId: id }).safeParse({ bookId: formData.get("bookId") });
if (!parsed.success) redirect("/loans");
const { bookId } = parsed.data;
// A second click finds the book already back: nothing changes.
rules.returnBook(db, { bookId });
redirect(`/books/${bookId}`);
}
TSrequireLibrarian() comes first, so a signed-out caller is sent to sign in and learns nothing, not even which fields are wrong. z.coerce.number() turns the form's text into a number, and a missing field becomes 0, which .positive() rejects. redirect() works by throwing, so nothing after it runs, and it is never inside a try. Each action ends on the book's page, which reads the database on every request, so the librarian sees the new status at once. Part 7 adds caching, and with it a call in both actions, just before the last redirect, that clears the cached catalogue.
Check it worked
npx tsc --noEmitIt prints nothing. If TypeScript says requireLibrarian is not exported, open src/lib/session.ts and use the name you gave the helper in part 5.
Step 5 · Put Lend and Return on the book page
A librarian lends from the book's own page: open the book, choose a member, press Lend. Members and visitors see the status and nothing else.
The submit button disables itself while its form is being sent. It needs useFormStatus, a React hook, so it is a tiny Client Component; the rest stays on the server:
cat > src/app/loans/submit-button.tsx <<'TSX'
"use client";
import type { ReactNode } from "react";
import { useFormStatus } from "react-dom";
export default function SubmitButton({
children,
pendingText,
label,
className,
}: {
children: ReactNode;
pendingText: string;
label?: string;
className?: string;
}) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-label={label} className={className}>
{pending ? pendingText : children}
</button>
);
}
TSX
cat > src/app/loans/loans.module.css <<'CSS'
.form {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.75rem;
margin: 1rem 0;
}
.field {
display: grid;
gap: 0.25rem;
font-weight: 600;
}
.field select {
font: inherit;
font-weight: 400;
padding: 0.5rem;
min-height: 2.75rem;
max-width: 100%;
}
.button {
font: inherit;
min-height: 2.75rem;
padding: 0.5rem 1rem;
border: 1px solid var(--line, #d9dce1);
border-radius: 0.375rem;
background: var(--paper, #ffffff);
}
.button:disabled {
opacity: 0.6;
}
.problem {
color: #a1260d;
font-weight: 600;
}
.list {
list-style: none;
margin: 0 0 2rem;
padding: 0;
display: grid;
gap: 0.5rem;
}
.loan {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem 1rem;
border: 1px solid var(--line, #d9dce1);
border-radius: 0.5rem;
padding: 0.75rem 1rem;
}
.overdue {
border-color: #a1260d;
}
.meta {
display: block;
color: var(--muted, #5b616b);
}
CSS
cat > "src/app/books/[id]/loan-desk.tsx" <<'TSX'
import { lendBook, returnBook } from "@/app/loans/actions";
import styles from "@/app/loans/loans.module.css";
import SubmitButton from "@/app/loans/submit-button";
import { LOAN_DAYS, MAX_OPEN_LOANS, type LendResult } from "@/lib/loan-rules";
import { getMembers } from "@/lib/loans";
type Problem = Extract<LendResult, { ok: false }>["reason"];
const problems: Record<Problem, string> = {
"no-such-book": "That book is not in the catalogue.",
"no-such-member": "That member is not registered.",
"on-loan": "This book was already on loan, so it was not lent again.",
"member-at-limit": `That member already has ${MAX_OPEN_LOANS} books out. Take one back first.`,
};
export default async function LoanDesk({
bookId,
onLoan,
problem,
}: {
bookId: number;
onLoan: boolean;
problem?: string;
}) {
// Only known reasons become a message; anything else in the URL is ignored.
const message = problem && Object.hasOwn(problems, problem) ? problems[problem as Problem] : null;
if (onLoan) {
return (
<section aria-label="Lending">
{message && <p role="alert" className={styles.problem}>{message}</p>}
<form action={returnBook} className={styles.form}>
<input type="hidden" name="bookId" value={bookId} />
<SubmitButton pendingText="Recording…" className={styles.button}>
Record return
</SubmitButton>
</form>
</section>
);
}
const people = await getMembers();
return (
<section aria-label="Lending">
{message && <p role="alert" className={styles.problem}>{message}</p>}
<form action={lendBook} className={styles.form}>
<input type="hidden" name="bookId" value={bookId} />
<label className={styles.field}>
Member
<select name="memberId" required defaultValue="">
<option value="" disabled>
Choose a member
</option>
{people.map((person) => (
<option key={person.id} value={person.id}>
{person.name}
</option>
))}
</select>
</label>
<SubmitButton pendingText="Lending…" className={styles.button}>
Lend for {LOAN_DAYS} days
</SubmitButton>
</form>
</section>
);
}
TSXNow replace src/app/books/[id]/page.tsx. It keeps the details and title from part 3 and the librarian-only edit link from part 5, and adds the loan status and the desk:
cat > "src/app/books/[id]/page.tsx" <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getBook } from "@/lib/books";
import { formatDate } from "@/lib/format";
import { getOpenLoan } from "@/lib/loans";
import { getLibrarian } from "@/lib/session";
import LoanDesk from "./loan-desk";
export async function generateMetadata({ params }: PageProps<"/books/[id]">): Promise<Metadata> {
const { id } = await params;
const book = await getBook(id);
return { title: book ? book.title : "Book not found" };
}
export default async function BookPage({ params, searchParams }: PageProps<"/books/[id]">) {
const { id } = await params;
const book = await getBook(id);
if (!book) notFound();
const [librarian, loan, query] = await Promise.all([getLibrarian(), getOpenLoan(book.id), searchParams]);
const problem = typeof query.problem === "string" ? query.problem : undefined;
// Members see when a book is due back; only librarians see who has it.
let status = "On the shelf";
if (loan) {
status = librarian
? `On loan to ${loan.memberName}, due back ${formatDate(loan.dueAt)}`
: `On loan, due back ${formatDate(loan.dueAt)}`;
}
return (
<main>
<p>
<Link href="/books">Back to all books</Link>
</p>
<h1>{book.title}</h1>
<dl>
<dt>Author</dt>
<dd>{book.author}</dd>
<dt>First published</dt>
<dd>{book.year}</dd>
<dt>Status</dt>
<dd>{status}</dd>
</dl>
{librarian ? (
<>
<LoanDesk bookId={book.id} onLoan={Boolean(loan)} problem={problem} />
<p>
<Link href={`/books/${book.id}/edit`}>Edit this book</Link>
</p>
</>
) : (
<p>Ask a librarian at the desk to borrow this book.</p>
)}
</main>
);
}
TSX
npx tsc --noEmitA few choices worth seeing:
- The page reads the status from
getOpenLoanrather than from the "available" flag, so the status line and the desk are always based on the same query. - The member list puts "Choose a member" first and
requiredon the select, so pressing Lend without choosing is caught by the browser. - The disabled button stops most accidental double clicks, but it is a convenience, not the protection. A fast double click can send two requests before React redraws the button, and a slow phone makes that more likely. The protection is the transaction: the second request finds the book on loan and changes nothing.
- The forms are plain HTML forms posting to server actions, so they work before the page's JavaScript has loaded. On a low-end Android phone on a slow prepaid connection, a librarian can lend or record a return as soon as the page appears.
Check it worked
npx tsc --noEmit prints nothing. If it says Object.hasOwn does not exist, your tsconfig.json has an old lib setting; create-next-app 16 uses esnext, which includes it.
Step 6 · List what is out and what is overdue
The loans page at /loans is for the start of a shift: what is overdue, who to phone, and every book that is out, with a Record return button for books handed back at the desk. It is librarians only, and everything on it is read per request, so the list sits inside <Suspense>: with Cache Components, the heading is built ahead of time and the lists are streamed for each request.
cat > src/app/loans/page.tsx <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import { Suspense } from "react";
import { formatDate } from "@/lib/format";
import { isOverdue } from "@/lib/loan-rules";
import { getOpenLoans } from "@/lib/loans";
import { requireLibrarian } from "@/lib/session";
import { returnBook } from "./actions";
import styles from "./loans.module.css";
import SubmitButton from "./submit-button";
export const metadata: Metadata = { title: "Loans" };
const DAY_MS = 24 * 60 * 60 * 1000;
export default function LoansPage() {
return (
<main>
<h1>Loans</h1>
<Suspense fallback={<p>Opening the loans book...</p>}>
<LoanLists />
</Suspense>
</main>
);
}
async function LoanLists() {
await requireLibrarian();
const openLoans = await getOpenLoans();
const now = new Date();
const overdue = openLoans.filter((loan) => isOverdue(loan, now));
return (
<>
<h2>Overdue ({overdue.length})</h2>
{overdue.length === 0 ? (
<p>Nothing is overdue.</p>
) : (
<ul className={styles.list} aria-label="Overdue loans">
{overdue.map((loan) => (
<li key={loan.id} className={`${styles.loan} ${styles.overdue}`}>
<span>
<Link href={`/books/${loan.bookId}`}>{loan.title}</Link>
<span className={styles.meta}>
{loan.memberName}
{loan.memberPhone ? `, ${loan.memberPhone}` : ""}. Due {formatDate(loan.dueAt)},{" "}
{Math.ceil((now.getTime() - loan.dueAt.getTime()) / DAY_MS)} days late.
</span>
</span>
</li>
))}
</ul>
)}
<h2>Out on loan ({openLoans.length})</h2>
<ul className={styles.list} aria-label="Books out on loan">
{openLoans.map((loan) => (
<li key={loan.id} className={styles.loan}>
<span>
<Link href={`/books/${loan.bookId}`}>{loan.title}</Link>
<span className={styles.meta}>
{loan.memberName}. Due {formatDate(loan.dueAt)}.
</span>
</span>
<form action={returnBook}>
<input type="hidden" name="bookId" value={loan.bookId} />
<SubmitButton
pendingText="Recording…"
label={`Record return of "${loan.title}"`}
className={styles.button}
>
Record return
</SubmitButton>
</form>
</li>
))}
</ul>
</>
);
}
TSXrequireLibrarian() comes first in LoanLists, before any query, so a signed-out visitor never causes a database read. The overdue filter uses isOverdue from the rules module, the same function part 8 tests. The overdue list shows the member's phone number when there is one, because a call or SMS is how most small libraries chase a late book. Each Record return button has an aria-label naming its book, so a screen reader user hears "Record return of Americanah" instead of a list of identical buttons. After a return, the action takes the librarian to that book's page, which now says "On the shelf".
Start the dev server in your second terminal:
npm run devCheck it worked
Open http://localhost:3000/loans in a private browser window, where you are signed out: you see the Loans heading for a moment, then land on the sign-in page. Sign in as a librarian and open /loans again: you see an Overdue section and an "Out on loan" list. Part 2's seed data includes a loan that is already late, so the Overdue section has at least one entry ("A Brief History of Time" with the series seed), with how many days late it is.
Then open a book that is on the shelf, such as "So Long a Letter". Signed in, you see a Member select and a "Lend for 14 days" button; open a book that is out and you see "On loan to" with the member's name and a "Record return" button. In the private window the same pages show only the status and "Ask a librarian at the desk to borrow this book."
Step 7 · Lend, return and double-click in the browser
Try the desk the way a busy Saturday would.
- Lend a book: open "So Long a Letter", choose Ama Mensah and press "Lend for 14 days". The page reloads with the status
On loan to Ama Mensah, due back 3 Dec 2026(14 days from today) and a "Record return" button. - Two desks, one book: open "Weep Not, Child" in two tabs. Choose a different member in each. Press Lend in the first tab, then in the second. The second tab's page was out of date, and the server says so:
This book was already on loan, so it was not lent again.in red, with the status showing who has it. - The member limit: lend books to one member until they hold three. The next lend to them is refused with
That member already has 3 books out. Take one back first. - Double-click: on a book that is on the shelf, choose a member and double-click Lend. The book is lent once:
/loanslists it once. If the second click got through before the button was disabled, you also see the "already on loan" message, which is that second request being refused. - Return: on
/loans, press Record return next to "So Long a Letter". You land on its page, now "On the shelf". Click Record return quickly twice on another book and the second click changes nothing.
Stop the dev server with Ctrl+C when you are done.
Check it worked
Run the safe race again with npx tsx scripts/race-lend.ts safe. It works on a copy of your current data, so it picks a different book if the first one is now out, and still ends with one open loan per book and at most three per member.
Step 8 · Check the production build
Cache Components makes the production build check how each page uses request-time data, so build before you move on. Open next.config.ts first and make sure it has cacheComponents: true. Cache Components is opt-in: this one key in next.config.ts turns it on, and without it the build skips these checks. If the line is missing, add it so the file reads:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;Keep any other keys you added in earlier parts. Then lint and build:
npm run lintnpm run buildCheck it worked
npm run lint prints no errors and the build finishes. In the route table, /loans is marked ◐ (partial prerender): the heading and fallback are built ahead of time and the lists are streamed for each request. If the build instead says that uncached data was accessed outside of <Suspense>, something in LoansPage itself reads the session or the database; move it into LoanLists.
Start the production server and repeat the two-tab test from the last step:
npm run startThe production server answers the page shell the same way as the dev server:
curl -s http://localhost:3000/loans | grep -o '<h1>Loans</h1>'This prints <h1>Loans</h1>. Stop the server with Ctrl+C. Keep ~/community-library-demo, src/lib/loan-rules.ts and scripts/race-lend.ts: part 7 caches the catalogue and adds a refresh call to lendBook and returnBook in src/app/loans/actions.ts, and part 8 tests the rules module and turns the race into a test.
Next steps
- Continue the series: Cache library pages with Next.js 16 Cache Components and refresh them on change makes the catalogue fast without ever showing a lent book as on the shelf.
- Test the library app: loan rules in Vitest, journeys in Playwright turns today's race into a test that would have caught the double lend.
- Go back to Sign in librarians with Better Auth and protect actions if
requireLibrarian()is missing or a member can reach/loans. - For
useFormStatusand pending states on their own, see Build forms in React 19 with actions.
Part of these paths
Related tutorials
- Sign in librarians with Better Auth and protect actionsYou 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.
- Cache library pages with Next.js 16 Cache Components and refresh them on changeYou will cache the library catalogue with the "use cache" directive, cacheLife and cacheTag, refresh it with updateTag after every edit or loan and with revalidateTag from outside the app, and end with a fast catalogue that never serves a lent book as available.
- 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.
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