A client's code branches on the status before it reads the body:
response.ok is true for any 2xx status. So an edit endpoint has to say
clearly which of these happened:
Outcome
Status
Body
No such record, or it belongs to someone else
404
code: "not_found"
The record changed since the client read it
409
code: "stale_version" and the current version
Saved
200
the new version
Two rules in that table are new.
Someone else's record is a 404, not a 403. Answering "forbidden" confirms
that item 2 exists. Treating "not yours" exactly like "not there" means a
reader can't probe for other people's ids. The lookup is scoped to the
owner.
A stale edit is a 409. Each record has a version that goes up on every
save. The edit form sends the version it was showing. If the stored version is
different, someone else saved in between, and blindly saving would erase their
change: a lost update. Answering 409 with the current version lets the
client show the newer data and ask the reader to try again.
Read, predict, run
lib/contract.js makes the decision. It knows nothing about HTTP objects; it
returns a status and a body:
JavaScript
export function run({ actor, record, expectedVersion }) { // Someone else's record is reported as missing, so its existence doesn't leak. if (!record || record.ownerId !== actor) return { status: 404, body: { code: "not_found" } }; if (record.version !== expectedVersion) return { status: 409, body: { code: "stale_version", currentVersion: record.version }, }; return { status: 200, body: { ok: true, version: record.version + 1 } };}
The route handler app/api/items/[id]/route.js loads the record, asks run,
saves only on success, and passes the status as the second argument to
Response.json. A status field inside the JSON alone would still go out as
200:
JavaScript
const record = await getRecord(id);const result = run({ actor, record, expectedVersion: body?.version });if (result.status === 200) await saveTitle(id, String(body.title ?? record.title));// The second argument sets the real HTTP status.return Response.json(result.body, { status: result.status });
The lab is signed in as Ada. Item 1 is hers at version 1; item 2 is Grace's.
Predict what Send PATCH shows when you send the starting body to
/api/items/1twice, then to /api/items/2.
Status and Body Must AgreeNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import PatchProbe from "./PatchProbe.jsx";
export default function Page() {
return (
<main>
<h1>Status and Body Must Agree</h1>
<PatchProbe />
<Cases />
</main>
);
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useState } from "react";
export default function PatchProbe() {
const [path, setPath] = useState("/api/items/1");
const [body, setBody] = useState('{"title": "Routing basics", "version": 1}');
const [result, setResult] = useState("");
async function send() {
const response = await fetch(path, { method: "PATCH", body });
setResult(`${response.status} ok=${response.ok} ${JSON.stringify(await response.json())}`);
}
return (
<section>
<label>
Path <input value={path} onChange={(event) => setPath(event.target.value)} />
</label>
<label>
Body <input value={body} size={44} onChange={(event) => setBody(event.target.value)} />
</label>{" "}
<button onClick={send}>Send PATCH</button>
<p role="status">{result}</p>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
import { run } from "@/lib/contract.js";
import { getRecord, saveTitle } from "@/lib/store.js";
// This lab's signed-in reader. A real app reads it from the session.
const actor = "ada";
export async function PATCH(request, { params }) {
const { id } = await params;
let body;
try {
body = await request.json();
} catch {
return Response.json({ code: "invalid_json" }, { status: 400 });
}
const record = await getRecord(id);
const result = run({ actor, record, expectedVersion: body?.version });
if (result.status === 200) await saveTitle(id, String(body.title ?? record.title));
// The second argument sets the real HTTP status.
return Response.json(result.body, { status: result.status });
}
export function run({ actor, record, expectedVersion }) {
// Someone else's record is reported as missing, so its existence doesn't leak.
if (!record || record.ownerId !== actor)
return { status: 404, body: { code: "not_found" } };
if (record.version !== expectedVersion)
return {
status: 409,
body: { code: "stale_version", currentVersion: record.version },
};
return { status: 200, body: { ok: true, version: record.version + 1 } };
}
export const examples = [
[
{ actor: "ada", record: null, expectedVersion: 1 },
{ status: 404, body: { code: "not_found" } },
],
[
{ actor: "grace", record: { ownerId: "ada", version: 1 }, expectedVersion: 1 },
{ status: 404, body: { code: "not_found" } },
],
[
{ actor: "ada", record: { ownerId: "ada", version: 2 }, expectedVersion: 1 },
{ status: 409, body: { code: "stale_version", currentVersion: 2 } },
],
[
{ actor: "ada", record: { ownerId: "ada", version: 1 }, expectedVersion: 1 },
{ status: 200, body: { ok: true, version: 2 } },
],
];
// Pretend table in server memory. Every successful edit bumps the version.
const records = {
1: { id: "1", ownerId: "ada", title: "Routing", version: 1 },
2: { id: "2", ownerId: "grace", title: "Grace's draft", version: 1 },
};
export async function getRecord(id) {
const record = records[id];
return record ? { ...record } : null;
}
export async function saveTitle(id, title) {
records[id].title = title;
records[id].version += 1;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
First send: 200 ok=true {"ok":true,"version":2}. The save bumped the
version.
Second send, still claiming version 1: 409 ok=false {"code":"stale_version","currentVersion":2}.
The same body is now out of date, exactly as if another tab had saved first.
/api/items/2: 404 ok=false {"code":"not_found"}, the same answer as
/api/items/9, which doesn't exist.
The failure to avoid
Answering an error with status 200 makes response.ok true, so the client
treats a failed save as a success. And a conflict is not a 500: retrying the
same request won't fix it, while a 500 invites exactly that.
Exercise
A request without a version
A form that forgot its hidden version field sends no expectedVersion. Reject
that with 400 and code: "missing_version", before looking at the record,
so the answer is the same whether or not the record exists.
Edit lib/contract.js, and add the acceptance cases to examples:
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
A request with no version is malformed: the client has a bug. That's a 400,
and it's about the request alone, so it's decided before the database is
consulted. The order of the checks is the precedence of the answers.
Hint 2: a first step
Add a check at the very top of run. What should it test: undefined, any
non-number? Run the original four cases afterwards: none of them should change.
Without this check, a missing version reaches record.version !== undefined
and answers 409, telling the client its data is stale when the real problem is
its own request. Checking typeof … !== "number" also rejects "1", a version
sent as a string, which !== would otherwise call stale forever. Placing it
first keeps it from leaking anything: Grace gets the same 400 whether or not a
record exists.
Explain it without the code
Two tabs open the same item at version 3. Tab A saves; then tab B saves. Write
what each tab receives, with the status and the versions involved, and what
tab B's reader should see next.
Going further
PATCH with a version in the body is one way to do this. HTTP also has a
standard header for it, If-Match, with an ETag from the earlier read; the
advanced course uses that. See the
route handler reference
for reading headers and setting statuses. The preview runs code-playpad's
Next.js simulation.
Completion is saved in this browser only. It does not measure mastery.