Skip to content

Extend the API with Preconditions

The Course
•
25 min study

The Review Queue's JSON API already refuses stale edits, but it learns the expected version from the request body, a convention only this API knows. HTTP has a standard for it, the one Day 3 taught: the server sends an ETag with each item, and an edit says If-Match with the tag it last saw. Caches, proxies and HTTP libraries understand those headers. Plan on about 25 minutes in the browser.

Extension workspace Next.js · 23 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> <Link href="/reviews">Review a batch</Link> <Link href="/console">API console</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>Review Queue</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; } textarea { display: block; max-width: 100%; font: 14px/1.5 monospace; padding: 8px; box-sizing: border-box; } "use client"; import { useState } from "react"; export default function ApiConsole() { const [method, setMethod] = useState("GET"); const [path, setPath] = useState("/api/items?limit=2"); const [key, setKey] = useState(""); const [ifMatch, setIfMatch] = useState(""); const [body, setBody] = useState(""); const [result, setResult] = useState(""); async function send() { const headers = { "Content-Type": "application/json" }; if (key) headers["Idempotency-Key"] = key; if (ifMatch) headers["If-Match"] = ifMatch; const response = await fetch(path, { method, headers, body: method === "GET" ? undefined : body, }); const etag = response.headers.get("ETag"); const text = await response.text(); setResult(`${response.status} ${etag ? `ETag: ${etag} ` : ""}${text}`); } return ( <section> <label> Method{" "} <select value={method} onChange={(event) => setMethod(event.target.value)}> <option>GET</option> <option>POST</option> <option>PATCH</option> <option>DELETE</option> </select> </label>{" "} <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label> <p> <label> Idempotency-Key{" "} <input value={key} onChange={(event) => setKey(event.target.value)} /> </label> </p> <p> <label> If-Match{" "} <input value={ifMatch} onChange={(event) => setIfMatch(event.target.value)} /> </label> </p> <p> <label> Body{" "} <input value={body} onChange={(event) => setBody(event.target.value)} /> </label> </p> <button onClick={send}>Send request</button> <p role="status">{result}</p> </section> ); } import ApiConsole from "./ApiConsole.jsx"; export const metadata = { title: "API console" }; export default function Page() { return ( <main> <h1>API console</h1> <p>Send requests to this app's route handlers as the fixed Ada actor.</p> <ApiConsole /> </main> ); } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } "use server"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { revalidatePath } from "next/cache"; export async function reviewBatch(previous, form) { const source = form.get("edits"); let input; try { input = JSON.parse(typeof source === "string" ? source : ""); } catch { return { message: "Enter a JSON array of edits.", ok: false }; } const result = repository.applyBatch(currentActor(), input); if (!result.ok) return { message: `No edits saved: ${result.code}. Refresh to get current versions.`, ok: false, }; revalidatePath("/"); for (const item of result.items) revalidatePath(`/items/${item.id}`); return { message: `Saved ${result.items.length} edits together.`, ok: true }; } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ReviewForm from "./ReviewForm.jsx"; export const dynamic = "force-dynamic"; export default function Reviews() { return ( <main> <h1>Review a batch</h1> <p> Edit titles in the JSON below. Every id must occur once; each version must still match. A rejected edit saves none of the batch. Refresh this page after saving to load current versions. </p> <ReviewForm items={repository.list(currentActor()).slice(0, 20)} /> </main> ); } "use client"; import { useActionState } from "react"; import { reviewBatch } from "./actions.js"; export default function ReviewForm({ items }) { const [state, action, pending] = useActionState(reviewBatch, { message: "", ok: false, }); return ( <form action={action}> <label htmlFor="review-edits">Review batch</label> <textarea id="review-edits" name="edits" rows={10} cols={45} defaultValue={JSON.stringify(items, null, 2)} aria-describedby="review-result" /> <button disabled={pending}> {pending ? "Saving…" : "Save entire batch"} </button> <p id="review-result" role="status"> {state.message} </p> </form> ); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; // GET /api/items?after=2&limit=2: a keyset page of the caller's items. export async function GET(request) { const requestId = newRequestId(); const params = new URL(request.url).searchParams; const limit = params.has("limit") ? Number(params.get("limit")) : 10; if (!Number.isInteger(limit) || limit < 1 || limit > 50) return errorResponse("invalid_limit", requestId); const after = params.has("after") ? Number(params.get("after")) : 0; if (!Number.isInteger(after) || after < 0) return errorResponse("invalid_cursor", requestId); return Response.json(repository.page(currentActor(), { after, limit }), { headers: { "Cache-Control": "private, no-store" }, }); } // POST /api/items with an Idempotency-Key header: a retry with the same key // and title returns the first result instead of saving twice. export async function POST(request) { const requestId = newRequestId(); const key = request.headers.get("Idempotency-Key"); if (!key) return errorResponse("missing_key", requestId); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.createOnce(currentActor(), key, body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json( { item: result.item, replayed: Boolean(result.replayed) }, { status: result.replayed ? 200 : 201 }, ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; export async function PATCH(request) { const requestId = newRequestId(); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.applyBatch(currentActor(), body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result, { headers: { "Cache-Control": "private, no-store" }, }); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) return errorResponse("not_found", newRequestId()); return Response.json(item, { headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const requestId = newRequestId(); const { id } = await params; const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const input = body.value; if (!input || !Number.isInteger(input.version) || input.version < 1) return errorResponse("invalid_version", requestId); const result = repository.edit(currentActor(), Number(id), input.version, input); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); if (!result.ok) return errorResponse(result.code, newRequestId()); return Response.json(result); } 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, }, ]; export function validateBatch(input) { if (!Array.isArray(input) || input.length < 1 || input.length > 20) return { ok: false, code: "invalid_batch" }; const ids = new Set(); const edits = []; for (const edit of input) { if ( !edit || !Number.isSafeInteger(edit.id) || edit.id < 1 || !Number.isSafeInteger(edit.version) || edit.version < 1 || ids.has(edit.id) ) return { ok: false, code: "invalid_batch" }; const valid = validateDraft(edit); if (!valid.ok) return valid; ids.add(edit.id); edits.push({ id: edit.id, version: edit.version, title: valid.title }); } return { ok: true, edits }; } // The service's public error vocabulary (Day 3). Clients branch on `code` // and must treat an unknown code by its status class. const STATUS = new Map( Object.entries({ invalid_json: 400, invalid_title: 400, invalid_batch: 400, invalid_version: 400, invalid_limit: 400, invalid_cursor: 400, missing_key: 400, unauthenticated: 401, not_found: 404, conflict: 409, key_reused: 422, }), ); export function newRequestId() { const bytes = crypto.getRandomValues(new Uint8Array(6)); return "req_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } // Known codes keep their status; anything else is a generic 500. Only the // code and the request id reach the caller; details go to the server log. export function errorResponse(code, requestId, detail) { const status = STATUS.get(code) ?? 500; const publicCode = status === 500 ? "internal_error" : code; console.log(`${requestId} ${publicCode}${detail ? `: ${detail}` : ""}`); return Response.json( { code: publicCode, requestId }, { status, headers: { "Cache-Control": "private, no-store" } }, ); } export async function readJson(request) { try { return { ok: true, value: await request.json() }; } catch { return { ok: false, code: "invalid_json" }; } } import { validateDraft, validateBatch, 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; // Idempotency receipts (Day 2): one per actor and key, with the payload // they were for. In SQLite this is a table written in the same transaction. const receipts = new Map(); return { list(actor, q = "") { return rows .filter( (row) => canWrite(actor, row) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, // Keyset pages (Day 3): rows after the cursor, one extra to learn whether // another page exists. page(actor, { after = 0, limit = 10 } = {}) { const window = rows .filter((row) => canWrite(actor, row) && row.id > after) .toSorted((a, b) => a.id - b.id) .slice(0, limit + 1); const items = window.slice(0, limit).map(publicItem); return { items, nextCursor: window.length > limit ? items.at(-1).id : null }; }, createOnce(actor, key, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const receiptKey = JSON.stringify([actor.tenantId, actor.id, key]); const fingerprint = JSON.stringify(input?.title ?? null); const receipt = receipts.get(receiptKey); if (receipt) { if (receipt.fingerprint !== fingerprint) return { ok: false, code: "key_reused" }; return { ...receipt.result, replayed: true }; } const result = this.create(actor, input); // Only a successful create is remembered; an invalid draft may be // corrected and sent again with the same key. if (result.ok) receipts.set(receiptKey, { fingerprint, result }); return result; }, 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) }; }, applyBatch(actor, input) { const valid = validateBatch(input); if (!valid.ok) return valid; const draft = rows.map((row) => ({ ...row })); const items = []; for (const edit of valid.edits) { const row = draft.find((row) => row.id === edit.id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== edit.version) return { ok: false, code: "conflict" }; row.title = edit.title; row.version++; items.push(publicItem(row)); } rows = draft; return { ok: true, items }; }, 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 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"; const pager = make(); const first = pager.page(ada, { limit: 1 }); pager.remove(ada, first.items[0].id); const second = pager.page(ada, { after: first.nextCursor, limit: 1 }); const paging = second.items[0]?.id === 2 && second.nextCursor === null; const once = make(); once.createOnce(ada, "k1", { title: "Retry me" }); const replay = once.createOnce(ada, "k1", { title: "Retry me" }); const idempotent = replay.replayed === true && once.list(ada).filter((row) => row.title === "Retry me").length === 1; return [ { name: "Tenant isolation", pass: tenant }, { name: "Deletion permission", pass: deletion }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, { name: "Cursor page survives a delete", pass: paging }, { name: "Retried create saves once", pass: idempotent }, ]; }
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.

Plan before you type

Write down your answer to each of these first. Each comes from an earlier day:

  1. What is the tag? It must change exactly when the item does, so build it from the version: "v1", "v2". It's a strong tag (Day 3).
  2. What if If-Match is missing? Existing clients send version in the body, and requiring the header would break them. Adding a way to send the precondition is additive; removing the old way is breaking (Day 3). Accept a body version when the header is absent; with neither, answer 428 precondition_required.
  3. What if the tag doesn't match? 412 precondition_failed, including a weak tag such as W/"v2" (Day 3). A body version that's stale stays a 409 conflict, as before, so old clients see no change.
  4. Where's the check? Turn the tag into the expected version and pass it to the existing repository.edit. Don't compare versions again in the handler: the repository's check is the one that's atomic with the write (Day 2).
  5. What do errors look like? Two new codes, added to the map in lib/http.js. Older clients will treat them by status class (Day 3).
Exercise

ETag and If-Match on the item API

Change app/api/items/[id]/route.js and lib/http.js:

  • GET /api/items/1 sends ETag: "v1".
  • PATCH reads If-Match first, then a body version, as planned above. A successful edit sends the new ETag.

Acceptance checks, in the API console (it shows the response's ETag and has an If-Match field):

  1. GET /api/items/1 → 200 ETag: "v1".
  2. PATCH /api/items/1, If-Match "v1", body {"title": "Tagged"} → 200 ETag: "v2".
  3. The same request again → 412 precondition_failed.
  4. If-Match W/"v2" → 412. No If-Match and no body version → 428.
  5. Body {"title": "Old client", "version": 2} with no header → 200, as an existing client expects.
Your working space Next.js · 23 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> <Link href="/reviews">Review a batch</Link> <Link href="/console">API console</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>Review Queue</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; } textarea { display: block; max-width: 100%; font: 14px/1.5 monospace; padding: 8px; box-sizing: border-box; } "use client"; import { useState } from "react"; export default function ApiConsole() { const [method, setMethod] = useState("GET"); const [path, setPath] = useState("/api/items?limit=2"); const [key, setKey] = useState(""); const [ifMatch, setIfMatch] = useState(""); const [body, setBody] = useState(""); const [result, setResult] = useState(""); async function send() { const headers = { "Content-Type": "application/json" }; if (key) headers["Idempotency-Key"] = key; if (ifMatch) headers["If-Match"] = ifMatch; const response = await fetch(path, { method, headers, body: method === "GET" ? undefined : body, }); const etag = response.headers.get("ETag"); const text = await response.text(); setResult(`${response.status} ${etag ? `ETag: ${etag} ` : ""}${text}`); } return ( <section> <label> Method{" "} <select value={method} onChange={(event) => setMethod(event.target.value)}> <option>GET</option> <option>POST</option> <option>PATCH</option> <option>DELETE</option> </select> </label>{" "} <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label> <p> <label> Idempotency-Key{" "} <input value={key} onChange={(event) => setKey(event.target.value)} /> </label> </p> <p> <label> If-Match{" "} <input value={ifMatch} onChange={(event) => setIfMatch(event.target.value)} /> </label> </p> <p> <label> Body{" "} <input value={body} onChange={(event) => setBody(event.target.value)} /> </label> </p> <button onClick={send}>Send request</button> <p role="status">{result}</p> </section> ); } import ApiConsole from "./ApiConsole.jsx"; export const metadata = { title: "API console" }; export default function Page() { return ( <main> <h1>API console</h1> <p>Send requests to this app's route handlers as the fixed Ada actor.</p> <ApiConsole /> </main> ); } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } "use server"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { revalidatePath } from "next/cache"; export async function reviewBatch(previous, form) { const source = form.get("edits"); let input; try { input = JSON.parse(typeof source === "string" ? source : ""); } catch { return { message: "Enter a JSON array of edits.", ok: false }; } const result = repository.applyBatch(currentActor(), input); if (!result.ok) return { message: `No edits saved: ${result.code}. Refresh to get current versions.`, ok: false, }; revalidatePath("/"); for (const item of result.items) revalidatePath(`/items/${item.id}`); return { message: `Saved ${result.items.length} edits together.`, ok: true }; } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ReviewForm from "./ReviewForm.jsx"; export const dynamic = "force-dynamic"; export default function Reviews() { return ( <main> <h1>Review a batch</h1> <p> Edit titles in the JSON below. Every id must occur once; each version must still match. A rejected edit saves none of the batch. Refresh this page after saving to load current versions. </p> <ReviewForm items={repository.list(currentActor()).slice(0, 20)} /> </main> ); } "use client"; import { useActionState } from "react"; import { reviewBatch } from "./actions.js"; export default function ReviewForm({ items }) { const [state, action, pending] = useActionState(reviewBatch, { message: "", ok: false, }); return ( <form action={action}> <label htmlFor="review-edits">Review batch</label> <textarea id="review-edits" name="edits" rows={10} cols={45} defaultValue={JSON.stringify(items, null, 2)} aria-describedby="review-result" /> <button disabled={pending}> {pending ? "Saving…" : "Save entire batch"} </button> <p id="review-result" role="status"> {state.message} </p> </form> ); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; // GET /api/items?after=2&limit=2: a keyset page of the caller's items. export async function GET(request) { const requestId = newRequestId(); const params = new URL(request.url).searchParams; const limit = params.has("limit") ? Number(params.get("limit")) : 10; if (!Number.isInteger(limit) || limit < 1 || limit > 50) return errorResponse("invalid_limit", requestId); const after = params.has("after") ? Number(params.get("after")) : 0; if (!Number.isInteger(after) || after < 0) return errorResponse("invalid_cursor", requestId); return Response.json(repository.page(currentActor(), { after, limit }), { headers: { "Cache-Control": "private, no-store" }, }); } // POST /api/items with an Idempotency-Key header: a retry with the same key // and title returns the first result instead of saving twice. export async function POST(request) { const requestId = newRequestId(); const key = request.headers.get("Idempotency-Key"); if (!key) return errorResponse("missing_key", requestId); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.createOnce(currentActor(), key, body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json( { item: result.item, replayed: Boolean(result.replayed) }, { status: result.replayed ? 200 : 201 }, ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; export async function PATCH(request) { const requestId = newRequestId(); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.applyBatch(currentActor(), body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result, { headers: { "Cache-Control": "private, no-store" }, }); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) return errorResponse("not_found", newRequestId()); return Response.json(item, { headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const requestId = newRequestId(); const { id } = await params; const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const input = body.value; if (!input || !Number.isInteger(input.version) || input.version < 1) return errorResponse("invalid_version", requestId); const result = repository.edit(currentActor(), Number(id), input.version, input); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); if (!result.ok) return errorResponse(result.code, newRequestId()); return Response.json(result); } 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, }, ]; export function validateBatch(input) { if (!Array.isArray(input) || input.length < 1 || input.length > 20) return { ok: false, code: "invalid_batch" }; const ids = new Set(); const edits = []; for (const edit of input) { if ( !edit || !Number.isSafeInteger(edit.id) || edit.id < 1 || !Number.isSafeInteger(edit.version) || edit.version < 1 || ids.has(edit.id) ) return { ok: false, code: "invalid_batch" }; const valid = validateDraft(edit); if (!valid.ok) return valid; ids.add(edit.id); edits.push({ id: edit.id, version: edit.version, title: valid.title }); } return { ok: true, edits }; } // The service's public error vocabulary (Day 3). Clients branch on `code` // and must treat an unknown code by its status class. const STATUS = new Map( Object.entries({ invalid_json: 400, invalid_title: 400, invalid_batch: 400, invalid_version: 400, invalid_limit: 400, invalid_cursor: 400, missing_key: 400, unauthenticated: 401, not_found: 404, conflict: 409, key_reused: 422, }), ); export function newRequestId() { const bytes = crypto.getRandomValues(new Uint8Array(6)); return "req_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } // Known codes keep their status; anything else is a generic 500. Only the // code and the request id reach the caller; details go to the server log. export function errorResponse(code, requestId, detail) { const status = STATUS.get(code) ?? 500; const publicCode = status === 500 ? "internal_error" : code; console.log(`${requestId} ${publicCode}${detail ? `: ${detail}` : ""}`); return Response.json( { code: publicCode, requestId }, { status, headers: { "Cache-Control": "private, no-store" } }, ); } export async function readJson(request) { try { return { ok: true, value: await request.json() }; } catch { return { ok: false, code: "invalid_json" }; } } import { validateDraft, validateBatch, 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; // Idempotency receipts (Day 2): one per actor and key, with the payload // they were for. In SQLite this is a table written in the same transaction. const receipts = new Map(); return { list(actor, q = "") { return rows .filter( (row) => canWrite(actor, row) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, // Keyset pages (Day 3): rows after the cursor, one extra to learn whether // another page exists. page(actor, { after = 0, limit = 10 } = {}) { const window = rows .filter((row) => canWrite(actor, row) && row.id > after) .toSorted((a, b) => a.id - b.id) .slice(0, limit + 1); const items = window.slice(0, limit).map(publicItem); return { items, nextCursor: window.length > limit ? items.at(-1).id : null }; }, createOnce(actor, key, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const receiptKey = JSON.stringify([actor.tenantId, actor.id, key]); const fingerprint = JSON.stringify(input?.title ?? null); const receipt = receipts.get(receiptKey); if (receipt) { if (receipt.fingerprint !== fingerprint) return { ok: false, code: "key_reused" }; return { ...receipt.result, replayed: true }; } const result = this.create(actor, input); // Only a successful create is remembered; an invalid draft may be // corrected and sent again with the same key. if (result.ok) receipts.set(receiptKey, { fingerprint, result }); return result; }, 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) }; }, applyBatch(actor, input) { const valid = validateBatch(input); if (!valid.ok) return valid; const draft = rows.map((row) => ({ ...row })); const items = []; for (const edit of valid.edits) { const row = draft.find((row) => row.id === edit.id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== edit.version) return { ok: false, code: "conflict" }; row.title = edit.title; row.version++; items.push(publicItem(row)); } rows = draft; return { ok: true, items }; }, 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 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"; const pager = make(); const first = pager.page(ada, { limit: 1 }); pager.remove(ada, first.items[0].id); const second = pager.page(ada, { after: first.nextCursor, limit: 1 }); const paging = second.items[0]?.id === 2 && second.nextCursor === null; const once = make(); once.createOnce(ada, "k1", { title: "Retry me" }); const replay = once.createOnce(ada, "k1", { title: "Retry me" }); const idempotent = replay.replayed === true && once.list(ada).filter((row) => row.title === "Retry me").length === 1; return [ { name: "Tenant isolation", pass: tenant }, { name: "Deletion permission", pass: deletion }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, { name: "Cursor page survives a delete", pass: paging }, { name: "Retried create saves once", pass: idempotent }, ]; }
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 header is a new way to deliver the same precondition the body version already delivers. Convert it into an expected version early, and everything after that point, including the repository, stays as it is.

Hint 2: a first step

Write a small function, precondition(request, input), that returns either { ok: true, version } or { ok: false, code }. Check the header first: a regular expression such as /^"v(\d+)"$/ both validates the tag and extracts the number, and it rejects W/ tags automatically. Make GET send the header before you start on PATCH, so you can copy a real tag into the console.

One implementation
Preconditions: one implementation Next.js · 23 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> <Link href="/reviews">Review a batch</Link> <Link href="/console">API console</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>Review Queue</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; } textarea { display: block; max-width: 100%; font: 14px/1.5 monospace; padding: 8px; box-sizing: border-box; } "use client"; import { useState } from "react"; export default function ApiConsole() { const [method, setMethod] = useState("GET"); const [path, setPath] = useState("/api/items?limit=2"); const [key, setKey] = useState(""); const [ifMatch, setIfMatch] = useState(""); const [body, setBody] = useState(""); const [result, setResult] = useState(""); async function send() { const headers = { "Content-Type": "application/json" }; if (key) headers["Idempotency-Key"] = key; if (ifMatch) headers["If-Match"] = ifMatch; const response = await fetch(path, { method, headers, body: method === "GET" ? undefined : body, }); const etag = response.headers.get("ETag"); const text = await response.text(); setResult(`${response.status} ${etag ? `ETag: ${etag} ` : ""}${text}`); } return ( <section> <label> Method{" "} <select value={method} onChange={(event) => setMethod(event.target.value)}> <option>GET</option> <option>POST</option> <option>PATCH</option> <option>DELETE</option> </select> </label>{" "} <label> Path <input value={path} onChange={(event) => setPath(event.target.value)} /> </label> <p> <label> Idempotency-Key{" "} <input value={key} onChange={(event) => setKey(event.target.value)} /> </label> </p> <p> <label> If-Match{" "} <input value={ifMatch} onChange={(event) => setIfMatch(event.target.value)} /> </label> </p> <p> <label> Body{" "} <input value={body} onChange={(event) => setBody(event.target.value)} /> </label> </p> <button onClick={send}>Send request</button> <p role="status">{result}</p> </section> ); } import ApiConsole from "./ApiConsole.jsx"; export const metadata = { title: "API console" }; export default function Page() { return ( <main> <h1>API console</h1> <p>Send requests to this app's route handlers as the fixed Ada actor.</p> <ApiConsole /> </main> ); } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } "use server"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { revalidatePath } from "next/cache"; export async function reviewBatch(previous, form) { const source = form.get("edits"); let input; try { input = JSON.parse(typeof source === "string" ? source : ""); } catch { return { message: "Enter a JSON array of edits.", ok: false }; } const result = repository.applyBatch(currentActor(), input); if (!result.ok) return { message: `No edits saved: ${result.code}. Refresh to get current versions.`, ok: false, }; revalidatePath("/"); for (const item of result.items) revalidatePath(`/items/${item.id}`); return { message: `Saved ${result.items.length} edits together.`, ok: true }; } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ReviewForm from "./ReviewForm.jsx"; export const dynamic = "force-dynamic"; export default function Reviews() { return ( <main> <h1>Review a batch</h1> <p> Edit titles in the JSON below. Every id must occur once; each version must still match. A rejected edit saves none of the batch. Refresh this page after saving to load current versions. </p> <ReviewForm items={repository.list(currentActor()).slice(0, 20)} /> </main> ); } "use client"; import { useActionState } from "react"; import { reviewBatch } from "./actions.js"; export default function ReviewForm({ items }) { const [state, action, pending] = useActionState(reviewBatch, { message: "", ok: false, }); return ( <form action={action}> <label htmlFor="review-edits">Review batch</label> <textarea id="review-edits" name="edits" rows={10} cols={45} defaultValue={JSON.stringify(items, null, 2)} aria-describedby="review-result" /> <button disabled={pending}> {pending ? "Saving…" : "Save entire batch"} </button> <p id="review-result" role="status"> {state.message} </p> </form> ); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; // GET /api/items?after=2&limit=2: a keyset page of the caller's items. export async function GET(request) { const requestId = newRequestId(); const params = new URL(request.url).searchParams; const limit = params.has("limit") ? Number(params.get("limit")) : 10; if (!Number.isInteger(limit) || limit < 1 || limit > 50) return errorResponse("invalid_limit", requestId); const after = params.has("after") ? Number(params.get("after")) : 0; if (!Number.isInteger(after) || after < 0) return errorResponse("invalid_cursor", requestId); return Response.json(repository.page(currentActor(), { after, limit }), { headers: { "Cache-Control": "private, no-store" }, }); } // POST /api/items with an Idempotency-Key header: a retry with the same key // and title returns the first result instead of saving twice. export async function POST(request) { const requestId = newRequestId(); const key = request.headers.get("Idempotency-Key"); if (!key) return errorResponse("missing_key", requestId); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.createOnce(currentActor(), key, body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json( { item: result.item, replayed: Boolean(result.replayed) }, { status: result.replayed ? 200 : 201 }, ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; export async function PATCH(request) { const requestId = newRequestId(); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.applyBatch(currentActor(), body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result, { headers: { "Cache-Control": "private, no-store" }, }); } 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"; import { errorResponse, newRequestId, readJson } from "@/lib/http.js"; // A strong tag built from the version: the representation changes exactly // when the version does. const etag = (item) => `"v${item.version}"`; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) return errorResponse("not_found", newRequestId()); return Response.json(item, { headers: { "Cache-Control": "private, no-store", ETag: etag(item) }, }); } // If-Match wins when present. A body version still works, so clients written // before this change keep working: an additive change, not a breaking one. function precondition(request, input) { const tag = request.headers.get("If-Match"); if (tag !== null) { const match = /^"v(\d+)"$/.exec(tag); return match ? { ok: true, version: Number(match[1]), viaTag: true } : { ok: false, code: "precondition_failed" }; } if (typeof input === "object" && input !== null && "version" in input) { return Number.isInteger(input.version) && input.version >= 1 ? { ok: true, version: input.version, viaTag: false } : { ok: false, code: "invalid_version" }; } return { ok: false, code: "precondition_required" }; } export async function PATCH(request, { params }) { const requestId = newRequestId(); const { id } = await params; const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const expected = precondition(request, body.value); if (!expected.ok) return errorResponse(expected.code, requestId); const result = repository.edit(currentActor(), Number(id), expected.version, body.value); if (!result.ok) { const code = result.code === "conflict" && expected.viaTag ? "precondition_failed" : result.code; return errorResponse(code, requestId); } return Response.json(result, { headers: { ETag: etag(result.item) } }); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); if (!result.ok) return errorResponse(result.code, newRequestId()); return Response.json(result); } 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, }, ]; export function validateBatch(input) { if (!Array.isArray(input) || input.length < 1 || input.length > 20) return { ok: false, code: "invalid_batch" }; const ids = new Set(); const edits = []; for (const edit of input) { if ( !edit || !Number.isSafeInteger(edit.id) || edit.id < 1 || !Number.isSafeInteger(edit.version) || edit.version < 1 || ids.has(edit.id) ) return { ok: false, code: "invalid_batch" }; const valid = validateDraft(edit); if (!valid.ok) return valid; ids.add(edit.id); edits.push({ id: edit.id, version: edit.version, title: valid.title }); } return { ok: true, edits }; } // The service's public error vocabulary (Day 3). Clients branch on `code` // and must treat an unknown code by its status class. const STATUS = new Map( Object.entries({ invalid_json: 400, invalid_title: 400, invalid_batch: 400, invalid_version: 400, invalid_limit: 400, invalid_cursor: 400, missing_key: 400, unauthenticated: 401, not_found: 404, conflict: 409, key_reused: 422, precondition_failed: 412, precondition_required: 428, }), ); export function newRequestId() { const bytes = crypto.getRandomValues(new Uint8Array(6)); return "req_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } // Known codes keep their status; anything else is a generic 500. Only the // code and the request id reach the caller; details go to the server log. export function errorResponse(code, requestId, detail) { const status = STATUS.get(code) ?? 500; const publicCode = status === 500 ? "internal_error" : code; console.log(`${requestId} ${publicCode}${detail ? `: ${detail}` : ""}`); return Response.json( { code: publicCode, requestId }, { status, headers: { "Cache-Control": "private, no-store" } }, ); } export async function readJson(request) { try { return { ok: true, value: await request.json() }; } catch { return { ok: false, code: "invalid_json" }; } } import { validateDraft, validateBatch, 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; // Idempotency receipts (Day 2): one per actor and key, with the payload // they were for. In SQLite this is a table written in the same transaction. const receipts = new Map(); return { list(actor, q = "") { return rows .filter( (row) => canWrite(actor, row) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, // Keyset pages (Day 3): rows after the cursor, one extra to learn whether // another page exists. page(actor, { after = 0, limit = 10 } = {}) { const window = rows .filter((row) => canWrite(actor, row) && row.id > after) .toSorted((a, b) => a.id - b.id) .slice(0, limit + 1); const items = window.slice(0, limit).map(publicItem); return { items, nextCursor: window.length > limit ? items.at(-1).id : null }; }, createOnce(actor, key, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const receiptKey = JSON.stringify([actor.tenantId, actor.id, key]); const fingerprint = JSON.stringify(input?.title ?? null); const receipt = receipts.get(receiptKey); if (receipt) { if (receipt.fingerprint !== fingerprint) return { ok: false, code: "key_reused" }; return { ...receipt.result, replayed: true }; } const result = this.create(actor, input); // Only a successful create is remembered; an invalid draft may be // corrected and sent again with the same key. if (result.ok) receipts.set(receiptKey, { fingerprint, result }); return result; }, 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) }; }, applyBatch(actor, input) { const valid = validateBatch(input); if (!valid.ok) return valid; const draft = rows.map((row) => ({ ...row })); const items = []; for (const edit of valid.edits) { const row = draft.find((row) => row.id === edit.id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== edit.version) return { ok: false, code: "conflict" }; row.title = edit.title; row.version++; items.push(publicItem(row)); } rows = draft; return { ok: true, items }; }, 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 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"; const pager = make(); const first = pager.page(ada, { limit: 1 }); pager.remove(ada, first.items[0].id); const second = pager.page(ada, { after: first.nextCursor, limit: 1 }); const paging = second.items[0]?.id === 2 && second.nextCursor === null; const once = make(); once.createOnce(ada, "k1", { title: "Retry me" }); const replay = once.createOnce(ada, "k1", { title: "Retry me" }); const idempotent = replay.replayed === true && once.list(ada).filter((row) => row.title === "Retry me").length === 1; return [ { name: "Tenant isolation", pass: tenant }, { name: "Deletion permission", pass: deletion }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, { name: "Cursor page survives a delete", pass: paging }, { name: "Retried create saves once", pass: idempotent }, ]; }
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.
JavaScript
const etag = (item) => `"v${item.version}"`;

function precondition(request, input) {
  const tag = request.headers.get("If-Match");
  if (tag !== null) {
    const match = /^"v(\d+)"$/.exec(tag);
    return match
      ? { ok: true, version: Number(match[1]), viaTag: true }
      : { ok: false, code: "precondition_failed" };
  }
  if (typeof input === "object" && input !== null && "version" in input) {
    return Number.isInteger(input.version) && input.version >= 1
      ? { ok: true, version: input.version, viaTag: false }
      : { ok: false, code: "invalid_version" };
  }
  return { ok: false, code: "precondition_required" };
}

PATCH passes expected.version to repository.edit. When the repository answers conflict and the precondition came from the header, the handler reports precondition_failed instead, because that's what the header's contract promises; a body version keeps conflict. A success sends ETag: etag(result.item), so the client can chain the next edit without a GET. lib/http.js gains precondition_failed: 412 and precondition_required: 428.

The regular expression is the whole tag parser: anything that isn't exactly a quoted v and digits, including a weak tag or a list of tags, fails the precondition rather than being guessed at. A different shape that keeps the five decisions is just as right.

Going further

  • Retire the body version. Once logs show no client sends version in a body, requiring If-Match is safe. Until then it's a breaking change; a versioned path such as /api/v2/items lets both exist side by side.
  • Conditional GET. A client can send If-None-Match: "v2"; when the item is still at version 2, answer 304 Not Modified with no body.
  • The SQLite project. The same precondition function fits its item handler, because edit already puts the version in its UPDATE … WHERE clause.

Was this article helpful?

Your response is saved on this device.