0
0
NextJSframework~30 mins

Catch-all API routes in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Catch-all API Route in Next.js
📖 Scenario: You are building a Next.js app that needs to handle API requests for multiple dynamic paths under one route.For example, you want to catch requests like /api/products/123, /api/products/123/reviews, or /api/products/123/reviews/456 with a single API route file.
🎯 Goal: Build a catch-all API route in Next.js that captures all sub-paths under /api/products and returns the path segments as JSON.
📋 What You'll Learn
Create a catch-all API route file named [...slug].ts inside app/api/products/
Extract the path segments from the request parameters
Return a JSON response with the captured path segments
Use Next.js 14+ App Router conventions with a GET handler
💡 Why This Matters
🌍 Real World
Catch-all API routes let you handle many dynamic URL paths with one file, useful for building flexible APIs in Next.js apps.
💼 Career
Understanding catch-all routes is important for Next.js developers building scalable backend APIs that respond to various dynamic paths.
Progress0 / 4 steps
1
Create the catch-all API route file
Create a file named [...slug].ts inside the app/api/products/ folder. Inside it, export an async function called GET that accepts a single parameter request and returns a JSON response with an empty array for slug.
NextJS
Need a hint?

Start by creating the API route file and export a GET function that returns { slug: [] } as JSON.

2
Extract the catch-all route parameter
Inside the GET function, extract the slug parameter from the request URL using new URL(request.url).pathname. Then split the pathname by '/' and remove the first 4 segments to isolate the slug parts. Store the result in a variable called slug.
NextJS
Need a hint?

Use new URL(request.url).pathname to get the path, then split by '/' and slice from index 4 to get the slug array.

3
Handle the case when no slug is provided
Add a check to see if the slug array is empty. If it is empty, return a JSON response with { message: 'No slug provided' }. Otherwise, return the slug array as before.
NextJS
Need a hint?

Check if slug.length === 0 and return a message JSON if true.

4
Complete the catch-all API route with proper export
Ensure the file exports the GET function as default export is not used. The file should be named [...slug].ts inside app/api/products/ and the GET function should handle the request as implemented.
NextJS
Need a hint?

Make sure the GET function is exported correctly and the file is named [...slug].ts.