Loading lessons...
Route Handlers Basics (route.ts & HTTP Methods)
Route Handlers Basics (route.ts & HTTP Methods)
Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. They are the App Router replacement for the legacy pages/api API routes.
File Conventions
Route Handlers are defined in a file named route.ts (or .js) inside the app/ directory.
[!CAUTION] A
route.tsfile cannot exist in the same route segment folder as apage.tsxfile! If both exist atapp/api/users/route.tsandapp/api/users/page.tsx, Next.js will throw a routing collision build error.
Supported HTTP Methods
Route Handlers support the following HTTP method functions: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
// app/api/users/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
return NextResponse.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
if (!body.name) {
return NextResponse.json({ error: 'Name is required' }, { status: 400 });
}
const newUser = { id: Date.now(), name: body.name };
return NextResponse.json(newUser, { status: 201 });
}
Caching Behavior of GET Route Handlers
GET Route Handlers are statically cached by default in Next.js if they do not use dynamic functions or request objects.
Opting Out of Route Handler Caching:
- Export
export const dynamic = 'force-dynamic';from theroute.tsfile. - Use dynamic methods like
POST,PUT, orDELETEin the file. - Access
NextRequestproperties likerequest.headersor query parameters.
Route Handler Method Summary
| Export Name | HTTP Verb | Purpose | Caching |
|---|---|---|---|
GET | Read resource | Retrieves data | Statically cached by default |
POST | Create resource | Creates new entry | Never cached |
PUT / PATCH | Update resource | Updates existing data | Never cached |
DELETE | Delete resource | Removes record | Never cached |
TL;DR
- Define API endpoints in
route.tsfiles inside theapp/directory. - Export functions named after HTTP verbs (
GET,POST,DELETE, etc.). - Never place
route.tsandpage.tsxin the exact same directory. - Use
NextResponse.json(data, { status: N })to return structured JSON responses.