0
0
NextJSframework~5 mins

Dynamic API routes in NextJS

Choose your learning style9 modes available
Introduction

Dynamic API routes let your app handle many similar requests using one route. This saves time and keeps your code neat.

You want to get user info by user ID from the URL.
You need to fetch product details based on product codes.
You want to handle blog posts with different slugs in the URL.
You want to create an API that responds differently based on URL parts.
Syntax
NextJS
/pages/api/[param].js

Use square brackets [param] in the file name to mark a dynamic part.

The dynamic part is available in the handler as req.query.param.

Examples
This route handles URLs like /api/user/123 and returns the user ID.
NextJS
// File: /pages/api/user/[id].js
export default function handler(req, res) {
  const { id } = req.query;
  res.status(200).json({ message: `User ID is ${id}` });
}
This route handles product codes dynamically from the URL.
NextJS
// File: /pages/api/product/[code].js
export default function handler(req, res) {
  const { code } = req.query;
  res.status(200).json({ productCode: code });
}
This catch-all route handles multiple URL parts like /api/blog/2024/06/nextjs.
NextJS
// File: /pages/api/blog/[...slug].js
export default function handler(req, res) {
  const { slug } = req.query;
  res.status(200).json({ slug });
}
Sample Program

This API route greets the user by the ID from the URL. For example, calling /api/user/42 returns a greeting with 42.

NextJS
// File: /pages/api/user/[id].js
export default function handler(req, res) {
  const { id } = req.query;
  res.status(200).json({ message: `Hello, user ${id}!` });
}
OutputSuccess
Important Notes

Dynamic routes let you write one handler for many URLs.

Use req.query to get the dynamic parts from the URL.

Catch-all routes use [...param] to capture multiple URL segments.

Summary

Dynamic API routes use square brackets in file names to capture URL parts.

You access these parts inside the handler with req.query.

This helps keep your API code simple and flexible.