Catch-all API routes let you handle many URL paths with one file. This helps when you want to respond to different paths without making many files.
0
0
Catch-all API routes in NextJS
Introduction
You want one API file to handle multiple related paths.
You need to build a flexible API that accepts different URL depths.
You want to create dynamic routes that catch all sub-paths.
You want to simplify your API folder structure by grouping routes.
You want to handle unknown or variable paths gracefully.
Syntax
NextJS
pages/api/[...slug].js export default function handler(req, res) { const { slug } = req.query; res.status(200).json({ slug }); }
The file name uses square brackets with three dots: [...slug].
The slug is an array of all parts of the URL after /api/.
Examples
This example uses
params as the catch-all name. It returns all URL parts as an array.NextJS
pages/api/[...params].js export default function handler(req, res) { const { params } = req.query; res.status(200).json({ params }); }
This catch-all route is inside a
blog folder, catching all paths under /api/blog/.NextJS
pages/api/blog/[...slug].js export default function handler(req, res) { const { slug } = req.query; res.status(200).json({ slug }); }
Using
all as the parameter name to catch all API paths.NextJS
pages/api/[...all].js export default function handler(req, res) { const { all } = req.query; res.status(200).json({ all }); }
Sample Program
This API route catches all paths under /api/[...slug]. It returns a JSON with a message and the array of URL parts.
NextJS
export default function handler(req, res) { const { slug } = req.query; res.status(200).json({ message: 'Catch-all route works!', slug }); }
OutputSuccess
Important Notes
If the URL is /api/posts/2024/06, the slug array will be ["posts", "2024", "06"].
You can also create optional catch-all routes using [[...slug]].js to allow empty paths.
Catch-all routes help keep your API organized and flexible.
Summary
Catch-all API routes use [...name].js to catch many URL parts.
The caught parts come as an array in req.query.
This makes handling dynamic and nested API paths easy.