How do you create API routes in the App Router (Route Handlers)?

Create a route.ts file inside app/, for example app/api/users/route.ts, and export functions named after HTTP methods. Each receives a Web Request (or NextRequest) and returns a Response. The URL follows the folder path.

Basics

  • Signature: export async function GET(request: NextRequest, ctx: RouteContext<'/api/users/[id]'>).
  • ctx.params is a Promise with dynamic segments.
  • Return Response.json(data, { status }), new Response(body, init) or NextResponse helpers.
  • Use standard Web APIs: request.json(), request.formData(), request.text(), Headers, streams.
  • Read cookies and headers with request.cookies / request.headers or cookies() / headers() from next/headers.

Rules

  • A route.ts cannot sit in the same segment as a page.tsx.
  • Route Handlers do not use layouts and render no React UI.
  • They run on the Node.js runtime. export const runtime = 'edge' is deprecated, and with Cache Components the runtime export must be removed.

Caching

  • Without Cache Components: handlers are not cached by default; opt GET in with export const dynamic = 'force-static' or revalidate.
  • With Cache Components: GET follows the same model as pages. A handler that reads no request data or uncached I/O is prerendered at build time. To cache data inside a handler, call a helper marked "use cache"; the directive cannot go directly in the handler body.

When to use them

Webhooks, public APIs for mobile or third parties, file downloads, OAuth callbacks, streaming responses and generated files. For mutations from your own UI, Server Functions are usually simpler.

Code example

tsx
1// app/api/users/[id]/route.ts
2import { NextRequest } from "next/server";
3import { cacheLife, cacheTag } from "next/cache";
4import { db } from "@/lib/db";
5
6async function getUser(id: string) {
7 "use cache"; // directive lives in a helper, not in the handler body
8 cacheLife("minutes");
9 cacheTag(`user:${id}`);
10 return db.user.findUnique({ where: { id }, select: { id: true, name: true } });
11}
12
13export async function GET(_req: NextRequest, ctx: RouteContext<"/api/users/[id]">) {
14 const { id } = await ctx.params;
15 const user = await getUser(id);
16 if (!user) return Response.json({ error: "Not found" }, { status: 404 });
17 return Response.json(user);
18}
19
20// app/api/health/route.ts - no request data: prerendered at build with Cache Components
21// export function GET() { return Response.json({ ok: true, version: process.env.APP_VERSION }); }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app