A Route Handler is an HTTP boundary, so it should make request validation, authorization, and response semantics explicit. Framework defaults evolve; check the documentation for the Next.js version installed in the application before relying on caching or runtime behavior.
Validate before doing work
Parse the request body with a runtime schema and return a clear client error for invalid input. TypeScript interfaces disappear at runtime and cannot validate JSON. Set limits on body size and accepted fields. For resource operations, load the resource and check the current user’s access on the server; a client-side hidden button is not authorization.
Return stable status codes and a consistent error shape. Avoid leaking stack traces, database messages, or secrets. Include a request identifier for support. For mutations, consider idempotency where clients or intermediaries may retry after a timeout. Use the project’s established CSRF protection for cookie-authenticated requests.
Decide caching per handler
Public, immutable responses can often be cached safely; user-specific or frequently changing responses need different treatment. Set and test cache headers deliberately, and verify whether the route is rendered dynamically under the current framework configuration. Never let a shared cache store a response containing one user’s private data.
Test direct HTTP requests, malformed JSON, unauthenticated and unauthorized callers, duplicate submissions, and cache behavior. Include method behavior and content type in the contract. A route is reliable when clients can distinguish success, validation failure, missing data, and temporary server failure.
Make caching part of the endpoint contract
A Next.js App Router Route Handler uses the Web Request and Response APIs and exports named HTTP methods from a route file. The current documentation describes Route Handlers as uncached by default and allows opting GET into caching. With Cache Components enabled, the documented prerendering behavior for GET depends on the data it reads. Check the configuration actually deployed before combining cache examples from different versions. Next.js Route Handlers
For a private handler, establish the session and check the resource permission before selecting the response fields. Return a suitable status for malformed input, a conflicting revision, or an unavailable dependency. Test headers and body together. For a simple health handler, a small public response can be useful without exposing server paths, connection strings or information about unrelated downstream systems.
Worked example
Place this in an App Router route.ts file. The response contains no user information; for authenticated handlers, resolve the server session and validate input before querying private data.
tsexport async function GET() { return Response.json({ status: "ok" }, { headers: { "Cache-Control": "no-store" } }); }




Community
Discussion
Loading comments…