Route Handlers
Next.js · Reference cheat sheet
Route Handlers
Next.js · Reference cheat sheet
📋 Overview
Route Handlers live in app/**/route.ts (or .js) and export HTTP method functions. They replace many pages/api use cases in the App Router.
🔧 Core concepts
| Export | HTTP method |
|---|---|
GET | Read |
POST | Create / submit |
PUT / PATCH | Update |
DELETE | Delete |
HEAD / OPTIONS | Meta / CORS |
| Helper | Use |
|---|---|
NextRequest | Extended Request (cookies, nextUrl) |
NextResponse | JSON, redirects, cookies |
params | Dynamic segment values |
💡 Examples
JSON GET:
// app/api/hello/route.ts
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "hi" });
}POST with body:
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const body = await req.json();
return NextResponse.json({ received: body }, { status: 201 });
}Dynamic segment:
// app/api/users/[id]/route.ts
export async function GET(
_req: Request,
ctx: { params: Promise<{ id: string }> },
) {
const { id } = await ctx.params;
return Response.json({ id });
}⚠️ Pitfalls
- Don't export a
page.tsxandroute.tsfor the same path segment. - Default caching of
GETcan surprise you — setexport const dynamic = 'force-dynamic'when needed. - Large file uploads need streaming/
FormDatacare; don't assume unlimited body size.