Skip to content

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.

22 min read0/7 questions

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.

app/api/health/route.ts
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.

Where route handlers live
  • 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.

Quick check
You add app/dashboard/route.ts next to an existing app/dashboard/page.tsx. What happens?
Need a nudge? A hint rules out a wrong answer.

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:

TypeScripthandler.ts
// The shape of a route.ts POST handler, runnable without Next.jsasync function POST(request: Request) { const body = await request.json().catch(() => null); if (!body || typeof body.title !== "string" || body.title.length < 3) { return Response.json({ error: "title must be at least 3 characters" }, { status: 400 }); } return Response.json({ id: "p_123", title: body.title }, { status: 201 });} for (const payload of [{ title: "Hi" }, { title: "Hello world" }]) { const req = new Request("https://acme.dev/api/posts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload), }); const res = await POST(req); console.log(res.status, await res.json());}
Output
Press Run (⌘ Enter) to see what happens.

The useful methods on a request:

You wantUse
JSON bodyawait request.json()
Form postsawait request.formData()
Raw body (for signatures)await request.text()
A headerrequest.headers.get("authorization")
Query stringnew 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.

Predict the outputTypeScript

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"));
Need a nudge? Hints walk you through it.

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:

app/api/posts/[id]/route.ts
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.

A CMS publishes an article
CMSRoute HandlerCachePOST /api/webhooks/cms + signatureverify signature from raw bodyrevalidateTag("articles", "max")200 OK

The CMS signs the body with a shared secret.

1/4
app/api/webhooks/cms/route.ts
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:

TypeScriptverify-webhook.ts
const encoder = new TextEncoder(); async function hmacHex(secret: string, body: string) { const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(body)); return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");} const secret = "whsec_demo";const body = JSON.stringify({ type: "article.published", slug: "hello" });const sentSignature = await hmacHex(secret, body); // what the CMS sends in x-signature console.log("genuine: ", (await hmacHex(secret, body)) === sentSignature);console.log("tampered:", (await hmacHex(secret, body.replace("hello", "evil"))) === sentSignature);console.log("forged: ", (await hmacHex("guessed", body)) === sentSignature);
Output
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.

Quick check
Inside a webhook Route Handler you call updateTag("products"). What happens?
Need a nudge? A hint rules out a wrong answer.

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.

app/api/public/route.ts
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":

app/api/products/route.ts
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.

app/api/chat/route.ts
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:

TypeScriptsse-stream.ts
const encoder = new TextEncoder();const decoder = new TextDecoder(); // Stand-in for an AI SDK: yields tokens one at a time.async function* fakeModel(prompt: string) { for (const token of ["Route", " handlers", " can", " stream", "."]) { await new Promise((r) => setTimeout(r, 50)); yield token; }} // What the route handler returns: one SSE event per token, then a done event.function sseStream(prompt: string): ReadableStream<Uint8Array> { const tokens = fakeModel(prompt); let id = 0; return new ReadableStream({ async pull(controller) { const { value, done } = await tokens.next(); if (done) { controller.enqueue(encoder.encode("event: done\ndata: {}\n\n")); controller.close(); return; } id++; controller.enqueue(encoder.encode(`id: ${id}\ndata: ${JSON.stringify({ token: value })}\n\n`)); }, cancel() { console.log("client went away: stop the upstream call here"); }, });} // What the browser does with fetch(): read chunks, split on the blank line.async function main() { const res = new Response(sseStream("hi"), { headers: { "content-type": "text/event-stream", "cache-control": "no-cache" }, }); const reader = res.body!.getReader(); let buffer = ""; let text = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let end: number; while ((end = buffer.indexOf("\n\n")) !== -1) { const event = buffer.slice(0, end); buffer = buffer.slice(end + 2); const data = event.split("\n").find((l) => l.startsWith("data: "))?.slice(6); if (event.startsWith("event: done")) console.log("done"); else if (data) { text += JSON.parse(data).token; console.log("so far:", text); } } }} main();
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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));
Need a nudge? Hints walk you through it.

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 = 60 in 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.signal aborts and the stream's cancel() 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: error with 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().

app/api/avatar/route.ts
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.type is a claim, not a fact. The client sets it. A script renamed to cat.png arrives as image/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 as avatars/<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:

TypeScriptsniff-upload.ts
// The browser sends file.type, but the client controls it. Check the first bytes instead.const SIGNATURES: Record<string, number[]> = { "image/png": [0x89, 0x50, 0x4e, 0x47], "image/jpeg": [0xff, 0xd8, 0xff], "application/pdf": [0x25, 0x50, 0x44, 0x46], // %PDF};const MAX_BYTES = 5 * 1024 * 1024; async function checkUpload(file: File): Promise<string> { if (file.size > MAX_BYTES) return `rejected: ${file.size} bytes is over the limit`; const head = new Uint8Array(await file.slice(0, 8).arrayBuffer()); const real = Object.entries(SIGNATURES).find(([, sig]) => sig.every((b, i) => head[i] === b))?.[0]; if (!real) return `rejected: unknown content (claimed ${file.type})`; if (real !== file.type) return `rejected: claims ${file.type} but bytes say ${real}`; return `ok: ${file.name} is ${real}`;} async function main() { const png = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a])], "logo.png", { type: "image/png" }); const fake = new File(["<script>alert(1)</script>"], "cat.png", { type: "image/png" }); const pdfAsPng = new File(["%PDF-1.7 ..."], "invoice.png", { type: "image/png" }); const form = new FormData(); for (const f of [png, fake, pdfAsPng]) form.append("files", f); // Inside a route handler this would be: const form = await request.formData(); for (const entry of form.getAll("files")) { if (entry instanceof File) console.log(await checkUpload(entry)); }} main();
Output
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.

Direct-to-storage upload with a presigned URL
BrowserRoute HandlerObject storagePOST /api/uploads { type, size }pick key, sign URL (5 min){ url, key }PUT file bytes200POST /api/uploads/complete { key }

Authenticate the user and check the declared size and type against your rules.

1/6
app/api/uploads/route.ts
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.

Quick check
Your avatar handler checks file.size > 2 MB after await request.formData(). Someone posts a 1 GB body. What does the check protect?
Need a nudge? A hint rules out a wrong answer.

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:

ExportDoes
maxDurationSeconds the route may run before the platform stops it. Matters for streaming and slow jobs.
preferredRegionWhere 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.

Quick check
You inherit app/api/report/route.ts with export const runtime = 'edge' and turn on Cache Components. What should you do?
Need a nudge? A hint rules out a wrong answer.

Route Handler or Server Action?

Both run on the server. Pick by who is calling:

Server ActionRoute Handler
CallerYour own React UIAnyone: other servers, mobile apps, scripts, browsers on other origins
MethodsPOST onlyAny HTTP method
URLHidden, generatedA stable public path you choose
ReturnsSerialisable values and updated UIAny Response: JSON, XML, files, streams, redirects
Typical useForms, buttons, mutations from your pagesWebhooks, public or mobile APIs, file downloads, RSS
Match the pairs0/5 matched

Server Action or Route Handler?

Choose an item, then its match on the other side.
ChallengeEasy

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 (%20 and + 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" }
TypeScript
function parseSearchParams(search: string): Record<string, string | string[]> { // URLSearchParams does the decoding for you. return {};}
ChallengeMedium

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 page is present but not a positive whole number: 400, { error: "page must be a positive integer" }
  • If limit is present but not a whole number from 1 to 50: 400, { error: "limit must be between 1 and 50" } (check page first)
  • totalPages is Math.ceil(items.length / limit), but at least 1
  • 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 } }
TypeScript
type Out = { status: number; body: Record<string, unknown> }; function handleGet(url: string, items: string[]): Out { // new URL(url).searchParams.get("page") return { status: 500, body: {} };}
Key terms
Route Handler
A route.ts file exporting functions named after HTTP methods, used to build an endpoint at that folder's URL.
NextRequest
Next.js's extension of Request, adding nextUrl (parsed URL and search params) and cookies helpers.
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 OPTIONS preflight.
preflight
The OPTIONS request 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.ts for edge logic.