Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNext.js
#Next.js#Route Handlers#API#Streaming
3D illustration of HTTP request blocks hitting a handler gate that answers with JSON and a chunked stream

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

ts
// 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 }); }
ts
// 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 }); }
ts
// 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

ExportMethodBody allowedTypical status
GETGETNo200
POSTPOSTYes201
PUTPUTYes200
PATCHPATCHYes200
DELETEDELETEOptional204
OPTIONSOPTIONSNo204 with CORS headers
HEADHEADNoDerived from GET
FeatureRoute HandlerServer Action
Callable from other originsYes (with CORS)No
Returns arbitrary HTTP statusYesNo
Works without JSYesYes (form)
Revalidates automaticallyNoYes, when you call it
Best forWebhooks, public API, files, SSEIn-app mutations
SymptomMeaning
Handler runs on every request in productionNext.js 15 does not cache GET by default
request.json() throwsEmpty body or wrong Content-Type
params.id undefinedNot awaited
Cookie set but not sentSet on the NextResponse, or use cookies().set

Practical Edge Cases & Deep Dives

1. Reading the body once, and failing safely

ts
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

ts
// 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

ts
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 driver

A 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

ts
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

ts
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

SymptomCauseFix
Handler cached unexpectedlyStatic output config or a revalidate exportSet dynamic = "force-dynamic"
Every request hits the DB in productionGET is uncached by default in 15Cache deliberately, or accept it
500 instead of 400 on bad JSONUnhandled request.json() rejectioncatch and return 400
Body is unusableBody read twiceRead once into a variable
params.id undefinedNot awaited in Next.js 15+await params
Cookie set in a Server Component throwsRead-only contextSet it in an action or a handler
File upload emptyrequest.json() used for multipartrequest.formData()
Edge runtime error on fs/pgNode built-ins unavailable at the edgeUse runtime = "nodejs"
Streaming arrives all at onceProxy or platform bufferingDisable buffering; verify on the host
Preflight failsNo OPTIONS export, or missing headersAdd 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 tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.