Next.js Route Handlers: Methods, Cookies, and Streaming Responses
route.ts is plain HTTP inside the App Router. Reading the body once, setting cookies two ways, opting into caching in v15, and streaming with a ReadableStream.

Quick Summary
A Route Handler is an HTTP endpoint written as a function export in app/**/route.ts. The exported name is the method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS), the first argument is a standard Request, and the return value is a standard Response or NextResponse. There is no layout, no React tree, and no automatic body type — you read the body and choose the shape.
Web standards are the API: request.json(), request.nextUrl.searchParams, Response.json(data, { status: 201 }), response.headers.set(...). cookies() from next/headers reads and writes cookies in a handler (Next.js 15 returns a Promise), and params in the second argument is a Promise too.
Caching changed in Next.js 15: a GET handler is not cached by default. Route handlers are dynamic unless you opt in with export const dynamic = "force-static" or a revalidate window. For streaming, return a ReadableStream — the runtime sends chunks as they are produced, which is how server-sent events and long-running completions are implemented.
Basic Syntax & Core Signatures
// app/api/todos/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
const limit = Number(request.nextUrl.searchParams.get("limit") ?? 20);
const status = request.nextUrl.searchParams.get("status");
const todos = await db.todo.findMany({
where: status ? { status } : undefined,
take: Math.min(limit, 100),
});
return NextResponse.json({ todos }, { headers: { "Cache-Control": "no-store" } });
}
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => null);
if (!body?.title) {
return NextResponse.json({ error: "title is required" }, { status: 400 });
}
const todo = await db.todo.create({ data: { title: String(body.title) } });
return NextResponse.json({ todo }, { status: 201 });
}// app/api/todos/[id]/route.ts — params is a Promise in Next.js 15+
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const patch = await request.json();
const todo = await db.todo.update({ where: { id }, data: patch });
return NextResponse.json(todo);
}
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
await db.todo.delete({ where: { id } });
return new Response(null, { status: 204 });
}// Cookies and streaming
import { cookies } from "next/headers";
export async function POST() {
const jar = await cookies();
jar.set("session", crypto.randomUUID(), { httpOnly: true, sameSite: "lax", path: "/" });
return NextResponse.json({ ok: true });
}
export async function GET() {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
for (const chunk of ["a", "b", "c"]) {
controller.enqueue(encoder.encode(`data: ${chunk}\n\n`));
await new Promise((r) => setTimeout(r, 500));
}
controller.close();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" },
});
}Key Comparison Table
| Export | Method | Body allowed | Typical status |
|---|---|---|---|
GET | GET | No | 200 |
POST | POST | Yes | 201 |
PUT | PUT | Yes | 200 |
PATCH | PATCH | Yes | 200 |
DELETE | DELETE | Optional | 204 |
OPTIONS | OPTIONS | No | 204 with CORS headers |
HEAD | HEAD | No | Derived from GET |
| Feature | Route Handler | Server Action |
|---|---|---|
| Callable from other origins | Yes (with CORS) | No |
| Returns arbitrary HTTP status | Yes | No |
| Works without JS | Yes | Yes (form) |
| Revalidates automatically | No | Yes, when you call it |
| Best for | Webhooks, public API, files, SSE | In-app mutations |
| Symptom | Meaning |
|---|---|
| Handler runs on every request in production | Next.js 15 does not cache GET by default |
request.json() throws | Empty body or wrong Content-Type |
params.id undefined | Not awaited |
| Cookie set but not sent | Set on the NextResponse, or use cookies().set |
Practical Edge Cases & Deep Dives
1. Reading the body once, and failing safely
const contentType = request.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
return NextResponse.json({ error: "unsupported media type" }, { status: 415 });
}
const body = await request.json();request.json() consumes the stream; a second call throws Body is unusable. It also throws on malformed JSON, which without a catch becomes a 500 instead of a 400 — an important distinction for a webhook sender that will retry on 5xx and not on 4xx. For form submissions, await request.formData() is the equivalent and handles multipart/form-data (file uploads included).
2. Cookies: reading, writing, and the two ways to set one
// In a route handler or Server Action — mutable
const jar = await cookies();
jar.set("theme", "dark", { maxAge: 60 * 60 * 24 * 365, httpOnly: true });
// On the response — explicit and visible in the code path
const res = NextResponse.json({ ok: true });
res.cookies.set({ name: "theme", value: "dark", httpOnly: true, secure: true, sameSite: "lax" });
return res;In a Server Component cookies() is read-only; writing throws. Setting a cookie in a GET handler while also returning a cached response is contradictory — a response with Set-Cookie must not be cached by a shared cache, so mark it Cache-Control: private, no-store.
3. Dynamic versus static route handlers
export const dynamic = "force-static"; // evaluated at build; request data is unavailable
export const revalidate = 3600; // ISR for a GET handler
export const runtime = "edge"; // Web APIs only; no Node built-ins, no DB driverA GET that reads request.url or request.nextUrl.searchParams cannot be force-static — the build has no request. The static form is for data that is the same for everyone: a sitemap, a manifest, a config document. Anything personalised belongs dynamic, and the Cache-Control header is then your own responsibility.
4. Streaming responses and the platform's flush behaviour
export async function POST(request: Request) {
const { prompt } = await request.json();
const upstream = await fetch("https://api.example.com/complete", {
method: "POST",
body: JSON.stringify({ prompt }),
});
return new Response(upstream.body, {
headers: { "Content-Type": "text/plain; charset=utf-8", "X-Accel-Buffering": "no" },
});
}Passing upstream.body straight through is the cheapest streaming proxy — no buffering, no string handling. The X-Accel-Buffering: no header matters behind an nginx-style proxy that would otherwise collect the whole body. On a platform that buffers by default, streaming may still work in development and arrive all at once in production; that is an infrastructure fact to verify, not a code bug.
5. CORS, webhooks, and status codes that carry meaning
export async function OPTIONS() {
return new NextResponse(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "https://partner.example.com",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "content-type, x-signature",
"Access-Control-Max-Age": "86400",
},
});
}Same-origin requests need no CORS at all; only a browser calling another origin does. A webhook is the opposite case: no CORS, but a signature header and a replay window. Verify the signature against the raw body before parsing, return 2xx quickly, and do the work asynchronously — most senders retry on non-2xx and time out in a few seconds.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Handler cached unexpectedly | Static output config or a revalidate export | Set dynamic = "force-dynamic" |
| Every request hits the DB in production | GET is uncached by default in 15 | Cache deliberately, or accept it |
| 500 instead of 400 on bad JSON | Unhandled request.json() rejection | catch and return 400 |
Body is unusable | Body read twice | Read once into a variable |
params.id undefined | Not awaited in Next.js 15+ | await params |
| Cookie set in a Server Component throws | Read-only context | Set it in an action or a handler |
| File upload empty | request.json() used for multipart | request.formData() |
Edge runtime error on fs/pg | Node built-ins unavailable at the edge | Use runtime = "nodejs" |
| Streaming arrives all at once | Proxy or platform buffering | Disable buffering; verify on the host |
| Preflight fails | No OPTIONS export, or missing headers | Add OPTIONS with CORS headers |
A route handler is plain HTTP with the framework's routing around it: pick the method export, read the request as a web Request, authorize it yourself, and return the right status. Everything the framework adds — dynamic rendering, params as a Promise, edge runtime — is configuration on top of that contract.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.