A valid payload can still be too expensive to process. Imports need limits on rows, field sizes and accepted operations as well as correct JSON syntax.
Read, predict, run
The model validates an array and checks its row count before inspecting each row. It returns a stable error code instead of throwing a property-access exception. A real endpoint must also limit bytes before or while reading the body:
JavaScript
export function run(rows) { if (!Array.isArray(rows)) return "invalid_shape"; if (rows.length > 100) return "too_many_rows"; if ( rows.some( (row) => !row || typeof row.title !== "string" || !row.title.trim(), ) ) return "invalid_row"; return "accepted";}
Before pressing Run, predict what run returns for null and [{"title": "Review"}], from the
code above. Write your answers down first: after Run, the case table shows the
expected values beside the actual ones.
Bound Work Before an Import StartsNext.js · 7 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
export default function Page() {
return (
<main>
<h1>Bound Work Before an Import Starts</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(rows) {
if (!Array.isArray(rows)) return "invalid_shape";
if (rows.length > 100) return "too_many_rows";
if (
rows.some(
(row) => !row || typeof row.title !== "string" || !row.title.trim(),
)
)
return "invalid_row";
return "accepted";
}
export const examples = [
[null, "invalid_shape"],
[[{ title: "Review" }], "accepted"],
];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
Input null → "invalid_shape".
Input [{"title": "Review"}] → "accepted".
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 rows after creating records is too late. Buffering an unlimited request before checking its length can exhaust memory even when the later validation is correct.
Compare checking and creating rows in one loop with checking everything first.
Trace 90 rows where row 60 has an empty title: the one-loop version has created
59 records before it notices; this version answers invalid_row having created
none.
Exercise
Extend the contract
Reject a title over 80 trimmed characters as invalid_row. Keep the row-count error precedence.
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": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}] must return "invalid_row".
Your working spaceNext.js · 7 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
export default function Page() {
return (
<main>
<h1>Bound Work Before an Import Starts</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(rows) {
if (!Array.isArray(rows)) return "invalid_shape";
if (rows.length > 100) return "too_many_rows";
if (
rows.some(
(row) => !row || typeof row.title !== "string" || !row.title.trim(),
)
)
return "invalid_row";
return "accepted";
}
export const examples = [
[null, "invalid_shape"],
[[{ title: "Review" }], "accepted"],
];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Field limits are per-row rules, so they belong in the same per-row check as
the type check. The order of the whole function still decides which error a
caller sees first.
Hint 2: a first step
The per-row predicate is the place for field limits, after the string type check.
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.
JavaScript
export function run(rows) { if (!Array.isArray(rows)) return "invalid_shape"; if (rows.length > 100) return "too_many_rows"; if ( rows.some( (row) => !row || typeof row.title !== "string" || !row.title.trim() || row.title.trim().length > 80, ) ) return "invalid_row"; return "accepted";}
The length check comes after typeof row.title !== "string", so .trim()
only runs on strings, and after the row-count check, so a 200-row import still
gets too_many_rows first. Measuring the trimmed title matches what would be
stored. Returning the failing row's index as well would help callers fix their
file, at the cost of a richer contract.
Explain it without the code
Write three limits this endpoint needs, and which one only the transport can
enforce, before the body has been read.
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.