route.ts files.GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.NextRequest and NextResponse for enhanced functionality like cookies and redirects.1import { NextRequest, NextResponse } from 'next/server';23export async function GET(request: NextRequest) {4const users = await db.user.findMany();5return NextResponse.json(users);6}78export async function POST(request: NextRequest) {9const body = await request.json();1011// Validate input12if (!body.email) {13return NextResponse.json(14{ error: 'Email required' },15{ status: 400 },16);17}1819const user = await db.user.create(body);20return NextResponse.json(user, { status: 201 });21}
| Approach | Best For |
|---|---|
| Route Handlers | External API consumers, webhooks, file downloads |
| Server Actions | Form submissions, mutations from React components |
| Server Components | Data fetching for rendering |
Handlers run in Node.js or Edge runtime based on your export config.
| Topic | Guidance |
|---|---|
| API design | One route handler per resource, small and focused |
| Runtime | Node.js for full APIs, Edge for low-latency endpoints |
| Caching | GET requests cache by default; use headers to control |
| Security | Always validate input and sanitize output |
Request object usage become dynamic.