Challenge - 5 Problems
API Route Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate1:30remaining
Why do Next.js API routes run on the server?
In Next.js, API routes are used to handle backend logic. Why do these routes run on the server instead of the client?
Attempts:
2 left
💡 Hint
Think about what kind of data should stay secret and where it should be processed.
✗ Incorrect
API routes run on the server to keep sensitive data safe, like database credentials and secret keys. Running them on the client would expose this information.
❓ component_behavior
intermediate1:30remaining
What happens when a Next.js API route is called?
When a client calls a Next.js API route, what is the typical behavior of that route?
Attempts:
2 left
💡 Hint
Think about what an API usually does when called.
✗ Incorrect
API routes run server-side code to handle requests and send back data, often in JSON format, without reloading the page.
📝 Syntax
advanced2:00remaining
Identify the correct Next.js API route handler syntax
Which option shows the correct way to define a Next.js API route handler that returns a JSON message?
Attempts:
2 left
💡 Hint
Check how the response object is used to send JSON and the function export style.
✗ Incorrect
The correct syntax exports a default function with (req, res) parameters and uses res.status().json() to send JSON.
🔧 Debug
advanced2:00remaining
Why is this Next.js API route not recommended?
Consider this API route code:
Why is this not the recommended way to write it?
export default function handler(req, res) { res.json({ message: 'Hi' }) }Why is this not the recommended way to write it?
Attempts:
2 left
💡 Hint
Next.js recommends explicitly setting the status code before sending JSON.
✗ Incorrect
Although res.json() works and defaults to status 200, the recommended syntax uses res.status(200).json() to explicitly set the status code.
❓ state_output
expert2:30remaining
What is the output of this Next.js API route when called with a POST request?
Given this API route code:
What will the client receive if it sends a POST request?
export default async function handler(req, res) {
if (req.method === 'POST') {
const data = await new Promise(resolve => setTimeout(() => resolve({ success: true }), 100))
res.status(201).json(data)
} else {
res.status(405).json({ error: 'Method not allowed' })
}
}What will the client receive if it sends a POST request?
Attempts:
2 left
💡 Hint
Look at the method check and the response sent for POST requests.
✗ Incorrect
The route waits 100ms, then sends a JSON response with { success: true } and status 201 for POST requests.