Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 13 / Topic 3 of 6

POST, a JSON body, and manual validation — no form anywhere

app/api/status/[pnr]/delay/route.ts stands in for a real railway ops system's own webhook — a delay update that a passenger's browser never triggers, pushed by somebody else's backend:

// harness/app/api/status/[pnr]/delay/route.ts
import { reportDelay } from "../../../../status/lib/pnr";

export async function POST(request: Request, context: RouteContext<"/api/status/[pnr]/delay">) {
  const { pnr } = await context.params;

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: "Request body must be valid JSON" }, { status: 400 });
  }

  const minutes = (body as { minutes?: unknown }).minutes;
  if (typeof minutes !== "number" || !Number.isFinite(minutes) || minutes < 0) {
    return Response.json({ error: "`minutes` must be a non-negative number" }, { status: 400 });
  }

  const updated = reportDelay(pnr, minutes);
  if (!updated) {
    return Response.json({ error: `No PNR record for ${pnr}` }, { status: 404 });
  }
  return Response.json({ updated: true, record: updated });
}

Run for real:

$ curl -s -X POST http://localhost:PORT/api/status/2458001234/delay \
  -H "Content-Type: application/json" -d '{"minutes": 20}'
{"updated":true,"record":{"pnr":"2458001234","train":"Karnataka Express","trainNumber":"12627","from":"Bengaluru Cantt","to":"Chennai Central","status":"Confirmed","coach":"B2","seat":"34","delayMinutes":20}}
$ curl -s -X POST http://localhost:PORT/api/status/2458001234/delay \
  -H "Content-Type: application/json" -d '{"minutes": -5}'
{"error":"`minutes` must be a non-negative number"}
$ curl -s -o /dev/null -w "status=%{http_code}\n" -X POST http://localhost:PORT/api/status/2458001234/delay \
  -H "Content-Type: application/json" -d 'not json'
status=400

There is no <form>, no useActionState, no hidden $ACTION_* field anywhere in this request — unlike Part 12's Server Actions, a Route Handler is just an HTTP endpoint with a URL, reachable by any HTTP client that knows the path and the shape of the body. The try { await request.json() } catch guard matters for exactly that reason: an external caller can send anything, including a body that isn't JSON at all, and the installed backend-for-frontend.md guide's own example uses this same try/catch-around-the-risky-call shape for a POST handler.

Done here? The practice set for Part 13 — including the solutions — is on the part page.

Search the guide