0
0
NextJSframework~10 mins

Catch-all 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 catch-all API route filename in Next.js.

NextJS
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from [1] route' });
}

// Filename: pages/api/[1].js
Drag options to blanks, or click blank then click option'
A[slug]
B[...slug]
Cindex
Dapi
Attempts:
3 left
💡 Hint
Common Mistakes
Using single brackets like [slug] only catches one segment.
Using 'index' or 'api' does not create a catch-all route.
2fill in blank
medium

Complete the code to access the catch-all route parameters inside the API handler.

NextJS
export default function handler(req, res) {
  const { [1] } = req.query;
  res.status(200).json({ params: [1] });
}
Drag options to blanks, or click blank then click option'
Apath
Bparams
Cquery
Dslug
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.query.params or req.query.path which do not match the filename.
Trying to access req.query.query which is not correct.
3fill in blank
hard

Fix the error in the catch-all API route handler to correctly handle no parameters.

NextJS
export default function handler(req, res) {
  const { slug = [] } = req.query;
  if ([1]) {
    res.status(200).json({ message: 'No parameters provided' });
  } else {
    res.status(200).json({ params: slug });
  }
}
Drag options to blanks, or click blank then click option'
Aslug === undefined
Bslug === null
Cslug.length === 0
Dslug.length > 0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if slug is null or undefined, which it never is due to default value.
Checking if slug.length > 0 which is true when parameters exist, not when missing.
4fill in blank
hard

Fill both blanks to create an optional catch-all API route filename and access its parameters.

NextJS
// Filename: pages/api/[1].js

export default function handler(req, res) {
  const { [2] = [] } = req.query;
  res.status(200).json({ params: [2] });
}
Drag options to blanks, or click blank then click option'
A[[...slug]]
B[...slug]
Cslug
Dparams
Attempts:
3 left
💡 Hint
Common Mistakes
Using single brackets for optional catch-all routes.
Using 'params' instead of the parameter name from the filename.
5fill in blank
hard

Fill all three blanks to return a JSON response with the first parameter, all parameters, and a message.

NextJS
export default function handler(req, res) {
  const { [1] = [] } = req.query;
  const firstParam = [2][0] || null;
  res.status(200).json({
    first: firstParam,
    all: [3],
    message: firstParam ? `First param is ${firstParam}` : 'No params'
  });
}
Drag options to blanks, or click blank then click option'
Aslug
Bparams
Dquery
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the parameter causing undefined errors.
Not handling the case when no parameters are passed.