Bird
Raised Fist0
NextJSframework~20 mins

Why API routes serve backend logic in NextJS - Challenge Your Understanding

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
🎖️
API Route Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1: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?
ABecause API routes are compiled into static HTML files.
BBecause API routes need to securely access databases and environment variables, which should not be exposed to the client.
CBecause API routes are only used to render UI components.
DBecause API routes are faster when run on the client browser.
Attempts:
2 left
💡 Hint
Think about what kind of data should stay secret and where it should be processed.
component_behavior
intermediate
1: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?
AIt executes server-side code, processes the request, and sends back a JSON response.
BIt directly updates the client UI without contacting the server.
CIt reloads the entire Next.js page on the client.
DIt compiles new React components on the client.
Attempts:
2 left
💡 Hint
Think about what an API usually does when called.
📝 Syntax
advanced
2: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?
Afunction handler(req, res) { res.send('Hello from API') } export default handler
Bexport function handler(req, res) { return { message: 'Hello from API' } }
Cexport default async function handler(req) { res.json({ message: 'Hello' }) }
Dexport default function handler(req, res) { res.status(200).json({ message: 'Hello from API' }) }
Attempts:
2 left
💡 Hint
Check how the response object is used to send JSON and the function export style.
🔧 Debug
advanced
2:00remaining
Why is this Next.js API route not recommended?
Consider this API route code:
export default function handler(req, res) { res.json({ message: 'Hi' }) }

Why is this not the recommended way to write it?
ABecause res.json is called without setting a status code first.
BBecause the function is missing the async keyword.
CBecause res.json is not a function on the response object in Next.js API routes.
DBecause the function does not return a value.
Attempts:
2 left
💡 Hint
Next.js recommends explicitly setting the status code before sending JSON.
state_output
expert
2:30remaining
What is the output of this Next.js API route when called with a POST request?
Given this API route code:
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?
AAn empty response with HTTP status 200
B{"error":"Method not allowed"} with HTTP status 405
C{"success":true} with HTTP status 201
DA JSON parse error because the response is delayed
Attempts:
2 left
💡 Hint
Look at the method check and the response sent for POST requests.

Practice

(1/5)
1. Why do Next.js API routes serve backend logic in a Next.js project?
easy
A. They are used only to style the frontend components.
B. They replace the need for React components in the app.
C. They allow running server-side code like data fetching and secure operations within the same project.
D. They automatically generate static HTML pages.

Solution

  1. Step 1: Understand the role of API routes

    API routes in Next.js let you write backend code inside your project to handle tasks like fetching data or processing forms.
  2. Step 2: Identify what backend logic means

    Backend logic means code that runs on the server, such as secure operations or database access, which API routes enable.
  3. Final Answer:

    They allow running server-side code like data fetching and secure operations within the same project. -> Option C
  4. Quick Check:

    API routes = backend logic handler [OK]
Hint: API routes run server code inside Next.js projects [OK]
Common Mistakes:
  • Thinking API routes style frontend
  • Confusing API routes with React components
  • Believing API routes generate static pages
2. Which of the following is the correct way to define a Next.js API route handler?
easy
A. const handler = () =>

Hello

B. function handler() { return
Hello
}
C. export function handler() { console.log('Hello') }
D. export default function handler(req, res) { res.status(200).json({ message: 'Hello' }) }

Solution

  1. Step 1: Recognize API route syntax

    Next.js API routes export a default function that receives req and res to handle requests and responses.
  2. Step 2: Check each option

    export default function handler(req, res) { res.status(200).json({ message: 'Hello' }) } correctly exports a default function with req and res and sends a JSON response. Others either lack export default or return JSX, which is incorrect for API routes.
  3. Final Answer:

    export default function handler(req, res) { res.status(200).json({ message: 'Hello' }) } -> Option D
  4. Quick Check:

    API route = export default function(req, res) [OK]
Hint: API routes export default function with req, res [OK]
Common Mistakes:
  • Returning JSX instead of JSON
  • Not exporting default function
  • Missing req and res parameters
3. Given this Next.js API route code, what will be the JSON response when a GET request is made?
export default function handler(req, res) {
  if (req.method === 'GET') {
    res.status(200).json({ success: true, data: 'Hello World' })
  } else {
    res.status(405).json({ error: 'Method Not Allowed' })
  }
}
medium
A. {"error":"Method Not Allowed"}
B. {"success":true,"data":"Hello World"}
C. An HTML page with 'Hello World'
D. A runtime error occurs

Solution

  1. Step 1: Check request method handling

    The handler checks if the request method is 'GET'. If yes, it sends a 200 status with JSON containing success and data.
  2. Step 2: Determine response for GET request

    Since the request is GET, the response will be JSON: {"success":true,"data":"Hello World"} with status 200.
  3. Final Answer:

    {"success":true,"data":"Hello World"} -> Option B
  4. Quick Check:

    GET request returns success JSON [OK]
Hint: GET method returns success JSON, others error [OK]
Common Mistakes:
  • Assuming all methods return success
  • Expecting HTML instead of JSON
  • Confusing status codes
4. Identify the error in this Next.js API route code:
export default function handler(req, res) {
  if (req.method === 'POST') {
    res.json({ message: 'Data received' })
  } else {
    res.status(405).json({ error: 'Method Not Allowed' })
  }
}
medium
A. No error, code is correct
B. Using res.json instead of res.send
C. Missing status code in the POST response
D. Missing req parameter

Solution

  1. Step 1: Review response methods

    In Next.js API routes, res.json() sends a JSON response with a default status code of 200, which is correct and functional.
  2. Step 2: Check each option

    The code properly handles POST with res.json() (200 OK implied) and other methods with 405 error. There are no syntax errors, runtime issues, or missing parameters. res.json is the right method for JSON responses.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    res.json defaults to 200, code runs correctly [OK]
Hint: res.json() defaults to status 200 [OK]
Common Mistakes:
  • Thinking missing explicit status code is an error
  • Confusing res.json and res.send
  • Forgetting req or res parameters
5. You want to create a Next.js API route that securely processes a form submission only if the request method is POST and the request body contains a non-empty 'email' field. Which code snippet correctly implements this logic?
hard
A. export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } }
B. export default function handler(req, res) { if (req.method === 'GET' || !req.body.email) { res.status(200).json({ message: 'Form processed' }) } else { res.status(400).json({ error: 'Invalid request' }) } }
C. export default function handler(req, res) { if (req.method === 'POST') { res.status(200).json({ message: 'Form processed' }) } else { res.status(400).json({ error: 'Invalid request' }) } }
D. export default function handler(req, res) { res.status(200).json({ message: 'Form processed' }) }

Solution

  1. Step 1: Check method and body content

    The handler must verify the request method is POST and that the 'email' field exists and is not empty in the request body.
  2. Step 2: Validate each option

    export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } correctly checks both conditions and returns a success message with the email. Others either check wrong methods, ignore the email field, or always respond without validation.
  3. Final Answer:

    export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } -> Option A
  4. Quick Check:

    POST + email check = export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } [OK]
Hint: Check method and required fields before responding [OK]
Common Mistakes:
  • Not checking request method
  • Ignoring required fields in body
  • Always returning success without validation