Next.jsEasy
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.paramsis a Promise with dynamic segments.- Return
Response.json(data, { status }),new Response(body, init)orNextResponsehelpers. - Use standard Web APIs:
request.json(),request.formData(),request.text(),Headers, streams. - Read cookies and headers with
request.cookies/request.headersorcookies()/headers()fromnext/headers.
Rules
- A
route.tscannot sit in the same segment as apage.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 theruntimeexport must be removed.
Caching
- Without Cache Components: handlers are not cached by default; opt
GETin withexport const dynamic = 'force-static'orrevalidate. - With Cache Components:
GETfollows 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.ts2import { NextRequest } from "next/server";3import { cacheLife, cacheTag } from "next/cache";4import { db } from "@/lib/db";56async function getUser(id: string) {7 "use cache"; // directive lives in a helper, not in the handler body8 cacheLife("minutes");9 cacheTag(`user:${id}`);10 return db.user.findUnique({ where: { id }, select: { id: true, name: true } });11}1213export 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}1920// app/api/health/route.ts - no request data: prerendered at build with Cache Components21// 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.