0
0
NextJSframework~5 mins

Dynamic API routes in NextJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a dynamic API route in Next.js?
A dynamic API route is an API endpoint that uses file names with square brackets (e.g., [id].js) to capture parts of the URL as parameters, allowing the API to respond differently based on the URL segment.
Click to reveal answer
beginner
How do you define a dynamic API route file for a user ID in Next.js?
You create a file named pages/api/users/[id].js. The [id] part captures the user ID from the URL, which you can access in the handler function.
Click to reveal answer
beginner
How do you access the dynamic parameter inside a Next.js API route handler?
Inside the API route handler, you access the parameter via <code>req.query</code>. For example, if the file is <code>[id].js</code>, you get the ID with <code>const { id } = req.query;</code>.
Click to reveal answer
beginner
What happens if you request /api/users/123 when you have a dynamic API route [id].js?
Next.js matches the URL segment '123' to the [id] parameter. The API handler receives req.query.id === '123' and can use it to return data specific to user 123.
Click to reveal answer
intermediate
Can you have multiple dynamic parameters in a Next.js API route? How?
Yes. You can create nested dynamic routes like pages/api/users/[userId]/posts/[postId].js. Both userId and postId are available in req.query.
Click to reveal answer
How do you name a file to create a dynamic API route for a product ID in Next.js?
AproductId[].js
BproductId.js
Cproduct-[id].js
D[productId].js
Where do you find the dynamic parameter value inside a Next.js API route handler?
Areq.body
Breq.query
Creq.params
Dreq.headers
What URL matches the API route file pages/api/posts/[postId].js?
A/api/posts
B/api/posts/postId
C/api/posts/42
D/api/posts/[postId]
Can you use multiple dynamic segments in one API route in Next.js?
AYes, by nesting folders with dynamic names
BNo, only one dynamic segment is allowed
CYes, but only separated by dashes
DNo, dynamic routes are not supported in API
What is the benefit of using dynamic API routes in Next.js?
AThey allow handling many similar URLs with one file
BThey improve CSS styling
CThey speed up image loading
DThey disable server-side rendering
Explain how to create and use a dynamic API route in Next.js to fetch data based on a URL parameter.
Think about how the file name relates to the URL and how you get the parameter inside the code.
You got /4 concepts.
    Describe how you can handle multiple dynamic parameters in Next.js API routes and how to access them.
    Consider a URL with two variable parts and how the folder structure matches it.
    You got /3 concepts.