Bird
Raised Fist0
NextJSframework~20 mins

Dynamic API routes in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Dynamic API Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this dynamic API route?
Consider a Next.js API route file named pages/api/user/[id].js with the following code. What will be the JSON response when a GET request is made to /api/user/42?
NextJS
export default function handler(req, res) {
  const { id } = req.query;
  res.status(200).json({ userId: id, message: `User ID is ${id}` });
}
A{"id":"42","message":"User ID is 42"}
B{"userId":42,"message":"User ID is 42"}
C{"userId":"42","message":"User ID is 42"}
D{"userId":"id","message":"User ID is id"}
Attempts:
2 left
💡 Hint
Remember that query parameters in Next.js API routes are always strings.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a catch-all dynamic API route?
You want to create a Next.js API route that catches all paths under /api/posts/, including nested paths like /api/posts/2023/05. Which file name correctly implements this?
Apages/api/posts/[...slug].jsx
Bpages/api/posts/[slug].js
Cpages/api/posts/[slug...].js
Dpages/api/posts/[...slug].js
Attempts:
2 left
💡 Hint
Catch-all routes use three dots inside square brackets.
🔧 Debug
advanced
2:00remaining
Why does this dynamic API route return 404 for /api/products/123?
Given the file pages/api/product/[productId].js with this code, why does a request to /api/products/123 return 404?
export default function handler(req, res) {
  const { productId } = req.query;
  if (!productId) {
    res.status(400).json({ error: 'Missing productId' });
    return;
  }
  res.status(200).json({ id: productId });
}
AThe handler does not handle POST requests, so GET returns 404.
BThe file is inside pages/api/product/ but the folder is named 'product' instead of 'products'.
CThe dynamic segment is named [id], but code uses productId.
DThe code returns 400 if productId is missing, but productId is always undefined.
Attempts:
2 left
💡 Hint
Check the folder name in the file path carefully.
state_output
advanced
2:00remaining
What is the value of slug in this catch-all API route?
In a Next.js API route file named pages/api/blog/[...slug].js, the handler is:
export default function handler(req, res) {
  const { slug } = req.query;
  res.status(200).json({ slug });
}
What is the JSON response when a request is made to /api/blog/2024/06/updates?
A{"slug":["2024","06","updates"]}
B{"slug":"2024/06/updates"}
C{"slug":["2024/06/updates"]}
D{"slug":null}
Attempts:
2 left
💡 Hint
Catch-all routes provide an array of path segments.
🧠 Conceptual
expert
2:00remaining
Which statement about dynamic API routes in Next.js is TRUE?
Select the correct statement about dynamic API routes in Next.js.
ACatch-all dynamic API routes capture multiple path segments as an array in req.query.
BDynamic API routes require manual parsing of URL parameters from req.url.
CDynamic API routes can only have one dynamic segment per file path.
DOptional catch-all routes use the syntax [..param] without three dots.
Attempts:
2 left
💡 Hint
Think about how Next.js handles multiple path segments in dynamic routes.

Practice

(1/5)
1. What is the purpose of using square brackets in Next.js API route filenames like [id].js?
easy
A. To create dynamic API routes that capture parts of the URL
B. To mark the file as a static API route
C. To import external modules dynamically
D. To define middleware for the API route

Solution

  1. Step 1: Understand file naming in Next.js API routes

    Square brackets in filenames like [id].js indicate a dynamic segment in the URL path.
  2. Step 2: Recognize the effect on routing

    This allows the API route to capture the value in that part of the URL and use it inside the handler.
  3. Final Answer:

    To create dynamic API routes that capture parts of the URL -> Option A
  4. Quick Check:

    Dynamic routes use brackets = D [OK]
Hint: Square brackets in filenames mean dynamic URL parts [OK]
Common Mistakes:
  • Thinking brackets mark static routes
  • Confusing with dynamic imports
  • Assuming brackets define middleware
2. Which of the following is the correct way to access the dynamic parameter id inside a Next.js API route handler in [id].js?
easy
A. const id = req.params.id;
B. const id = req.body.id;
C. const id = req.query.id;
D. const id = req.route.id;

Solution

  1. Step 1: Recall how Next.js passes dynamic route params

    Next.js provides dynamic route parameters inside req.query in API routes.
  2. Step 2: Identify the correct syntax

    Accessing id is done by req.query.id, not req.params or others.
  3. Final Answer:

    const id = req.query.id; -> Option C
  4. Quick Check:

    Dynamic params in API routes = req.query [OK]
Hint: Use req.query to get dynamic route params in Next.js API [OK]
Common Mistakes:
  • Using req.params instead of req.query
  • Trying to get params from req.body
  • Using incorrect property like req.route
3. Given the API route file pages/api/user/[userId].js with this handler:
export default function handler(req, res) {
  const { userId } = req.query;
  res.status(200).json({ message: `User ID is ${userId}` });
}

What will be the JSON response when a client requests /api/user/42?
medium
A. 404 Not Found
B. {"message":"User ID is userId"}
C. {"message":"User ID is undefined"}
D. {"message":"User ID is 42"}

Solution

  1. Step 1: Extract dynamic parameter from URL

    The URL /api/user/42 matches the dynamic route [userId].js, so userId is "42".
  2. Step 2: Check the handler response

    The handler reads userId from req.query and returns JSON with message including that value.
  3. Final Answer:

    {"message":"User ID is 42"} -> Option D
  4. Quick Check:

    Dynamic param value used in response = A [OK]
Hint: Dynamic param in URL becomes req.query value [OK]
Common Mistakes:
  • Expecting literal string 'userId' instead of value
  • Assuming undefined if param missing
  • Thinking route returns 404 for dynamic routes
4. Consider this Next.js API route file named pages/api/product/[pid].js with the handler:
export default function handler(req, res) {
  const pid = req.query.pid;
  if (!pid) {
    res.status(400).json({ error: "Product ID missing" });
  }
  res.status(200).json({ productId: pid });
}

What is the bug in this code?
medium
A. It should use res.send instead of res.json
B. It does not return after sending 400 response, causing headers to be sent twice
C. It uses req.query.pid instead of req.params.pid
D. The file name should be [pid].ts instead of .js

Solution

  1. Step 1: Analyze the conditional response

    If pid is missing, the code sends a 400 response but does not stop execution.
  2. Step 2: Understand HTTP response behavior

    Without a return after sending 400, the code continues and tries to send a 200 response, causing an error.
  3. Final Answer:

    It does not return after sending 400 response, causing headers to be sent twice -> Option B
  4. Quick Check:

    Return after error response to avoid double send [OK]
Hint: Always return after sending error response in API handlers [OK]
Common Mistakes:
  • Ignoring missing return after res.status(400).json()
  • Confusing req.query with req.params
  • Thinking res.send is required over res.json
5. You want to create a Next.js API route that handles multiple dynamic segments like /api/order/[orderId]/item/[itemId].js. How should you structure the files and access both orderId and itemId inside the handler?
hard
A. Create nested folders: pages/api/order/[orderId]/item/[itemId].js and access via req.query.orderId and req.query.itemId
B. Create a single file pages/api/order-item.js and parse URL manually
C. Use query parameters like /api/order?orderId=1&itemId=2 and access req.query
D. Create a file pages/api/order/[orderId]-[itemId].js and access req.query as an array

Solution

  1. Step 1: Understand nested dynamic routes in Next.js

    Next.js supports nested folders with dynamic segments using square brackets for each segment.
  2. Step 2: Access multiple dynamic params in handler

    Both orderId and itemId appear in req.query as separate keys.
  3. Final Answer:

    Create nested folders: pages/api/order/[orderId]/item/[itemId].js and access via req.query.orderId and req.query.itemId -> Option A
  4. Quick Check:

    Nested folders with brackets = multiple params in req.query [OK]
Hint: Use nested folders with brackets for multiple dynamic params [OK]
Common Mistakes:
  • Trying to parse multiple params in one filename
  • Using query string instead of dynamic routes
  • Assuming req.query returns array for multiple params