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: "Review Queue", template: "%s · Review Queue" }, }; export default function Layout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue</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.trim(); if (!title || title.length > 60) return { ok: false, code: "invalid_title" }; return { ok: true, title }; } export function canWrite(actor, row) { return Boolean(actor && row && 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.toLowerCase().includes(q.toLowerCase()), ) .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 (!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 tenant = make().get({ id: "ada", tenantId: "other" }, 1) === null; const deletion = make().remove({ id: "grace", tenantId: "local" }, 1).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: "Tenant isolation", pass: tenant }, { name: "Deletion permission", pass: deletion }, { 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 failures concern tenant isolation, deletion authorization, output projection and version checks. For each, write a counterexample and the state that should remain unchanged before editing anything.

Hint 2: a first step

Each finding names the rule it guards. Start from the check in lib/review-checks.js, note the call it makes, and follow that call into lib/repository.js and the helper it uses in lib/domain.js. Two of the bugs are in domain.js helpers that several operations share, so one fix there repairs more than one operation. Compare each line with what Day 1 or Day 2 said it must check.

The four bugs
FindingThe broken lineThe fixTaught on
Tenant isolationcanWrite compares only actor.id === row.ownerIdalso require actor.tenantId === row.tenantIdDay 1, deny by default
Deletion permissionremove checks only if (!row)if (!canWrite(actor, row)), the same guard as editDay 1, trusted actor
Public projectionpublicItem returns { ...row }an allowlist: { id: row.id, title: row.title, version: row.version }Day 1, minimal output
Stale edit rejectededit has no version comparisonif (row.version !== version) return { ok: false, code: "conflict" }; before the writeDay 2, concurrent edits

The tenant bug lives in a shared helper, so it also let get and list read across tenants; fixing canWrite repairs all of them. The spread in publicItem sends ownerId and tenantId to every page and route that shows an item. The exercise is complete when all four findings pass without any change to lib/review-checks.js.

Retrieval questions

  1. Which values come from a caller, and where is identity established? (Day 1)
  2. Which fields may leave the server, even for an authorized reader? (Day 1)
  3. What must remain unchanged after a rejected mutation, and how would a test prove it? (Days 2 and 6)
  4. What makes a version check atomic with the write? (Day 2)
  5. Why can offset pages skip a row, and how does a cursor with limit + 1 know there's no next page? (Day 3)
  6. Which changes to an error vocabulary are safe for existing clients, and what must a client do with a code it doesn't know? (Day 3)
  7. When should a request be retried, and how long may each call wait inside one deadline? (Day 4)
  8. Which cache scope could return another caller's data, and why can't a "use cache" function read cookies()? (Day 5)
  9. Why does toLocaleTimeString() in a client component's first render cause a hydration error, and what's the fix? (Day 5)
  10. What's the difference between a readiness probe and a release gate? (Day 6)
  11. Which evidence must come from a real Next.js build or database? (Day 7)

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.