Bird
Raised Fist0
NextJSframework~20 mins

Request parsing in route handlers 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
🎖️
Next.js Request Parsing 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 Next.js route handler when receiving a POST request with JSON body?

Consider this Next.js API route handler in the app/api/data/route.js file:

export async function POST(request) {
  const data = await request.json();
  return new Response(JSON.stringify({ received: data.message }), {
    headers: { 'Content-Type': 'application/json' }
  });
}

If the client sends a POST request with JSON body {"message": "hello"}, what will be the response body?

NextJS
export async function POST(request) {
  const data = await request.json();
  return new Response(JSON.stringify({ received: data.message }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
A{"message":"hello"}
B{"received":null}
C{"received":"hello"}
DSyntaxError
Attempts:
2 left
💡 Hint

Remember that request.json() parses the JSON body and returns the object.

📝 Syntax
intermediate
2:00remaining
Which option correctly parses URL query parameters in a Next.js route handler?

Given a GET request to /api/items?category=books&sort=asc, which code snippet correctly extracts the category and sort query parameters inside a Next.js route handler?

NextJS
export async function GET(request) {
  // extract query params here
}
A
const query = JSON.parse(request.url);
const category = query.category;
const sort = query.sort;
Bconst { category, sort } = request.query;
C
const params = request.params;
const category = params.category;
const sort = params.sort;
D
const url = new URL(request.url);
const category = url.searchParams.get('category');
const sort = url.searchParams.get('sort');
Attempts:
2 left
💡 Hint

Think about how to get query parameters from the full URL string.

🔧 Debug
advanced
2:00remaining
Why does this Next.js route handler throw an error when parsing JSON body?

Examine this Next.js POST route handler:

export async function POST(request) {
  const data = request.json();
  return new Response(JSON.stringify({ name: data.name }), {
    headers: { 'Content-Type': 'application/json' }
  });
}

What is the cause of the error?

NextJS
export async function POST(request) {
  const data = request.json();
  return new Response(JSON.stringify({ name: data.name }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
AMissing await before request.json(), so data is a Promise, not the parsed object
Brequest.json() is not a function on the request object
CResponse constructor requires a string, but JSON.stringify returns an object
DHeaders object is missing required 'Accept' header
Attempts:
2 left
💡 Hint

Check if the JSON parsing is asynchronous and how the result is used.

state_output
advanced
2:00remaining
What is the response when parsing form data in a Next.js POST route handler?

Given this Next.js route handler:

export async function POST(request) {
  const formData = await request.formData();
  const username = formData.get('username');
  return new Response(`Hello, ${username}!`);
}

If the client sends a form with username=Alice, what is the response text?

NextJS
export async function POST(request) {
  const formData = await request.formData();
  const username = formData.get('username');
  return new Response(`Hello, ${username}!`);
}
AHello, undefined!
BHello, Alice!
CSyntaxError
DHello, [object FormData]!
Attempts:
2 left
💡 Hint

Remember how to extract values from form data.

🧠 Conceptual
expert
2:00remaining
Which statement about Next.js route handler request parsing is TRUE?

Choose the correct statement about parsing requests in Next.js route handlers.

AThe <code>request.json()</code> method returns a Promise that resolves to the parsed JSON object from the request body.
BThe <code>request.body</code> property contains the parsed JSON object directly without needing to await anything.
CTo parse URL query parameters, you can directly access <code>request.query</code> in the route handler.
DThe <code>request.formData()</code> method returns a synchronous object representing form fields.
Attempts:
2 left
💡 Hint

Think about asynchronous parsing methods and standard Web API request properties.

Practice

(1/5)
1. In Next.js route handlers, which method is used to parse JSON data from a POST request's body?
easy
A. request.json()
B. request.text()
C. request.formData()
D. request.body()

Solution

  1. Step 1: Understand the data type sent in the request

    JSON data requires parsing as JSON, not as text or form data.
  2. Step 2: Identify the correct parsing method in Next.js route handlers

    The request.json() method parses the request body as JSON.
  3. Final Answer:

    request.json() -> Option A
  4. Quick Check:

    JSON data parsing = request.json() [OK]
Hint: Use request.json() to parse JSON bodies in Next.js [OK]
Common Mistakes:
  • Using request.text() for JSON data
  • Trying to use request.body() which is not a method
  • Using request.formData() for JSON instead of form data
2. Which of the following is the correct syntax to parse form data in a Next.js route handler?
easy
A. const data = await request.json();
B. const data = await request.formData();
C. const data = request.formData();
D. const data = request.json();

Solution

  1. Step 1: Recognize that form data parsing is asynchronous

    Parsing form data requires awaiting the promise returned by request.formData().
  2. Step 2: Identify the correct syntax with await

    The correct syntax is const data = await request.formData(); to properly parse form data.
  3. Final Answer:

    const data = await request.formData(); -> Option B
  4. Quick Check:

    Form data parsing requires await request.formData() [OK]
Hint: Always await request.formData() to parse form data [OK]
Common Mistakes:
  • Not using await with request.formData()
  • Using request.json() to parse form data
  • Calling request.formData() without await
3. Given this Next.js route handler code snippet, what will be logged if the request body contains JSON {"name":"Alice"}?
export async function POST(request) {
  const data = await request.json();
  console.log(data.name);
  return new Response('OK');
}
medium
A. "Alice"
B. undefined
C. Error: Cannot read property 'name' of undefined
D. "{\"name\":\"Alice\"}"

Solution

  1. Step 1: Parse the JSON body using request.json()

    The request.json() method converts the JSON string into a JavaScript object.
  2. Step 2: Access the 'name' property from the parsed object

    Since the JSON contains {"name":"Alice"}, data.name will be "Alice".
  3. Final Answer:

    "Alice" -> Option A
  4. Quick Check:

    Parsed JSON object property access = "Alice" [OK]
Hint: request.json() returns object; access properties normally [OK]
Common Mistakes:
  • Expecting raw JSON string instead of parsed object
  • Not awaiting request.json() causing undefined
  • Trying to access property before parsing
4. Identify the error in this Next.js route handler code for parsing JSON:
export async function POST(request) {
  const data = request.json();
  return new Response(JSON.stringify(data));
}
medium
A. request.json() is not a valid method
B. Cannot use JSON.stringify on data
C. Missing await before request.json()
D. Response constructor requires status code

Solution

  1. Step 1: Check how request.json() is called

    The request.json() method returns a promise and must be awaited.
  2. Step 2: Identify missing await causing data to be a promise

    Without await, data is a promise, not the parsed object, causing incorrect response.
  3. Final Answer:

    Missing await before request.json() -> Option C
  4. Quick Check:

    Always await request.json() to get parsed data [OK]
Hint: Always await async parsing methods like request.json() [OK]
Common Mistakes:
  • Forgetting await before request.json()
  • Assuming request.json() returns data synchronously
  • Misunderstanding promise behavior in async functions
5. You want to handle a POST request in Next.js that can accept either JSON or form data. Which approach correctly parses the request body depending on its Content-Type header?
hard
A. Always use await request.json() regardless of Content-Type
B. Use await request.formData() for all POST requests
C. Use await request.text() and manually parse JSON or form data
D. Check request.headers.get('content-type') and use await request.json() for 'application/json', await request.formData() for 'multipart/form-data'

Solution

  1. Step 1: Identify the Content-Type header to determine data format

    The Content-Type header tells if the body is JSON or form data.
  2. Step 2: Use conditional parsing based on Content-Type

    Use await request.json() for 'application/json' and await request.formData() for 'multipart/form-data' or 'application/x-www-form-urlencoded'.
  3. Final Answer:

    Check content-type and parse accordingly with request.json() or request.formData() -> Option D
  4. Quick Check:

    Parse based on Content-Type header [OK]
Hint: Check Content-Type header to choose JSON or formData parsing [OK]
Common Mistakes:
  • Parsing all requests as JSON ignoring Content-Type
  • Parsing all requests as formData ignoring Content-Type
  • Not checking Content-Type before parsing