Skip to content
Watch the complete Next.js 15 course on YouTube

Dynamic route handlers

This page explains how to implement dynamic route handlers in Next.js for handling requests with URL parameters.

Understanding dynamic route handlers

Dynamic route handlers allow you to create API endpoints that can handle requests with variable URL segments. They follow the same pattern as dynamic page routes, using square brackets to denote dynamic segments.

Creating dynamic route handlers

To create a dynamic route handler:

  1. Create a folder with the dynamic segment name in square brackets (e.g., [id])
  2. Add a route.ts file inside the folder
  3. Export functions for the HTTP methods you want to handle
  • Directoryapp/
    • Directoryapi/
      • Directorycomments/
        • Directory[id]/
          • route.ts /api/comments/[id]
        • route.ts /api/comments

Here’s a basic dynamic route handler that retrieves a comment by its ID:

app/api/comments/[id]/route.ts
import { comments } from "../data";
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const comment = comments.find((comment) => comment.id === parseInt(id));
return Response.json(comment);
}

Route parameters

Dynamic route handlers receive two parameters:

  • A request object containing the HTTP request details
  • A context object containing route parameters

The params object in the context is a Promise that resolves to an object containing all dynamic segments from the URL. For example, accessing /api/comments/1 provides:

params = { id: "1" };

Good to know

  • Dynamic segments are passed as strings and may need type conversion
  • The handler receives the same Request object as standard route handlers
  • Route parameters are accessed through the context object’s params property