0
0
NextJSframework~10 mins

Dynamic API routes in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a dynamic API route file name for a user ID.

NextJS
export default function handler(req, res) {
  const { [1] } = req.query;
  res.status(200).json({ id: [1] });
}
Drag options to blanks, or click blank then click option'
Aid
Bslug
Cparam
DuserId
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different key than the file name in req.query.
Forgetting to destructure the parameter from req.query.
2fill in blank
medium

Complete the code to create a dynamic API route file that captures a post slug.

NextJS
export default function handler(req, res) {
  const { [1] } = req.query;
  res.status(200).json({ slug: [1] });
}
Drag options to blanks, or click blank then click option'
Apost
BpostSlug
Cid
Dslug
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the file name.
Not matching the dynamic segment name exactly.
3fill in blank
hard

Fix the error in accessing the dynamic route parameter in this API handler.

NextJS
export default function handler(req, res) {
  const id = req.[1].id;
  res.status(200).json({ id });
}
Drag options to blanks, or click blank then click option'
Aquery
Bslug
Cparam
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params which is undefined in Next.js API routes.
Not destructuring the parameter from req.query.
4fill in blank
hard

Fill both blanks to correctly extract and respond with a dynamic user ID and post ID from the API route.

NextJS
export default function handler(req, res) {
  const { [1], [2] } = req.query;
  res.status(200).json({ userId: [1], postId: [2] });
}
Drag options to blanks, or click blank then click option'
AuserId
BpostId
Cid
Dslug
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up parameter names that don't match the file names.
Using id or slug instead of the correct keys.
5fill in blank
hard

Fill all three blanks to create a dynamic API route handler that returns the category, subcategory, and item ID.

NextJS
export default function handler(req, res) {
  const { [1], [2], [3] } = req.query;
  res.status(200).json({ category: [1], subcategory: [2], itemId: [3] });
}
Drag options to blanks, or click blank then click option'
Acategory
Bsubcategory
CitemId
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic names like id instead of specific dynamic segment names.
Not matching the order of destructured variables to the file path segments.