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:
- Create a folder with the dynamic segment name in square brackets (e.g.,
[id]
) - Add a
route.ts
file inside the folder - Export functions for the HTTP methods you want to handle
Directoryapp/
Directoryapi/
Directorycomments/
Directory[id]/
- route.ts
/api/comments/[id]
- route.ts
- route.ts
/api/comments
Here’s a basic dynamic route handler that retrieves a comment by its ID:
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