Designing RESTful Route Handlers with the Web Request API
Implement GET/POST/PATCH/DELETE handlers using the native Request and Response objects and dynamic segments.
What Route Handlers Are
In the Next.js 15 App Router, a Route Handler is a file named route.ts inside the app directory. It lets you build a REST-style API endpoint without a separate Express server.
- You export an async function named after the HTTP method:
GET,POST,PATCH,DELETE,PUT,HEAD,OPTIONS. - Each function receives a standard Web
Requestand returns a standard WebResponse. - The URL is derived from the folder path:
app/api/users/route.tsserves/api/users.
Because these are built on the platform's native Fetch API, the same mental model works on Node and Edge runtimes.
// app/api/users/route.ts
export async function GET(request: Request): Promise<Response> {
return Response.json({ users: ["Ada", "Linus"] });
}
export async function POST(request: Request): Promise<Response> {
const body = await request.json();
return Response.json({ created: body }, { status: 201 });
}Returning Responses
A handler must return a Response. Next.js gives you the native object plus a convenience helper.
Response.json(data, init)serializesdataand setsContent-Type: application/jsonautomatically.- Use the second
initargument to setstatusand customheaders. - For plain text or other payloads, construct
new Response(body, init)directly.
Picking the right status code is part of RESTful design: 200 for reads, 201 for creates, 204 for deletes with no body.
// Three idiomatic ways to respond
Response.json({ ok: true }); // 200 + JSON
Response.json({ id: 1 }, { status: 201 }); // 201 Created
new Response(null, { status: 204 }); // 204 No Content
new Response("pong", {
status: 200,
headers: { "Content-Type": "text/plain" },
});All lessons in this course
- Designing RESTful Route Handlers with the Web Request API
- Node Runtime vs Edge Runtime Tradeoffs
- Streaming Responses and ReadableStream in Handlers
- Request Validation and Typed JSON Responses with Zod