Q19: What are Route Handlers and how do they replace API Routes?
Route Handlers (route.js) replace legacy Pages Router API routes (/pages/api). Defined inside the /app directory, they export named functions matching HTTP methods: GET, POST, PUT, DELETE, PATCH.
JSON Response Route Handler
// app/api/users/route.js
import { NextResponse } from 'next/server';
export async function GET() {
const users = [{ id: 1, name: 'Alice' }];
return NextResponse.json(users);
}
export async function POST(request) {
const body = await request.json();
return NextResponse.json({ status: 'Created', data: body }, { status: 201 });
}💡 Maps REST API endpoints to GET and POST requests served from /api/users.
Key Takeaways
- Created inside
/appdirectory usingroute.jsfiles. - Export standard HTTP method functions (
export async function GET(request) {}).
Knowledge Check
Can a route.js file coexist inside the exact same folder directory as a page.js file?