0
0
NextJSframework~10 mins

Request parsing in route handlers 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 parse JSON body from the request in a Next.js route handler.

NextJS
export async function POST(request) {
  const data = await request.[1]();
  return new Response(JSON.stringify(data));
}
Drag options to blanks, or click blank then click option'
Atext
Bblob
CformData
Djson
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.text() instead of request.json() causes the body to be read as plain text.
Using request.formData() when the body is JSON will cause errors.
2fill in blank
medium

Complete the code to extract a query parameter named 'id' from the URL in a Next.js route handler.

NextJS
export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const id = searchParams.[1]('id');
  return new Response(id);
}
Drag options to blanks, or click blank then click option'
Aget
Bhas
CgetAll
Dset
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'has' returns a boolean, not the value.
Using 'getAll' returns an array, not a single value.
3fill in blank
hard

Fix the error in the code to correctly parse JSON body and handle missing fields in a Next.js POST route handler.

NextJS
export async function POST(request) {
  const data = await request.[1]();
  if (!data.name) {
    return new Response('Missing name', { status: 400 });
  }
  return new Response(`Hello, ${data.name}`);
}
Drag options to blanks, or click blank then click option'
Atext
Bjson
CformData
Dblob
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.text() and then trying to access properties on the string causes errors.
Using request.formData() when expecting JSON data.
4fill in blank
hard

Fill both blanks to parse JSON body and extract a nested field 'user.email' in a Next.js POST route handler.

NextJS
export async function POST(request) {
  const data = await request.[1]();
  const email = data.user?.[2];
  return new Response(email || 'No email');
}
Drag options to blanks, or click blank then click option'
Ajson
Btext
Cemail
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.text() instead of request.json() causes data to be a string.
Accessing a wrong property name instead of 'email'.
5fill in blank
hard

Fill all three blanks to parse JSON body, extract 'username' and 'age', and check if age is over 18 in a Next.js POST route handler.

NextJS
export async function POST(request) {
  const data = await request.[1]();
  const username = data.[2];
  if (data.[3] > 18) {
    return new Response(`Welcome, ${username}`);
  }
  return new Response('Too young', { status: 403 });
}
Drag options to blanks, or click blank then click option'
Ajson
Busername
Cage
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.text() instead of request.json() causes errors.
Mixing up property names or misspelling them.