Create Next REST Framework API
Implement Next.js APIs with next-rest-framework using schema-driven request validation, typed responses, and OpenAPI generation.
Workflow
- Pick router surface first: App Router (
docsRoute,route,routeOperation,rpcRoute) or Pages Router (docsApiRoute,apiRoute,apiRouteOperation,rpcApiRoute). - Load only the reference file needed for the task:
references/app-router.mdreferences/pages-router.mdreferences/forms-and-typed-responses.mdreferences/openapi-and-cli.md
- Define input and output schemas before handler logic.
- Add middleware only for cross-cutting concerns (auth, tracing, feature flags), and pass derived context through middleware return values.
- Wire docs and CLI (
generateandvalidate) so OpenAPI stays current in CI.
Router Selection
- Use App Router handlers when files live under
src/app/**/route.ts. - Use Pages Router handlers when files live under
src/pages/api/**/*.ts. - Keep RPC routes at:
- App Router:
.../[operationId]/route.ts - Pages Router:
.../[operationId].ts
Guardrails
- Use
zod-form-dataschemas forapplication/x-www-form-urlencodedandmultipart/form-datarequest bodies. - Use plain Zod schemas for JSON request/response bodies.
- For multipart file schemas that cannot be represented correctly from Zod, provide explicit
bodySchemaJSON Schema overrides. - In App Router, return
TypedNextResponsewhen you want compile-time enforcement of declared status/content-type outputs. - In Pages Router multipart handlers, disable Next body parser (
export const config = { api: { bodyParser: false } }). - Use
openApiPathat route level andopenApiOperationat operation level for targeted OpenAPI overrides.
Done Criteria
- Endpoints compile with inferred input/output types.
- Error and success responses match declared
outputs. - Docs endpoint renders and includes intended paths (
allowedPaths/deniedPaths). next-rest-framework generateandnext-rest-framework validatepass for the intended docs config path.