Next.js
API Routes
Creating API endpoints using Next.js App Router Route Handlers.
Basic GET and POST: Standard route handler handling multiple HTTP methods.
app/api/users/route.ts
TS
import { NextResponse } from 'next/server';
export async function GET() {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' }
];
return NextResponse.json(users);
}
export async function POST(request: Request) {
const data = await request.json();
// Create user logic here
return NextResponse.json({ message: 'User created', data }, { status: 201 });
}
Dynamic Route Parameters: Accessing dynamic route segments like IDs in the API handler.
app/api/users/[id]/route.ts
TS
import { NextResponse } from 'next/server';
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const id = params.id;
// Fetch user by id logic here
return NextResponse.json({
id,
name: 'Dynamic User',
message: `Fetched user with ID: ${id}`
});
}