Explain it simply
Route Handlers in plain language
A Route Handler is a reception desk for programs outside your app: a mobile app, a payment service sending webhooks, a partner company's script. A page answers people with HTML; a Route Handler answers programs with JSON, or anything else.
Your own Server Components do not need to walk round to the reception desk. They already run on the server, so they can call the data layer directly and skip the HTTP round trip entirely.
Problem → Why → Solution
The problem: an endpoint that accepts anything
The mobile team asks for a /api/notes endpoint. The first version parses the body, pushes it into an array and always returns { ok: true }. A body that is not JSON makes request.json() throw, which becomes a 500. { "title": 42 } is accepted and crashes later when the list is displayed. Every response is 200, so the app cannot tell what went wrong. The module-level array works locally, but in serverless production each instance has its own copy and data vanishes.
const notes: unknown[] = []; // "database"
export async function POST(request: Request) {
const body = await request.json(); // throws on bad JSON -> 500
notes.push(body); // stores whatever the caller sent
return Response.json({ ok: true }); // always 200, even for garbage
}An endpoint is a contract
Programs understand your endpoint through status codes and the JSON shape. If the body is not checked, garbage reaches the database; if the status is wrong, the client cannot decide whether to retry or show an error. Validating input and reporting the outcome with an honest status is what makes an endpoint trustworthy.
Core concept: file path, HTTP method and a Web Response
You create a Route Handler with a route.ts file inside the app folder: app/api/notes/route.ts becomes the /api/notes URL. In it you export async functions named after HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. Calling a method you did not export gets an automatic 405 Method Not Allowed. A single segment cannot hold both page.tsx and route.ts, because it must be clear who answers that URL.
A handler receives a standard Web Request and returns a Response, the same API as fetch in the browser; NextRequest and NextResponse extend them with helpers such as cookies and nextUrl. Read the body with request.json(), request.formData() or request.text(), remembering that request.json() throws on invalid JSON. Get the query string from new URL(request.url).searchParams. In a dynamic segment such as app/api/notes/[id]/route.ts, the second argument { params } carries the id, and since Next.js 15 params is a Promise you await.
| Status | When |
|---|---|
| 200 OK | a read or update succeeded |
| 201 Created | a new resource was created and is returned |
| 204 No Content | success with no body, such as a delete |
| 400 / 401 / 403 | bad input, not signed in, not allowed |
| 404 Not Found | no resource with that id |
On a serverless platform any request may run on a fresh instance, so module-level variables and local files are not storage; keep durable data in a database. Caching also differs by version: Next.js 14 cached GET handlers that used no request data by default, and Next.js 15 stopped doing so, so check the docs for your version.
- Folder path becomes the URL
- Exported GET/POST picks the method
- Parse and validate the Request
- Do the work via the data layer
- Return a Response, honest status
A handler should be a thin layer that translates HTTP; the business logic belongs in the data layer.
General pattern
// app/api/<resource>/route.ts
export async function GET(request: Request) {
return Response.json(data, { status: 200 });
}
// app/api/<resource>/[id]/route.ts
type Ctx = { params: Promise<{ id: string }> };
export async function DELETE(request: Request, { params }: Ctx) {
const { id } = await params;
return new Response(null, { status: 204 });
}Export a function named after the method and return a Response; dynamic segment values come from the awaited params on the second argument.
Worked example: a notes list and create endpoint
Watch how the handler treats bad input. A body that is not valid JSON would otherwise surface as a 500, and a null body could crash the handler, so the code answers 400 through try/catch, checks the title with a zod schema, and bounds the limit taken from the query string.
// app/api/notes/route.ts
import { NextResponse } from "next/server";
import { z } from "zod";
import { createNote, listNotes } from "@/lib/data/notes";
const NoteInput = z.object({
title: z.string().trim().min(3).max(120),
});
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const requested = Number(searchParams.get("limit") ?? "20");
const limit = Number.isInteger(requested) && requested > 0
? Math.min(requested, 100)
: 20;
const notes = await listNotes({ limit });
return NextResponse.json(notes);
}
export async function POST(request: Request) {
// a real app checks the caller's session or API token here (lesson 20)
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Body must be valid JSON" }, { status: 400 });
}
const parsed = NoteInput.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid title" }, { status: 400 });
}
const note = await createNote({ title: parsed.data.title });
return NextResponse.json(note, { status: 201 });
}Code breakdown
- Schema for the body
title: z.string().trim().min(3).max(120),A zod object strips unknown keys by default, so a caller who adds a field such as ownerId does not get it through.
- Bounded query value
? Math.min(requested, 100)It caps the limit at 100 so a request like ?limit=1000000 cannot pull the whole table, and invalid values become 20.
- Bad JSON is a 400
return NextResponse.json({ error: "Body must be valid JSON" }, { status: 400 });A client mistake is reported as 400, not disguised as a 500 server error.
- safeParse, not parse
const parsed = NoteInput.safeParse(body);safeParse returns an object with a success flag instead of throwing, which makes turning a failure into a 400 straightforward.
- 201 for a new resource
return NextResponse.json(note, { status: 201 });The created note goes back with 201 Created, so the client can use its id straight away.
GET /api/notes?limit=5 returns 200 with a JSON array of at most 5 notes. POST with {"title":"Hello Next"} returns 201 with the new note, while {"title":"Hi"} or a body that is not JSON gets 400 with an error message.When you actually need a Route Handler
The App Router offers three ways to read and change data, and picking the right one simplifies code noticeably. A Server Component that fetches your own Route Handler makes the server call itself over HTTP, adding a network hop for nothing.
| Need | Use |
|---|---|
| Read data for your own page | Server Component + data layer |
| Submit a form in your own UI | Server Action |
| Mobile app, partner, webhook | Route Handler |
| File download, RSS, OAuth callback | Route Handler |
In real projects
In real projects
In production apps most Route Handlers sit where the app meets the outside world. Each one validates the body, authenticates the caller and then calls the data layer.
- Payment webhooks: when a service such as Stripe sends an event, the handler verifies the signature against the raw body (request.text()) before updating the order.
- Mobile APIs: iOS and Android apps call /api/notes with a Bearer token, while the web app uses the same data layer directly from Server Components.
- Files and feeds: CSV exports, sitemaps or RSS feeds are returned as a Response with the right Content-Type header.
- OAuth callbacks: the handler receives the URL the login provider redirects back to with a code, and sets the session cookie.
Common mistakes
Common Route Handler mistakes
Writing the body to the database unvalidated
TypeScript types do not check JSON arriving from the network at runtime. Parse it with a schema and keep only the fields you need, or a caller can set role or ownerId themselves.
Using memory or a local file as storage
It works on the dev server, but serverless instances share no memory and their file system may be temporary or read-only. Keep data in a database or object storage.
Answering every error with 200 or 500
Clients decide whether to retry or show a form error from the status code. Use 400 for bad input, 404 for something missing, and keep 500 for real server failures.
Fetching your own Route Handler from a Server Component
It can fail at build time because no server is running yet, and every request pays for an extra HTTP hop. Call the data function directly.
Best practices
Best practices
- Keep handlers thin: parse, authenticate, call the data layer, return a Response.
- Return errors in one shape such as { error: string }, and never expose a stack trace.
- Add rate limiting and body size limits to public endpoints.
- Handlers are functions from Request to Response, so test them by calling them with new Request(...).
Mini challenge
Mini challenge: handlers for /api/notes/[id]
Write GET, PATCH and DELETE handlers for app/api/notes/[id]/route.ts, then call them the way Next.js does, by building a Request object and a params Promise yourself. Use an in-memory Map for this exercise only.
- All three handlers return 404 with { error } when the id does not exist
- PATCH validates title (trimmed, 3-120 characters) and returns 400 when invalid
- A successful DELETE returns 204 with no body
- Print the method, status and body of every call
import { z } from "zod";
type Note = { id: string; title: string };
type Ctx = { params: Promise<{ id: string }> };
// In-memory store for this exercise only.
const store = new Map<string, Note>(/* TODO: two sample notes */);
const PatchInput = z.object({ /* TODO: title rules */ });
export async function GET(_request: Request, { params }: Ctx) {
// TODO: 200 with the note, or 404
}
export async function PATCH(request: Request, { params }: Ctx) {
// TODO: 404 if missing, 400 if the body is invalid, 200 with the updated note
}
export async function DELETE(_request: Request, { params }: Ctx) {
// TODO: 404 if missing, otherwise 204 with no body
}
// TODO: build Requests, call the handlers and print status + bodyExpected: GET 1 gives 200, PATCH 1 gives 200 with the trimmed title, PATCH 2 ("No") gives 400, the first DELETE 2 gives 204, and the second DELETE 2 and GET 99 give 404.
Show hint
request.json().catch(() => null) turns an invalid body into null, which the schema then rejects as a 400. Map.prototype.delete returns true when it removed something.
Show solution
import { z } from "zod";
type Note = { id: string; title: string };
type Ctx = { params: Promise<{ id: string }> };
type Handler = (request: Request, ctx: Ctx) => Promise<Response>;
// In-memory store for this exercise only; a real app uses the data layer.
const store = new Map<string, Note>([
["1", { id: "1", title: "Learn route handlers" }],
["2", { id: "2", title: "Write tests" }],
]);
const PatchInput = z.object({ title: z.string().trim().min(3).max(120) });
const notFound = () => Response.json({ error: "Note not found" }, { status: 404 });
export async function GET(_request: Request, { params }: Ctx) {
const note = store.get((await params).id);
return note ? Response.json(note) : notFound();
}
export async function PATCH(request: Request, { params }: Ctx) {
const { id } = await params;
const note = store.get(id);
if (!note) return notFound();
const parsed = PatchInput.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return Response.json({ error: "Invalid title" }, { status: 400 });
}
const updated = { ...note, title: parsed.data.title };
store.set(id, updated);
return Response.json(updated);
}
export async function DELETE(_request: Request, { params }: Ctx) {
if (!store.delete((await params).id)) return notFound();
return new Response(null, { status: 204 });
}
// What Next.js does for you: build the Request and pass the route params.
async function call(handler: Handler, method: string, id: string, body?: unknown) {
const request = new Request(`http://localhost/api/notes/${id}`, {
method,
headers: { "content-type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const response = await handler(request, { params: Promise.resolve({ id }) });
const text = await response.text();
console.log(`${method} /api/notes/${id} -> ${response.status} ${text}`);
}
async function main() {
await call(GET, "GET", "1");
await call(PATCH, "PATCH", "1", { title: " Ship it " });
await call(PATCH, "PATCH", "2", { title: "No" });
await call(DELETE, "DELETE", "2");
await call(DELETE, "DELETE", "2");
await call(GET, "GET", "99");
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Export functions named GET, POST and so on from app/api/<name>/route.ts; they take a Web Request and return a Response.
- Treat the body as untrusted: catch JSON parse errors, validate with a schema and answer 400 clearly.
- Since Next.js 15, dynamic segment params are a Promise, and methods you do not export get a 405.
- Use Route Handlers for outside clients; your own pages use the data layer and Server Actions directly.
Next.js — Route Handlers — Next.js
Next.js — Route Handlers — Next.js