Learn the concept
Route Handlers & API Routes
API routes let you build backend endpoints within your Next.js app. In the Pages Router, files in `pages/api/` export handlers. In the App Router, you create `route.ts` files that export functions named after HTTP methods (GET, POST, etc.).
Pages Router API Routes:
pages/api/req and res objects (like Express)App Router Route Handlers:
app/api/.../route.tsGET, POST, PUT, DELETE, etc.Common Use Cases:
Key Points:
Current Behavior in App Router:
headers() and cookies() are now async and must be awaitedResponse objects directly// app/api/posts/route.ts
import { NextResponse } from 'next/server';
// GET /api/posts
export async function GET() {
const posts = await db.posts.findMany();
return NextResponse.json(posts);
}
// POST /api/posts
export async function POST(request: Request) {
const body = await request.json();
const post = await db.posts.create({
data: {
title: body.title,
content: body.content,
},
});
return NextResponse.json(post, { status: 201 });
}
// app/api/posts/[id]/route.ts
// GET /api/posts/123
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const { id } = await params;
const post = await db.posts.findUnique({
where: { id },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
return NextResponse.json(post);
}Using Route Handlers as a Backend-for-Frontend layer to aggregate and transform data from multiple microservices
Creating POST route handlers to receive webhooks from Stripe, GitHub, or other services with secret validation
Using streaming responses in route handlers for real-time updates like progress bars or live notifications
Build a complete CRUD API for a resource using App Router route handlers with validation and error handling
Create a chat application using Route Handler streaming for Server-Sent Events with client-side EventSource