Skip to content

Come Back Later

The Course
•
20 min study

Return a few days after finishing. Close the earlier lessons and use your own notes only after a first attempt from memory.

Four boundary bugs

This copy of the project has four deliberately broken rules. The case table runs repository operations on fresh fixtures and reports four findings. Fix the implementation in lib/domain.js and lib/repository.js, not the checks in lib/review-checks.js.

Four boundary bugs Next.js · 16 files
import "./globals.css"; import Link from "next/link"; export const metadata = { title: { default: "Study Library", template: "%s · Study Library" }, }; export default function Layout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library</strong> <p> Practice app: the server uses a fixed Ada actor. No real authentication is implemented. </p> <nav> <Link href="/">Items</Link> <Link href="/new">Add an item</Link> </nav> </header> {children} </body> </html> ); } import { reviewChecks } from "@/lib/review-checks.js"; export default function Review() { const checks = reviewChecks(); return ( <main> <h1>Four boundary bugs</h1> <p>Review findings: {checks.filter((check) => !check.pass).length}</p> <ul> {checks.map((check) => ( <li key={check.name}> {check.pass ? "PASS" : "FAIL"}: {check.name} </li> ))} </ul> <p> Open lib/repository.js and lib/domain.js. Fix the rules, not these checks. </p> </main> ); } "use server"; import { redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function saveItem(previous, formData) { const raw = formData.get("title"); const title = typeof raw === "string" ? raw : ""; const id = Number(formData.get("id")); const version = Number(formData.get("version")); const result = id ? repository.edit(currentActor(), id, version, { title }) : repository.create(currentActor(), { title }); if (!result.ok) return { title, error: result.code === "conflict" ? "This item changed. Reload before saving." : result.code === "not_found" ? "This item is unavailable." : "Enter a title of 1–60 characters.", }; revalidatePath("/"); revalidatePath(`/items/${result.item.id}`); redirect(`/items/${result.item.id}`); } export async function removeItem(id) { const result = repository.remove(currentActor(), id); if (!result.ok) throw new Error("Item unavailable"); revalidatePath("/"); redirect("/"); } "use client"; export default function ErrorPage({ retry }) { return ( <main> <h1>Could not load this view</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function ItemForm({ item }) { const [state, action, pending] = useActionState(saveItem, { error: null, title: item?.title ?? "", }); return ( <form action={action}> <input type="hidden" name="id" value={item?.id ?? ""} /> <input type="hidden" name="version" value={item?.version ?? ""} /> <label> Title{" "} <input name="title" defaultValue={state.title} aria-invalid={Boolean(state.error)} aria-describedby="save-error" /> </label> <p id="save-error" role="alert"> {state.error} </p> <button disabled={pending}> {pending ? "Saving…" : item ? "Save changes" : "Add item"} </button> </form> ); } body { font: 16px/1.5 system-ui; background: #f5f8fc; color: #183048; margin: 0; } main, header { max-width: 850px; margin: auto; padding: 20px; } input, button { font: inherit; padding: 8px; margin: 4px; } a { color: #075985; } li { padding: 12px; } form { margin: 16px 0; } nav { display: flex; gap: 16px; } [role="alert"] { color: #a01818; } label { display: block; } section { padding: 12px; background: white; border-radius: 8px; } code { overflow-wrap: anywhere; } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } import { repository } from "@/lib/repository.js"; export async function GET() { try { const ready = repository.probe(); return Response.json( { ready }, { status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } }, ); } catch { return Response.json({ ready: false }, { status: 503 }); } } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; return Response.json(repository.list(currentActor(), q), { headers: { "Cache-Control": "private, no-store" }, }); } export async function POST(request) { let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } const result = repository.create(currentActor(), input); return Response.json(result, { status: result.ok ? 201 : 400 }); } import Link from "next/link"; export default function Missing() { return ( <main> <h1>Item unavailable</h1> <p>It may be missing or not visible to this caller.</p> <Link href="/">All items</Link> </main> ); } import { notFound } from "next/navigation"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ItemForm from "../../ItemForm.jsx"; import { removeItem } from "../../actions.js"; export const dynamic = "force-dynamic"; export default async function ItemPage({ params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) notFound(); return ( <main> <h1>{item.title}</h1> <p>Version {item.version}</p> <ItemForm item={item} /> <form action={removeItem.bind(null, item.id)}> <button>Remove item</button> </form> </main> ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); return Response.json(item ?? { code: "not_found" }, { status: item ? 200 : 404, headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const { id } = await params; let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } if (!input || !Number.isInteger(input.version) || input.version < 1) return Response.json({ code: "invalid_version" }, { status: 400 }); const result = repository.edit( currentActor(), Number(id), input.version, input, ); return Response.json(result, { status: result.ok ? 200 : result.code === "conflict" ? 409 : result.code === "not_found" ? 404 : 400, }); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); return Response.json(result, { status: result.ok ? 200 : 404 }); } export function currentActor() { return { id: "ada", tenantId: "local" }; } export function validateDraft(input) { if (!input || typeof input.title !== "string") return { ok: false, code: "invalid_title" }; const title = input.title; if (title.length > 60) return { ok: false, code: "invalid_title" }; return { ok: true, title }; } export function canWrite(actor, row) { return Boolean( actor && row && actor.tenantId === row.tenantId && actor.id === row.ownerId, ); } export function publicItem(row) { return { ...row }; } export const seed = [ { id: 1, title: "Read about server boundaries", ownerId: "ada", tenantId: "local", version: 1, }, { id: 2, title: "Test a stale edit", ownerId: "ada", tenantId: "local", version: 1, }, { id: 3, title: "Grace's private review", ownerId: "grace", tenantId: "local", version: 1, }, ]; import { validateDraft, canWrite, publicItem, seed } from "./domain.js"; export function createRepository(initial = seed) { let rows = initial.map((row) => ({ ...row })); let nextId = Math.max(0, ...rows.map((row) => row.id)) + 1; return { list(actor, q = "") { return rows .filter((row) => canWrite(actor, row) && row.title.includes(q)) .map(publicItem); }, get(actor, id) { const row = rows.find((row) => row.id === id); return canWrite(actor, row) ? publicItem(row) : null; }, create(actor, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const valid = validateDraft(input); if (!valid.ok) return valid; const row = { id: nextId++, title: valid.title, ownerId: actor.id, tenantId: actor.tenantId, version: 1, }; rows = [...rows, row]; return { ok: true, item: publicItem(row) }; }, edit(actor, id, version, input) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; const valid = validateDraft(input); if (!valid.ok) return valid; const next = { ...row, title: valid.title, version: row.version + 1 }; rows = rows.map((item) => (item.id === id ? next : item)); return { ok: true, item: publicItem(next) }; }, remove(actor, id) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; rows = rows.filter((row) => row.id !== id); return { ok: true }; }, probe() { return true; }, close() {}, }; } export const repository = createRepository(); import { createRepository } from "./repository.js"; export function reviewChecks() { const make = () => createRepository(); const ada = { id: "ada", tenantId: "local" }; const search = make().list(ada, "read").length === 1; const blank = make().create(ada, { title: " " }).ok === false; const projection = !Object.hasOwn(make().get(ada, 1), "ownerId"); const repo = make(); repo.edit(ada, 1, 1, { title: "First" }); const conflict = repo.edit(ada, 1, 1, { title: "Stale" }).code === "conflict"; return [ { name: "Case-insensitive search", pass: search }, { name: "Blank draft rejected", pass: blank }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, ]; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

The four findings are about searching, validating a title, what leaves the server, and editing. Before changing anything, write for each one an input that shows the bug and what the correct result would be.

Hint 2: a first step

Read the four failing checks' names in the table. Then compare three places with the Study Library lesson's code: validateDraft and publicItem in lib/domain.js, and list and edit in lib/repository.js. Each holds one bug, except domain.js, which holds two.

The four bugs
BugWhy it's wrongFixDay
list filters with row.title.includes(q)Searching read misses Read about server boundaries: the search is case-sensitive.Compare row.title.toLowerCase() with q.toLowerCase().1
validateDraft uses input.title untrimmed and has no blank checkA title of spaces is saved, and spaces around a title count towards 60.const title = input.title.trim(); then reject !title.2
publicItem returns { ...row }ownerId and tenantId leave the server, and any column added later will too: a denylist by accident.Return only id, title and version.1
edit has no version checkAn edit from a stale page silently overwrites someone's newer save: a lost update.if (row.version !== version) return { ok: false, code: "conflict" }; before writing.4

The owner scoping (canWrite) is still correct in this copy; a fix that touches it is fixing the wrong thing. The exercise is complete when the four findings disappear and the checks in lib/review-checks.js are unchanged.

Retrieval questions

  1. Which values come from a caller, and where is identity established?
  2. Which fields may leave the server, even for an authorized reader?
  3. What must remain unchanged after a rejected mutation?
  4. What makes a version check atomic with the write?
  5. Which cache lifetime or scope could return another caller's data?
  6. What can a pure rule test prove that a browser check cannot, and vice versa?
  7. Which evidence must come from a real Next.js build or database?
  8. What would you change before offering the practice app to multiple users?

If any answer is vague, redo that day's checkpoint without the solution. Completion is a useful record of practice, not evidence of mastery by itself.

Was this article helpful?

Your response is saved on this device.