About 20 minutes of active study
Include time to predict, run, change, and explain the code. This is a suggested pace, not a time limit.
Read a complete application
This app connects the course's rules to actual pages, actions and JSON routes.
It lists only records visible to a server-selected Ada fixture, supports
search, validates creates and edits, rejects stale edits and lets the caller
remove an item. Use it before reading the implementation.
Every rule in it is one you've practised this week:
In the app Where you met it A normalized search term, and public fields only Day 1: request values, public records Validated drafts and result shapes; write, invalidate, then redirect Day 2 Another owner's item answers as missing; an edit carries the version it read, and a stale one is a conflict Day 4: Status and Body Must Agree Repository tests with fresh fixtures, and adapter tests Day 6
Each row also has a tenantId, always "local" here, and canWrite checks it
alongside the owner. It's a placeholder for a multi-organization app; the
advanced course is where tenants are taught. In this project, read it as
"same owner".
Study Library 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 Link from "next/link";
import { Suspense } from "react";
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
export const dynamic = "force-dynamic";
async function Count({ count }) {
await new Promise((resolve) => setTimeout(resolve, 350));
return <p>{count} visible items</p>;
}
export default async function Page({ searchParams }) {
const params = await searchParams;
const raw = Array.isArray(params.q) ? params.q[0] : params.q;
const q = typeof raw === "string" ? raw.trim() : "";
const rows = repository.list(currentActor(), q);
return (
<main>
<h1>Study Library</h1>
<form action="/">
<label>
Search <input name="q" defaultValue={q} />
</label>
<button>Search</button>
</form>
<ul>
{rows.map((row) => (
<li key={row.id}>
<Link href={`/items/${row.id}`}>{row.title}</Link> · version{" "}
{row.version}
</li>
))}
</ul>
{!rows.length && <p>No items match.</p>}
<Suspense key={q} fallback={<p>Counting…</p>}>
<Count count={rows.length} />
</Suspense>
</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.tenantId === row.tenantId && actor.id === row.ownerId,
);
}
export function publicItem(row) {
return { id: row.id, title: row.title, version: row.version };
}
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" };
if (row.version !== version) return { ok: false, code: "conflict" };
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 },
];
}
Trace the boundaries
Search for read . The page unwraps searchParams, normalizes the query
and asks repository.list for public items:
const params = await searchParams ;
const raw = Array . isArray ( params . q ) ? params . q [ 0 ] : params . q ;
const q = typeof raw === "string" ? raw . trim () : "" ;
const rows = repository . list ( currentActor (), q );
Follow Read about server boundaries . The dynamic page checks visibility
before rendering the record; an unknown or unavailable id selects notFound:
const { id } = await params ;
const item = repository . get ( currentActor (), Number ( id ));
if ( ! item ) notFound ();
Save a blank title. The action returns a recoverable error and the draft;
the field is marked invalid and its alert region is linked by description:
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." ,
};
Save a real edit. The repository checks its expected version atomically in
the SQLite download, then the action invalidates the view and redirects:
edit ( actor , id , version , input ) {
const row = rows . find (( row ) => row . id === id );
if ( ! canWrite ( actor , row )) return { ok : false , code : "not_found" };
if ( row . version !== version ) return { ok : false , code : "conflict" };
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 ) };
},
revalidatePath ( "/" );
revalidatePath ( `/items/ ${ result . item . id } ` );
redirect ( `/items/ ${ result . item . id } ` );
Open /api/items and /api/items/1 in the preview address bar. Compare
their public fields with the domain's internal record shape.
Read lib/domain.js, lib/repository.js, app/actions.js, app/ItemForm.jsx
and app/api/items/[id]/route.js in that order. Explain where each input becomes
trusted enough for the next operation. An id from a form is still untrusted.
Scope of this project
This is a boundary-design project, not a finished multi-user product.
currentActor() is a fixed server-side fixture, not authentication . A real
session provider must replace it before offering private data to real users.
The browser repository lives in memory; Run restarts it. The lab toolbar
downloads that memory version. Use the separate SQLite ZIP in the next lesson
for persistent storage and a conditional version update. Neither the simulator nor a pure
policy test proves a production cache or distributed deployment is correct.
Exercise Trace one rejected write Describe what happens when an edit carries an old version. Name the result
from the repository, the message in the form, and the data that must remain
unchanged. Then compare it with an unavailable record.
Your answer Saved in this browser as you type. Hint 1: the idea Follow the result through the repository and action before looking at JSX.
A rejection is useful only if no earlier write already happened.
Hint 2: a first step Find the version comparison in edit, then the error mapping in saveItem.
The input's hidden version is a precondition, not a permission check.
Show one solution A stale version produces conflict; saveItem returns the submitted title
with This item changed. Reload before saving. It does not invalidate or
redirect. The stored title and version stay as they were after the first edit.
An unavailable record instead returns a generic unavailable result so the
caller is not told another owner's data. Tests assert both the rejection and
unchanged stored state.
Mark as done Completion is saved in this browser only. It does not measure mastery.