Back to results for “Error Handling”
Next.js › Route Handlers (API Route.js)

How do you access dynamic route parameters inside a route handler defined with a dynamic segment?

Intermediate

Answer

The second argument passed to your route handler function contains a params object, which you await to access the dynamic segment values captured from the URL, letting you build endpoints like fetching a specific item by its id.
// app/api/products/[id]/route.js
export async function GET(request, { params }) {
  const { id } = await params;
  const product = await getProduct(id);
  return Response.json(product);
}
Real-world example A product API endpoint reads the product id directly from the dynamic route segment, letting it fetch and return the correct product details for any given id in the URL.

Common follow-ups: Can route handlers have both dynamic segments and query parameters at the same time?;How do you return a 404 response from within a route handler?