Lesson 14 of 27Full-stack
Route Handlers
Build HTTP endpoints with route.ts: web Request and Response, webhooks, CORS, caching, streaming, file uploads and runtimes.
Not every request wants a page. Stripe needs somewhere to send payment webhooks, your mobile app needs JSON, a partner needs a CSV export. Route Handlers are the App Router's way to write plain HTTP endpoints, using the same Request and Response objects you already know from fetch. Knowing when to reach for one instead of a Server Action is a common interview question.
route.ts: one file, one endpoint
A Route Handler lives in a file named route.ts inside app/. The folder path is the URL, exactly like pages. Instead of a component, you export functions named after HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS.
export async function GET() {
return Response.json({ status: "ok", time: new Date().toISOString() });
}That is a working GET /api/health. Calling it with an HTTP method you did not export returns 405 Method Not Allowed automatically.
- app/
- page.tsxthe / page
- api/
- health/
- route.tsGET /api/health
- posts/
- route.tsGET, POST /api/posts
- [id]/
- route.tsGET, PATCH, DELETE /api/posts/:id
- webhooks/
- stripe/
- route.tsPOST /api/webhooks/stripe
- feed.xml/
- route.tsGET /feed.xml (an RSS feed)
The api/ folder is only a convention; a handler can live at any path. The one rule: a folder cannot have both a page.tsx and a route.ts, because both would claim the same URL. Route handlers also do not use layouts; they return raw responses.
app/dashboard/route.ts next to an existing app/dashboard/page.tsx. What happens?Requests and responses are web standards
Handlers receive a standard Request and return a standard Response. These are the same classes your browser and the JavaScript runtime here provide, so you can try the pattern right now:
Press Run (⌘ Enter) to see what happens.The useful methods on a request:
| You want | Use |
|---|---|
| JSON body | await request.json() |
| Form posts | await request.formData() |
| Raw body (for signatures) | await request.text() |
| A header | request.headers.get("authorization") |
| Query string | new URL(request.url).searchParams |
Next.js also offers NextRequest and NextResponse, thin extensions with conveniences: request.nextUrl.searchParams, request.cookies.get("session"), and NextResponse.redirect() or NextResponse.json() with cookie helpers. Inside handlers you can also call cookies() and headers() from next/headers.
What does this print?
const res = Response.json({ ok: true }, { status: 201, headers: { "x-id": "42" } });
console.log(res.status, res.headers.get("x-id"), res.headers.get("content-type"));Dynamic segments and query strings
Dynamic folders work the same as for pages. The second argument is a context whose params is a Promise. Next.js generates a RouteContext type from your folder names:
import type { NextRequest } from "next/server";
import { getPost } from "@/lib/posts";
export async function GET(request: NextRequest, ctx: RouteContext<"/api/posts/[id]">) {
const { id } = await ctx.params;
const fields = request.nextUrl.searchParams.get("fields"); // ?fields=title,body
const post = await getPost(id);
if (!post) return Response.json({ error: "Not found" }, { status: 404 });
return Response.json(fields ? pick(post, fields.split(",")) : post);
}
function pick<T extends object>(obj: T, keys: string[]) {
return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
}Webhooks
A webhook is a request another service sends you when something happens: a payment succeeded, a CMS entry was published. Route Handlers are the natural place to receive them, because the caller is a server, not your UI.
The CMS signs the body with a shared secret.
import { revalidateTag } from "next/cache";
import { verifySignature } from "@/lib/webhooks";
export async function POST(request: Request) {
const raw = await request.text(); // read the raw body: signatures are computed over exact bytes
const signature = request.headers.get("x-signature") ?? "";
if (!(await verifySignature(raw, signature, process.env.CMS_WEBHOOK_SECRET!))) {
return new Response("Invalid signature", { status: 401 });
}
const event = JSON.parse(raw) as { type: string; slug: string };
if (event.type === "article.published") revalidateTag("articles", "max");
return Response.json({ received: true });
}What does verifySignature do? The sender computes an HMAC (a hash keyed with the shared secret) of the exact body bytes and puts it in a header. You compute the same HMAC and compare. Anyone without the secret cannot produce a matching value. The Web Crypto API does this in every modern runtime:
Press Run (⌘ Enter) to see what happens.In production, compare with a constant-time function (Node's crypto.timingSafeEqual) so attackers cannot learn the signature from response timing, and use the provider's SDK when one exists (Stripe's constructEvent, for example).
Note the cache call. updateTag only works inside Server Actions, so webhooks use revalidateTag(tag, "max") (serve stale while refreshing) or revalidateTag(tag, { expire: 0 }) when the old data must disappear immediately.
updateTag("products"). What happens?CORS
If JavaScript on another origin (say, https://partner.com) calls your API from the browser, the browser enforces CORS (Cross-Origin Resource Sharing): your response must include headers saying that origin is allowed. For non-simple requests (custom headers, JSON bodies, PUT), the browser first sends an OPTIONS preflight request.
const CORS = {
"Access-Control-Allow-Origin": "https://partner.com",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
export function OPTIONS() {
return new Response(null, { status: 204, headers: CORS });
}
export async function GET() {
return Response.json({ items: [] }, { headers: CORS });
}CORS only matters for browsers. Server-to-server calls (webhooks, your own Server Components) ignore it. To apply CORS headers across many routes, use headers() in next.config.ts or proxy.ts.
Static and cached GET handlers
With Cache Components on, GET handlers follow the same rules as pages. A handler that uses no request data and no uncached I/O is prerendered at build time and served as a static file. Reading request.url, headers, cookies, or querying a database makes it run per request, unless you move the data access into a helper with "use cache":
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/db";
export async function GET() {
return Response.json(await getProducts());
}
async function getProducts() {
"use cache"; // not allowed directly in the handler body, so it lives in a helper
cacheLife("hours");
cacheTag("products");
return db.query.products.findMany();
}Only GET can be cached. POST, PUT, DELETE and the rest always run per request. (Without Cache Components, the older way is export const dynamic = "force-static" in the file.) Special metadata routes like sitemap.ts and robots.ts are Route Handlers under the hood and are static by default.
Streaming responses
An AI chat feature is the classic case. The model takes ten seconds to finish an answer, but it produces the first word after half a second. If your handler waits for the whole answer and then returns JSON, the user stares at a spinner for ten seconds. If it streams, words appear as the model writes them. The same applies to long CSV exports, progress updates for a slow job and live dashboards.
A Response body does not have to be a finished string. It can be a ReadableStream: an object the runtime pulls chunks from and writes to the socket as they arrive. Next.js passes it straight through, and the HTTP response uses chunked transfer, so the browser receives bytes long before the handler finishes.
import { streamAnswer } from "@/lib/ai"; // yields text tokens
export async function POST(request: Request) {
const { prompt } = await request.json();
const encoder = new TextEncoder();
const tokens = streamAnswer(prompt, { signal: request.signal });
const stream = new ReadableStream({
async pull(controller) {
const { value, done } = await tokens.next();
if (done) return controller.close();
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ token: value })}\n\n`));
},
});
return new Response(stream, {
headers: {
"content-type": "text/event-stream",
"cache-control": "no-cache, no-transform",
"x-accel-buffering": "no", // ask nginx-style proxies not to buffer
},
});
}pull is called whenever the consumer is ready for more. That gives you backpressure for free: a slow client is not flooded, because you only produce the next chunk when the last one was taken.
The SSE format
The body above uses Server-Sent Events (SSE), a tiny text protocol on top of a streamed response. Each event is a few field: value lines followed by a blank line:
id: 7
event: token
data: {"token":"Hello"}
data carries the payload, event names the type (the default is message), and id lets a reconnecting client say where it got to. The blank line, two newlines in a row, is what ends an event. Network chunks do not respect it: one read() can contain half an event or three of them, so a client must buffer text and only parse up to the last \n\n.
The browser's built-in EventSource only does GET and cannot send custom headers such as Authorization. AI chat needs a POST with a prompt body, so most apps read the stream with fetch and a reader instead. This simulation runs the server half and the client half together:
Press Run (⌘ Enter) to see what happens.What does this print?
const raw = "data: a\n\ndata: b\n\nda";
const events = raw.split("\n\n");
console.log(events.length, events.at(-1));What goes wrong in production
- Buffering. Some proxies, CDNs and compression layers collect the whole body before sending it on, which turns your stream back into one slow response. Send
cache-control: no-cache, no-transform, and check your host's docs for streaming support. - Timeouts. A serverless function has a maximum run time.
export const maxDuration = 60in the route file tells platforms that read it how long this route may run. Very long jobs belong in a queue, with the stream only reporting progress. - Abandoned requests. When the user closes the tab,
request.signalaborts and the stream'scancel()runs. Pass the signal to the upstream model call. If you do not, you keep paying for tokens nobody will read. - Errors mid-stream. The status code (200) went out with the first byte. You cannot change it to 500 later, so send an
event: errorwith a message the client can show, then close.
AI SDKs wrap all of this in helpers that return a ready-made streaming Response. They are built on exactly these Web APIs, so knowing the layer underneath is what lets you debug them.
File uploads
A user uploads an avatar or a PDF invoice. The browser sends multipart/form-data, and await request.formData() gives you a FormData whose file fields are File objects with name, size, type and methods like arrayBuffer().
import { getSession } from "@/lib/auth";
import { saveAvatar } from "@/lib/storage";
const MAX_BYTES = 2 * 1024 * 1024;
export async function POST(request: Request) {
const session = await getSession();
if (!session) return new Response("Unauthorized", { status: 401 });
const form = await request.formData();
const file = form.get("avatar");
if (!(file instanceof File)) return Response.json({ error: "avatar is required" }, { status: 400 });
if (file.size > MAX_BYTES) return Response.json({ error: "max 2 MB" }, { status: 413 });
const url = await saveAvatar(session.userId, file); // your code picks the storage key
return Response.json({ url }, { status: 201 });
}Three things in that handler are easy to get wrong:
file.typeis a claim, not a fact. The client sets it. A script renamed tocat.pngarrives asimage/png. Check the first bytes (the "magic number") of the file before you trust it, and never serve user uploads from your own domain with a type they chose.- The file name is untrusted input. Never use it as a storage path;
../../in a name is a classic path traversal. Generate your own key, such asavatars/<userId>/<random id>.png, and keep the original name only as metadata. formData()reads the whole body into memory. That is fine for a 2 MB avatar and dangerous for a 2 GB video. Your size check also runs after the body arrived, so it protects your storage, not your server's memory.
Try the type check:
Press Run (⌘ Enter) to see what happens.Size limits come from several places
Route Handlers have no small built-in body limit of their own, but the layers around them do. Hosting platforms cap request bodies for serverless functions, often at a few megabytes; check your host's current limits. If a proxy.ts runs on the route, Next.js buffers the body so both can read it, up to the experimental.proxyClientMaxBodySize setting (10 MB by default), and logs a warning past it. Server Actions have their own serverActions.bodySizeLimit, 1 MB by default. A reverse proxy such as nginx adds another. When an upload "fails for big files only", walk through these layers in order.
Large files: upload straight to storage
For anything big, do not send the file through your server at all. Your handler signs a short-lived presigned URL that lets the browser upload one object directly to S3 (or R2, GCS, Azure Blob). Your server only handles a few hundred bytes of JSON.
Authenticate the user and check the declared size and type against your rules.
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { getSession } from "@/lib/auth";
const s3 = new S3Client({});
const ALLOWED = new Set(["image/png", "image/jpeg", "application/pdf"]);
export async function POST(request: Request) {
const session = await getSession();
if (!session) return new Response("Unauthorized", { status: 401 });
const { type, size } = await request.json();
if (!ALLOWED.has(type) || size > 50 * 1024 * 1024) {
return Response.json({ error: "unsupported file" }, { status: 400 });
}
const key = `uploads/${session.userId}/${crypto.randomUUID()}`;
const url = await getSignedUrl(
s3,
new PutObjectCommand({ Bucket: process.env.UPLOAD_BUCKET, Key: key, ContentType: type, ContentLength: size }),
{ expiresIn: 300 },
);
return Response.json({ url, key });
}The trade-off: the client now talks to storage directly, so the bucket needs a CORS rule for your origin, and your server learns about the file only when the client reports back. That is why the complete step re-checks the object instead of trusting the client. Presigned POST policies can enforce a size range on the storage side; check your provider's docs for what its signed URLs can restrict.
file.size > 2 MB after await request.formData(). Someone posts a 1 GB body. What does the check protect?Which runtime runs your handler
Route Handlers run on the Node.js runtime by default, the same as pages. You get the full Node API (fs, crypto, native database drivers) and the whole npm ecosystem.
Older code often has export const runtime = "edge" at the top of a route file. The Edge Runtime is a smaller, web-only environment designed to start fast close to the user. It has no fs, no native modules and only part of the Node API, so many database drivers and SDKs do not work in it. It is deprecated in current Next.js 16 releases, and with Cache Components on you must remove the runtime export entirely, even runtime = "nodejs". If you need code at the edge, the supported place is proxy.ts, covered in Auth and Proxy.
What you still tune per route:
| Export | Does |
|---|---|
maxDuration | Seconds the route may run before the platform stops it. Matters for streaming and slow jobs. |
preferredRegion | Where platforms that support it should run the function. Put it near your database, not near the user. |
That last point surprises people. A function next to the user but far from the database makes several slow round trips per request. A function next to the database makes one slow round trip, to the user. For almost every handler that reads data, close to the data wins. Keeping connections healthy from serverless functions is covered in Databases and the Data Access Layer, and tracing slow handlers in Observability and Running Next.js in Production.
app/api/report/route.ts with export const runtime = 'edge' and turn on Cache Components. What should you do?Route Handler or Server Action?
Both run on the server. Pick by who is calling:
| Server Action | Route Handler | |
|---|---|---|
| Caller | Your own React UI | Anyone: other servers, mobile apps, scripts, browsers on other origins |
| Methods | POST only | Any HTTP method |
| URL | Hidden, generated | A stable public path you choose |
| Returns | Serialisable values and updated UI | Any Response: JSON, XML, files, streams, redirects |
| Typical use | Forms, buttons, mutations from your pages | Webhooks, public or mobile APIs, file downloads, RSS |
Server Action or Route Handler?
Parse search params like Next.js
A page's searchParams prop resolves to an object whose values are string | string[]. Write parseSearchParams(search) that builds the same shape from a query string.
- A leading
?is optional. - A key that appears once maps to a string. A key that appears more than once maps to an array, in order.
- Decode values the way browsers do (
%20and+are spaces). A key with no=has the value"".
"?tag=react&tag=next&page=2" → { tag: ["react", "next"], page: "2" }
"q=hello+world" → { q: "hello world" }A paginated GET handler
Write the logic of GET /api/posts as a pure function: handleGet(url, items) returns { status, body }, which a Route Handler would turn into Response.json(body, { status }).
Read page (default 1) and limit (default 10) from the URL's query string.
- If
pageis present but not a positive whole number:400,{ error: "page must be a positive integer" } - If
limitis present but not a whole number from 1 to 50:400,{ error: "limit must be between 1 and 50" }(checkpagefirst) totalPagesisMath.ceil(items.length / limit), but at least1- If
page > totalPages:404,{ error: "Page not found" } - Otherwise
200,{ items: <that page's slice>, page, totalPages }
handleGet("https://acme.dev/api/posts?page=2&limit=2", ["a","b","c","d","e"])
→ { status: 200, body: { items: ["c","d"], page: 2, totalPages: 3 } }- Route Handler
- A
route.tsfile exporting functions named after HTTP methods, used to build an endpoint at that folder's URL. - NextRequest
- Next.js's extension of
Request, addingnextUrl(parsed URL and search params) andcookieshelpers. - webhook
- An HTTP request another service sends to your endpoint when an event happens, usually signed with a shared secret.
- CORS
- Browser rule that cross-origin requests need permission headers from the server, often after an
OPTIONSpreflight. - preflight
- The
OPTIONSrequest a browser sends before a non-simple cross-origin request, asking which methods and headers are allowed. - ReadableStream
- A web-standard body the runtime pulls chunks from, so a response can start before the handler finishes.
- Server-Sent Events
- A text protocol over one streamed response:
data:lines ended by a blank line, used for live updates and AI tokens. - presigned URL
- A short-lived signed link that lets a client upload or download one storage object directly, without your server in the middle.
- Edge Runtime
- A web-only, deprecated alternative to the Node.js runtime. Current Next.js runs handlers on Node.js and uses
proxy.tsfor edge logic.