Lesson 26 of 27Production Next.js
Project: A Neighbourhood Tool Library
Build a members-only tool library in Next.js 16 on your own machine, stage by stage: Server Components that read a data file, cached reads with use cache and cache tags, a join form and proxy, a borrow Server Action with useActionState, a public route handler with metadata, and a Vitest suite.
You have learned the App Router one idea at a time. This project puts those ideas in one small app, in the order you would add them on a real job. The app is a tool library for one street. Neighbours join with a shared code, browse a drill, a ladder, a saw and a pressure washer, and borrow one for 7 or 14 days. Another site can read which tools are free from a small JSON API.
Next.js needs a real Node.js server, so this is a guided build. You type the files on your own machine, run the exact commands, and compare what you see with the output shown here. One piece of pure logic, the due date, also runs in the browser below.
The code was checked with Next.js 16.4, React 19.3, Zod 4 and Vitest 5 on Node.js 24. Next.js moves fast. If a flag or a message differs on your machine, the official docs at nextjs.org/docs are the reference, not this page.
The plan: read fast, write safely
Most visits only read: the list of tools and one tool's page. Those reads should come from a cache and arrive as static HTML. Writes are rare: joining and borrowing. Each write goes through a Server Action that checks who you are, validates the input, changes the data and then invalidates the cache, so the next read is fresh.
The data lives in one JSON file, data/library.json, behind a small server-only data layer. That keeps the setup to a single npm install. Because every read and write goes through the data layer, swapping the file for Postgres later changes one file, as Databases and the Data Access Layer recommended.
The form posts to the page it lives on. Proxy only checks that a member cookie exists. It is a quick redirect, not the security check.
Stage 1: a server-rendered catalogue
Create the app with the same flags as the Project Lab, minus Tailwind and the src folder to keep the paths short. Then add the two packages the data layer needs:
npx create-next-app@latest tool-library --ts --eslint --app --no-tailwind --no-src-dir --import-alias "@/*" --use-npm --yescd tool-librarynpm install zod server-onlyThe installer ends with Success! Created tool-library at .... Open next.config.ts. Recent versions of create-next-app already set cacheComponents: true, the switch behind partial prerendering from Rendering Strategies. If yours does not, add it inside the config object. Delete app/page.module.css, which nothing will use.
Now the data. Create a data folder with the four tools. A loan of null means the tool is on the shelf:
[
{ "id": "drill", "name": "Cordless drill", "category": "Power tools", "description": "18V drill with two batteries and a bit set.", "loan": null },
{ "id": "ladder", "name": "Step ladder", "category": "Access", "description": "Six-step aluminium ladder, good to 2.5 m.", "loan": null },
{ "id": "saw", "name": "Hand saw", "category": "Hand tools", "description": "Fine-tooth saw for timber up to 10 cm.", "loan": null },
{ "id": "washer", "name": "Pressure washer", "category": "Garden", "description": "For patios, bikes and bins. Bring your own hose.", "loan": null }
]The types go in their own file with no server imports, so tests and Client Components can use them:
export type Loan = { member: string; dueBack: string };
export type Tool = {
id: string;
name: string;
category: string;
description: string;
loan: Loan | null;
};The data layer starts with import "server-only". If a Client Component ever imports it, the build fails instead of shipping file paths to the browser, as Server and Client Components showed:
import "server-only";
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Tool } from "./loans";
const FILE = path.join(process.cwd(), "data", "library.json");
async function readAll(): Promise<Tool[]> {
return JSON.parse(await readFile(FILE, "utf8")) as Tool[];
}
export async function getTools(): Promise<Tool[]> {
return readAll();
}
export async function getTool(id: string): Promise<Tool | null> {
const tools = await readAll();
return tools.find((tool) => tool.id === id) ?? null;
}Replace the generated layout and home page. Both are Server Components: they are async, they call the data layer directly, and they ship no JavaScript of their own. The title.template sets a pattern each page will fill in during stage 5.
import type { Metadata } from "next";
import Link from "next/link";
import "./globals.css";
export const metadata: Metadata = {
title: { default: "Tool Library", template: "%s | Tool Library" },
description: "Borrow tools from your neighbours.",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="en">
<body>
<header>
<Link href="/">Tool Library</Link>
</header>
<main>{children}</main>
</body>
</html>
);
}import Link from "next/link";
import { getTools } from "@/lib/library";
export default async function HomePage() {
const tools = await getTools();
return (
<>
<h1>Tools</h1>
<ul>
{tools.map((tool) => (
<li key={tool.id}>
<Link href={`/tools/${tool.id}`}>{tool.name}</Link>{" "}
{tool.loan ? `(out until ${tool.loan.dueBack})` : "(available)"}
</li>
))}
</ul>
</>
);
}Add a loading file at the root and a page for one tool. The folder [id] is a dynamic segment from App Router Routing, and PageProps<"/tools/[id]"> is the typed helper that comes with it. params is a promise in Next.js 16, so you await it. An unknown id calls notFound().
export default function Loading() {
return <p>Loading tools...</p>;
}import { notFound } from "next/navigation";
import { getTool } from "@/lib/library";
export default async function ToolPage({ params }: PageProps<"/tools/[id]">) {
const { id } = await params;
const tool = await getTool(id);
if (!tool) notFound();
return (
<article>
<h1>{tool.name}</h1>
<p>{tool.category}</p>
<p>{tool.description}</p>
{tool.loan ? <p>Out with {tool.loan.member} until {tool.loan.dueBack}.</p> : <p>Available.</p>}
</article>
);
}Check it. Run npm run dev. You should see ▲ Next.js 16.4.3, a Local: http://localhost:3000 line and ✓ Ready. Open that address: four tools, all available. Click the drill and you get its page. Then stop the server and run npm run build. Both routes show ◐ (Partial Prerender). Next.js prerenders the shell and the loading text, and streams the file read on every request, as Streaming, Loading UI and Instant Navigations described. Now delete app/loading.tsx and build again. It fails with Route "/": Next.js encountered uncached or runtime data during prerendering. With Cache Components on, uncached data must sit inside a Suspense boundary or be cached. Put the file back. The next stage takes the second option.
Stage 2: cache the reads, handle the failures
The catalogue changes only when someone borrows a tool. Reading the file on every visit is wasted work. Following Data Fetching and Caching, mark both reads with "use cache", tag them so a write can expire them, and give them a lifetime. Change the top of lib/library.ts and the two read functions:
import "server-only";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { cacheLife, cacheTag } from "next/cache";
import type { Tool } from "./loans";
const FILE = path.join(process.cwd(), "data", "library.json");
async function readAll(): Promise<Tool[]> {
return JSON.parse(await readFile(FILE, "utf8")) as Tool[];
}
export async function getTools(): Promise<Tool[]> {
"use cache";
cacheTag("tools");
cacheLife("hours");
return readAll();
}
export async function getTool(id: string): Promise<Tool | null> {
"use cache";
cacheTag("tools");
cacheLife("hours");
const tools = await readAll();
return tools.find((tool) => tool.id === id) ?? null;
}The id argument is part of the cache key, so each tool gets its own entry, as Cache Components in Depth explained. Both entries share the tools tag, so one call can expire them all.
Next, tell Next.js which tool pages to build ahead of time. Add generateStaticParams to the tool page, above the component, and update the import, as in Dynamic Routes and Static Generation:
import { notFound } from "next/navigation";
import { getTool, getTools } from "@/lib/library";
export async function generateStaticParams() {
const tools = await getTools();
return tools.map((tool) => ({ id: tool.id }));
}Finally, plan for failure, as Error Handling in Next.js taught. A missing tool is expected, so it gets a friendly not-found.tsx. A broken data file is unexpected, so it lands in error.tsx. That file must be a Client Component, because reset is an event handler. It shows the digest, which matches the server log, and never the raw message.
import Link from "next/link";
export default function NotFound() {
return (
<>
<h1>No such tool</h1>
<Link href="/">Back to all tools</Link>
</>
);
}"use client";
export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<div role="alert">
<h1>Something went wrong</h1>
<p>Reference: {error.digest ?? "none"}</p>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Check it. Run npm run build. The route table now looks like this:
Route (app) Revalidate Expire
┌ ○ / 1h 1d
├ ○ /_not-found
└ /tools/[id]
├ ◐ /tools/[id]
├ ○ /tools/drill 1h 1d
├ ○ /tools/ladder 1h 1d
└ ◐ [+2 more paths]The home page and every known tool are now ○ static, with the hours profile shown as a 1 hour revalidate. Run npm start and open /tools/hammer. You see "No such tool". The status is 200, not 404, because the loading shell had already streamed. Error Handling in Next.js explained why: the status goes out with the first byte. Next.js adds a noindex tag, so search engines still skip the page.
Stage 3: members, a join form and proxy
Only members may borrow. A member here is anyone who knows the library's shared code, which lives in an environment variable. Create .env.local in the project root. create-next-app already lists .env* in .gitignore, so it stays on your machine.
LIBRARY_CODE=shed-42Add the schemas. Form data is always strings, so z.coerce.number() turns "14" into 14 before the check:
import { z } from "zod";
export const BorrowSchema = z.object({
toolId: z.string().min(1),
days: z.coerce.number().int().refine((d) => d === 7 || d === 14, "Pick 7 or 14 days"),
});
export const JoinSchema = z.object({
name: z.string().trim().min(2, "Use at least 2 characters").max(40),
code: z.string().min(1, "Enter the library code"),
});Then a tiny session module. getMember() is the real membership check. Every action will call it:
import "server-only";
import { cookies } from "next/headers";
export const MEMBER_COOKIE = "member";
export async function getMember(): Promise<string | null> {
const store = await cookies();
return store.get(MEMBER_COOKIE)?.value ?? null;
}The join action follows Server Actions and Forms. It takes the previous state and the form data, validates with safeParse, and returns errors as values, never by throwing. On success it sets an httpOnly cookie and redirects:
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { JoinSchema } from "@/lib/schemas";
import { MEMBER_COOKIE } from "@/lib/session";
export type FormState = { error: string | null; message: string | null };
export async function join(_prev: FormState, formData: FormData): Promise<FormState> {
const parsed = JoinSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: parsed.error.issues[0].message, message: null };
if (parsed.data.code !== process.env.LIBRARY_CODE) return { error: "Wrong library code.", message: null };
const store = await cookies();
store.set(MEMBER_COOKIE, parsed.data.name, { httpOnly: true, sameSite: "lax", path: "/" });
redirect("/");
}The form is a small Client Component. useActionState gives it the last result and a pending flag, so the button can say what is happening. The page around it stays a Server Component.
"use client";
import { useActionState } from "react";
import { join, type FormState } from "@/app/actions";
const initial: FormState = { error: null, message: null };
export function JoinForm() {
const [state, formAction, pending] = useActionState(join, initial);
return (
<form action={formAction}>
<label>
Your name <input name="name" required />
</label>
<label>
Library code <input name="code" type="password" required />
</label>
<button disabled={pending}>{pending ? "Joining..." : "Join"}</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}import type { Metadata } from "next";
import { JoinForm } from "./JoinForm";
export const metadata: Metadata = { title: "Join" };
export default function JoinPage() {
return (
<>
<h1>Join the library</h1>
<JoinForm />
</>
);
}Last, proxy.ts in the project root, next to package.json. As Auth and Proxy warned, proxy is an optimistic redirect for people with no cookie at all. It is not where security lives. The matcher skips /join, the API and static files, so the join page can load:
import { NextResponse, type NextRequest } from "next/server";
export function proxy(request: NextRequest) {
if (!request.cookies.has("member")) {
return NextResponse.redirect(new URL("/join", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!join|api|_next/static|_next/image|favicon.ico).*)"],
};Check it. Restart npm run dev, because Next.js reads .env.local at startup. In a second terminal, ask for the home page without a cookie:
curl -sI http://localhost:3000/ | head -3HTTP/1.1 307 Temporary Redirect
location: /join
...In the browser you land on the join form. A wrong code shows "Wrong library code." under the button. The right one, shed-42, sets the cookie and takes you to the tools.
Stage 4: borrowing with a Server Action
A loan needs a due date. Keep that rule pure: it takes "today" as an argument instead of reading the clock, so a test can pin the date. Add these two functions to the end of lib/loans.ts. Here they are on their own, so you can run them:
Press Run (⌘ Enter) to see what happens.Dates as YYYY-MM-DD strings compare correctly with <, which keeps isOverdue to one line. In your file, put export in front of both functions. Then give the data layer a write. Add writeFile to the node:fs/promises import, add Loan to the type import, and put this at the end of lib/library.ts:
export async function setLoan(id: string, loan: Loan | null): Promise<void> {
const tools = await readAll();
const next = tools.map((tool) => (tool.id === id ? { ...tool, loan } : tool));
await writeFile(FILE, JSON.stringify(next, null, 2) + "\n");
}Now the action. Its steps follow Securing a Next.js App: who is asking, is the input valid, is the change allowed, then write and refresh. Here is the whole of app/actions.ts now, with the new imports and borrowTool added below join:
"use server";
import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { getTool, setLoan } from "@/lib/library";
import { dueDate } from "@/lib/loans";
import { BorrowSchema, JoinSchema } from "@/lib/schemas";
import { getMember, MEMBER_COOKIE } from "@/lib/session";
export type FormState = { error: string | null; message: string | null };
export async function borrowTool(_prev: FormState, formData: FormData): Promise<FormState> {
const member = await getMember();
if (!member) return { error: "Join the library before you borrow.", message: null };
const parsed = BorrowSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: parsed.error.issues[0].message, message: null };
const tool = await getTool(parsed.data.toolId);
if (!tool) return { error: "That tool does not exist.", message: null };
if (tool.loan) return { error: `Already out until ${tool.loan.dueBack}.`, message: null };
const due = dueDate(new Date(), parsed.data.days);
await setLoan(tool.id, { member, dueBack: due });
updateTag("tools");
return { error: null, message: `Borrowed. Bring it back by ${due}.` };
}
export async function join(_prev: FormState, formData: FormData): Promise<FormState> {
const parsed = JoinSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: parsed.error.issues[0].message, message: null };
if (parsed.data.code !== process.env.LIBRARY_CODE) return { error: "Wrong library code.", message: null };
const store = await cookies();
store.set(MEMBER_COOKIE, parsed.data.name, { httpOnly: true, sameSite: "lax", path: "/" });
redirect("/");
}Notice that the member comes from the cookie, never from the form. A hidden member field could be edited by anyone. updateTag is the Server Action version of revalidation from Server Actions and Forms: it expires the tag at once, so the page the action returns already shows the loan. A webhook in a route handler would call revalidateTag("tools", "max") instead.
The form sends the tool id in a hidden field, and the action checks it like any other input:
"use client";
import { useActionState } from "react";
import { borrowTool, type FormState } from "@/app/actions";
const initial: FormState = { error: null, message: null };
export function BorrowForm({ toolId }: { toolId: string }) {
const [state, formAction, pending] = useActionState(borrowTool, initial);
return (
<form action={formAction}>
<input type="hidden" name="toolId" value={toolId} />
<label>
Borrow for{" "}
<select name="days" defaultValue="7">
<option value="7">7 days</option>
<option value="14">14 days</option>
</select>
</label>{" "}
<button disabled={pending}>{pending ? "Borrowing..." : "Borrow"}</button>
{state.error && <p role="alert">{state.error}</p>}
{state.message && <p role="status">{state.message}</p>}
</form>
);
}In app/tools/[id]/page.tsx, import BorrowForm from ./BorrowForm and swap the "Available." paragraph for the form:
{tool.loan ? (
<p>Out with {tool.loan.member} until {tool.loan.dueBack}.</p>
) : (
<BorrowForm toolId={tool.id} />
)}Check it. Run npm run build and then npm start, so you test the real cache rather than the dev server. Join, open the drill, pick 14 days and click Borrow. The button reads "Borrowing..." for a moment, then "Borrowed. Bring it back by ..." with a date 14 days away. Go back to the list: the drill says "out until" that date, with no reload and no hour-long wait. Open data/library.json and the loan is there. To reset, set loan back to null, then rebuild.
Put the steps inside borrowTool in the order the code runs them.
- Tap the steps below in the right order.
Stage 5: a public API and page metadata
The community centre wants a "free tools" box on its own site. That is another server calling yours, so it needs a plain HTTP endpoint, not an action. Route Handlers covered when to pick which. The handler returns only what a stranger may see: no member names.
import { getTools } from "@/lib/library";
export async function GET() {
const tools = await getTools();
return Response.json(
tools.map((tool) => ({ id: tool.id, name: tool.name, available: tool.loan === null })),
);
}It reuses the cached getTools, so it carries the tools tag too. A borrow refreshes the API along with the pages.
Then give each tool page its own title and description, from Metadata and Images. Add this to app/tools/[id]/page.tsx, and add import type { Metadata } from "next"; at the top. It calls the same cached getTool as the page, so the data is read once:
export async function generateMetadata({ params }: PageProps<"/tools/[id]">): Promise<Metadata> {
const { id } = await params;
const tool = await getTool(id);
return tool ? { title: tool.name, description: tool.description } : { title: "Not found" };
}Check it. Build and start again, then call the API. The matcher skips /api, so no cookie is needed:
curl -s http://localhost:3000/api/tools[{"id":"drill","name":"Cordless drill","available":true},{"id":"ladder","name":"Step ladder","available":true},{"id":"saw","name":"Hand saw","available":true},{"id":"washer","name":"Pressure washer","available":true}]If you borrowed the drill and did not reset it, it shows "available":false. In the browser, the tab for the drill reads "Cordless drill | Tool Library", which is the layout's template filled in. The build table now also lists ○ /api/tools and ○ /join, and a line ƒ Proxy (Middleware).
Match each file in the tool library to the job it does.
Stage 6: tests that pin the rules
Testing Next.js Apps said to test logic and handlers with direct calls in plain Node, and leave full flows to Playwright. Install Vitest. At the time of writing, its peer range needs a newer @types/node than create-next-app installs, so ask for both:
npm install -D vitest @types/node@24npm pkg set scripts.test="vitest run"The config only needs to understand the @/ alias:
import { defineConfig } from "vitest/config";
export default defineConfig({
resolve: {
alias: { "@": new URL(".", import.meta.url).pathname },
},
test: {
environment: "node",
},
});Pure functions get pinned dates, including a month boundary and the due day itself:
import { describe, expect, test } from "vitest";
import { dueDate, isOverdue } from "./loans";
describe("dueDate", () => {
test("adds days in UTC", () => {
expect(dueDate(new Date("2026-10-23T09:00:00Z"), 7)).toBe("2026-10-30");
});
test("rolls over the month end", () => {
expect(dueDate(new Date("2026-10-28T09:00:00Z"), 14)).toBe("2026-11-11");
});
});
describe("isOverdue", () => {
const loan = { member: "Sam", dueBack: "2026-10-30" };
test("is not overdue on the due date", () => {
expect(isOverdue(loan, new Date("2026-10-30T18:00:00Z"))).toBe(false);
});
test("is overdue the day after", () => {
expect(isOverdue(loan, new Date("2026-10-31T08:00:00Z"))).toBe(true);
});
});The schema test proves the form string becomes a number and that a 30-day loan is refused:
import { expect, test } from "vitest";
import { BorrowSchema } from "./schemas";
test("accepts 7 or 14 days from a form string", () => {
const result = BorrowSchema.safeParse({ toolId: "drill", days: "14" });
expect(result.success && result.data.days).toBe(14);
});
test("rejects any other length", () => {
const result = BorrowSchema.safeParse({ toolId: "drill", days: "30" });
expect(result.success).toBe(false);
});The route handler is just a function that returns a Response, so you call it. Mocking the data layer keeps the file system, server-only and the cache out of the test, and lets you assert the privacy rule:
import { expect, test, vi } from "vitest";
import { GET } from "./route";
vi.mock("@/lib/library", () => ({
getTools: async () => [
{ id: "drill", name: "Cordless drill", category: "Power tools", description: "", loan: null },
{ id: "saw", name: "Hand saw", category: "Hand tools", description: "", loan: { member: "Sam", dueBack: "2026-10-30" } },
],
}));
test("GET lists availability without member names", async () => {
const response = await GET();
expect(response.status).toBe(200);
expect(await response.json()).toEqual([
{ id: "drill", name: "Cordless drill", available: true },
{ id: "saw", name: "Hand saw", available: false },
]);
});Check it. Run npm test:
Test Files 3 passed (3)
Tests 7 passed (7)Then run npm run lint (no output means clean) and npx tsc --noEmit. Break something on purpose: change 14 to 15 in the schema refine and watch one test fail with the expected and received values side by side.
What does this print?
function dueDate(today: Date, days: number): string {
const due = new Date(today);
due.setUTCDate(due.getUTCDate() + days);
return due.toISOString().slice(0, 10);
}
console.log(dueDate(new Date("2026-12-25T23:30:00Z"), 7));Make it yours
The core works. These would make it worth showing:
- A real database. Replace
data/library.jsonwith Postgres behind the same data layer, as in Databases and the Data Access Layer. Make "borrow if free" one conditionalUPDATE, so two neighbours clicking at once cannot both get the drill. - Real sessions. A plain name in a cookie can be forged. Sign it, or use a session library, and store sessions so you can revoke them, following Auth and Proxy.
- Returns and overdue reminders. Add a "Return" action that calls
setLoan(id, null), and a "My loans" page that usesisOverdue. Read the cookie inside a Suspense boundary, since it is runtime data. - Search and categories in the URL. Filter the list with
?q=and?category=, parsed on the server, as Search Params and URL State taught. - Ship it. Add a Playwright test for join and borrow, then deploy with Deploying Next.js. A JSON file does not survive serverless deploys, which is one more reason for the database.
When it is done, write it up with the Interview Prep lesson Writing Project Case Studies.
Build it for real in the Project Lab
- Did you drink water today? builds the same idea in plain JavaScript: state in an array, a render function and data saved between visits.
- Sticky notes, sorted practices a status field driving which column a card lives in, the same shape as a borrow status.
- data layer
- A server-only module that every read and write goes through, so storage and access rules live in one place.
- cache tag
- A label set with cacheTag on cached data, so updateTag or revalidateTag can expire every entry that carries it.
- updateTag
- The Server Action call that expires a tag at once, so the response to the action already shows fresh data.
- useActionState
- A React hook that wires a form to an action and returns the last result and a pending flag.
- proxy
- The proxy.ts file that runs before matched routes. Good for quick redirects, never the only security check.
- generateStaticParams
- A function in a dynamic route that lists the params to prerender at build time.
- Partial Prerender
- A route whose static shell is built ahead of time while uncached parts stream in on each request, shown as ◐ in the build output.
That is a tool library a real street could use. The wrap-up next pulls the whole course together around one more realistic feature, from a slow old page to a watched production release.