Next.js API Routes explains how to build custom backend HTTP endpoints using Route Handlers inside the App Router.
Route Handlers are defined in a route.ts or route.js file inside any app/ directory subfolder.
flowchart LR
A["Client HTTP Request"] --> B["app/api/users/route.ts"]
B --> C{"HTTP Method"}
C -- "GET" --> D["Execute GET Handler"]
C -- "POST" --> E["Execute POST Handler"]
D & E --> F["Return NextResponse JSON"]
GET and POST)Export named async functions corresponding to standard HTTP methods (GET, POST, PUT, PATCH, DELETE):
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
interface User {
id: number;
name: string;
}
const mockUsers: User[] = [
{ id: 1, name: 'Alice Smith' },
{ id: 2, name: 'Bob Jones' },
];
// Handle GET /api/users
export async function GET() {
return NextResponse.json({ success: true, data: mockUsers });
}
// Handle POST /api/users
export async function POST(request: NextRequest) {
const body = await request.json();
const newUser = { id: Date.now(), name: body.name };
mockUsers.push(newUser);
return NextResponse.json({ success: true, data: newUser }, { status: 201 });
}
Access incoming request details using NextRequest:
// app/api/search/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q');
const authHeader = request.headers.get('authorization');
return NextResponse.json({
query,
authenticated: Boolean(authHeader),
});
}
Next.js supplies standard helper constructors for returning JSON, setting status codes, and managing cookies:
// Set cookies and custom response headers
return NextResponse.json(
{ message: 'Success' },
{
status: 200,
headers: { 'Cache-Control': 'no-store' }
}
);
page.tsx and route.ts in the Same Directory: Route Handlers and pages cannot share the same route URL path segment.POST body data before saving records to your database.Route Handlers inside route.ts provide full REST API flexibility inside Next.js. They handle JSON responses, status codes, and HTTP methods directly on the server.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.