Next.js 40: Route Handlers — Dynamic Segments & NextRequest/NextResponse
easy⏱ 5 mincoursenextjs
params + nextUrl.searchParams
The folder [id] captures a dynamic segment, available as params.id. NextRequest extends the Web Request with nextUrl, a parsed URL whose .searchParams is a standard URLSearchParams — perfect for reading ?verbose=true without manually parsing the query string.
// app/api/todos/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const verbose = request.nextUrl.searchParams.get('verbose');
const todo = findTodo(params.id);
if (!todo) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(verbose ? { ...todo, verbose: true } : todo);
}
Return the right status code
Pick an id from the dropdown (including one that doesn't exist) and toggle ?verbose=true, then click the button. The response panel should show 404 for a missing id and 200 with the extra verbose fields when the flag is on.
Status codes are part of the contract
Callers of your API rely on the status code just as much as the body: 200 for success, 201 for created, 404 for not found, 400 for a bad request. NextResponse.json(data, { status }) lets you set it explicitly instead of always defaulting to 200.