Quick answer
A typed handler must validate the HTTP boundary at runtime. Parse request data as unknown, reject malformed or invalid input, verify identity and permission for the operation, and return a deliberate response contract. TypeScript checks application code; annotating request.json as a domain type does not prove the incoming JSON conforms. Keep parsing, authorization, domain work, and HTTP projection easy to distinguish.
Practical implementation steps
1. Define inputs by their source
Path parameters, query strings, headers, and body fields are separate inputs. Check their intended formats and limits, including absent values and repeated query parameters. Next.js 16 route context exposes params as a promise, so await dynamic parameters. Decide whether the route expects JSON and apply hosting or application body limits; checking Content-Length alone cannot constrain a chunked or dishonest request.
2. Separate syntax from domain validation
A JSON parse failure is different from a valid object containing an invalid name or amount. Return a consistent 400 or other documented client-error response without echoing sensitive payloads. A runtime schema or explicit guard should reject wrong types and enforce relevant ranges. Avoid permissive coercion unless the contract deliberately allows it: string "false" and Boolean(false) are not interchangeable parsing rules.
3. Authorize the operation independently of parsing
A valid record ID is not permission to access it. Use the verified server session and tenant scope, then call the authorized domain operation. Keep HTTP status decisions explicit: unauthenticated, denied, missing, conflict, and upstream failure do not all mean success with an empty object. A browser-facing route also needs an origin and request-protection policy appropriate to its authentication model.
Implementation example
This standalone demonstration validates a public normalization endpoint and has no side effect. It rejects malformed JSON and returns a typed public projection. A production write route must add authentication, permission, storage limits, rate policy, and the application’s domain operation. The guard deliberately avoids treating a cast as evidence of valid input.
// app/api/normalize-name/route.ts
type Input = { name: string };
type Output = { name: string };
function isInput(value: unknown): value is Input {
return typeof value === "object" && value !== null &&
"name" in value && typeof value.name === "string" &&
value.name.trim().length >= 2 && value.name.trim().length <= 80;
}
export async function POST(request: Request) {
let value: unknown;
try { value = await request.json(); }
catch { return Response.json({ error: "Malformed JSON" }, { status: 400 }); }
if (!isInput(value)) {
return Response.json({ error: "Invalid name" }, { status: 400 });
}
const result: Output = { name: value.name.trim() };
return Response.json(result);
}
Tradeoffs and alternatives
A schema library can provide reusable validation and field errors; a small explicit guard can be clearer for a tiny contract. Generated client types help callers compile but still do not validate runtime requests or upstream responses. A Route Handler is useful for browser or external HTTP consumers. A Server Component that already runs on the server can call the same underlying reader directly instead of making a self-HTTP request.
Common mistakes
Avoid unchecked request-body casts, accepting identity from input, returning full database records, and converting every exception to a 200 response. Do not place page.tsx and route.ts at the same route segment. Do not assume a GET handler is cached merely because it reads public data; cache behavior depends on explicit configuration and the selected Next.js model. Never log tokens or entire submitted private payloads as routine diagnostics.
Production checklist
- Every external input validates at runtime.
- Body limits and expected content format are defined.
- Protected operations verify session, record, and tenant access.
- HTTP errors match documented outcomes.
- Responses and logs expose only intended fields.
FAQ
Does a TypeScript response type validate the caller?
No. It checks how application code constructs the response. Validate request input and verify identity independently.
Should all handlers use NextRequest?
Use the standard Request when its APIs suffice. NextRequest adds framework conveniences such as nextUrl and cookies; choosing it does not change trust or validation requirements.
Next step
Document one route’s input, authorization, success, and failure contract. Verify malformed bodies, denied records, and upstream failure before sharing its types with clients. Reuse the authorized domain function while keeping HTTP-specific decisions at the route boundary.
Primary sources
Related guides and examples
Need this implemented in a real product?
React and Next.js applications with deliberate rendering, reliable data flows, and a clear path to production.