A request body can be malformed JSON, valid null, an array or an object with the wrong field types. Parse errors and shape errors both need useful responses, without changing stored data.
Read, predict, run
The function accepts unknown data after parsing and returns a response contract. app/api/example/route.js catches parse failures before calling it. Inspect both layers: one cannot replace the other:
JavaScript
export async function POST(request) { let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } const result = await run(input); const status = typeof result?.status === "number" ? result.status : 200; return Response.json(result, { status });}
Before pressing Run, predict what run returns for null, [] and {"title": " Forms "}, from the
code above. Write your answers down first: after Run, the case table shows the
expected values beside the actual ones.
Parsing JSON Is Only the First CheckNext.js · 7 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 ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
export default function Page() {
return (
<main>
<h1>Parsing JSON Is Only the First Check</h1>
<p>
Read the input and predict the result before running. Change
lib/contract.js for the exercise.
</p>
<ApiProbe />
<Cases />
</main>
);
}
"use client";
import { useState } from "react";
export default function ApiProbe() {
const [result, setResult] = useState("");
async function load() {
try {
const response = await fetch("/api/example");
setResult(response.status + " " + JSON.stringify(await response.json()));
} catch {
setResult("Request failed");
}
}
return (
<section>
<button onClick={load}>Ask the API</button>
<p role="status">{result}</p>
</section>
);
}
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>
);
}
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, examples } from "@/lib/contract.js";
export async function GET() {
const result = await run(examples[0][0]);
const status = typeof result?.status === "number" ? result.status : 200;
return Response.json(result, { status });
}
export async function POST(request) {
let input;
try {
input = await request.json();
} catch {
return Response.json({ code: "invalid_json" }, { status: 400 });
}
const result = await run(input);
const status = typeof result?.status === "number" ? result.status : 200;
return Response.json(result, { status });
}
export function run(body) {
if (
!body ||
Array.isArray(body) ||
typeof body.title !== "string" ||
!body.title.trim()
)
return { status: 400, code: "invalid_title" };
return { status: 201, title: body.title.trim() };
}
export const examples = [
[null, { status: 400, code: "invalid_title" }],
[[], { status: 400, code: "invalid_title" }],
[{ title: " Forms " }, { status: 201, title: "Forms" }],
];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Input {"title": " Forms "} → {"status": 201, "title": "Forms"}.
The case table computes these results on the server side of the simulation.
It compares values; it does not prove a production deployment or database works.
The failure to avoid
Checking body.title before checking body can throw on null. String conversion can accept arrays or files that the application never intended to store.
Trace the body [] through both layers: does request.json() throw? Which
condition in run rejects it?
Exercise
Extend the contract
Reject titles longer than 60 characters after trimming, using the same invalid_title response.
Edit lib/contract.js, then rerun the original cases. If the requested rule
changes an earlier result, update that expected value deliberately. Keep the
other cases. Add the acceptance cases to examples so the preview checks them too.
Input {"title": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"} must return {"status": 400, "code": "invalid_title"}.
Your working spaceNext.js · 7 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 ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
export default function Page() {
return (
<main>
<h1>Parsing JSON Is Only the First Check</h1>
<p>
Read the input and predict the result before running. Change
lib/contract.js for the exercise.
</p>
<ApiProbe />
<Cases />
</main>
);
}
"use client";
import { useState } from "react";
export default function ApiProbe() {
const [result, setResult] = useState("");
async function load() {
try {
const response = await fetch("/api/example");
setResult(response.status + " " + JSON.stringify(await response.json()));
} catch {
setResult("Request failed");
}
}
return (
<section>
<button onClick={load}>Ask the API</button>
<p role="status">{result}</p>
</section>
);
}
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>
);
}
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, examples } from "@/lib/contract.js";
export async function GET() {
const result = await run(examples[0][0]);
const status = typeof result?.status === "number" ? result.status : 200;
return Response.json(result, { status });
}
export async function POST(request) {
let input;
try {
input = await request.json();
} catch {
return Response.json({ code: "invalid_json" }, { status: 400 });
}
const result = await run(input);
const status = typeof result?.status === "number" ? result.status : 200;
return Response.json(result, { status });
}
export function run(body) {
if (
!body ||
Array.isArray(body) ||
typeof body.title !== "string" ||
!body.title.trim()
)
return { status: 400, code: "invalid_title" };
return { status: 201, title: body.title.trim() };
}
export const examples = [
[null, { status: 400, code: "invalid_title" }],
[[], { status: 400, code: "invalid_title" }],
[{ title: " Forms " }, { status: 201, title: "Forms" }],
];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
The length rule is one more rule about the title's shape, so it joins the same
condition, at the point where the title is known to be a string.
Hint 2: a first step
Extend the title condition after the type check, where trim is safe.
Show one solution
Replace the exported run function and any constants shown here; keep the
examples export underneath it. Compare the result with your own approach.
The new check comes after typeof body.title !== "string", so .trim() only
runs on strings, and || stops at the first failing check. Measuring the
trimmed title matches what's saved. Reusing invalid_title keeps the response
vocabulary small; if a client needs to tell "too long" apart, that's a new code,
added deliberately.
Explain it without the code
List three request bodies that reach run and get a 400, and one that never
reaches it. Write which layer answers each.
Going further
Read the Next.js guide for the framework boundary around this rule.
The preview runs code-playpad's Next.js simulation. Real caching, hydration,
authentication and persistence require the real-server checks described on Day 7.
Completion is saved in this browser only. It does not measure mastery.