0
0
NextJSframework~10 mins

Route handlers (route.ts) 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 export a GET route handler that returns a JSON response.

NextJS
export async function GET(req: Request) {
  return new Response(JSON.stringify({ message: [1] }), {
    headers: { 'Content-Type': 'application/json' },
  });
}
Drag options to blanks, or click blank then click option'
A"Hello from GET"
BHello from GET
C'Hello from GET'
DGET
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string value inside JSON.stringify.
Returning a plain string instead of a JSON string.
2fill in blank
medium

Complete the code to parse JSON from the POST request body.

NextJS
export async function POST(req: Request) {
  const data = await req.[1]();
  return new Response(JSON.stringify({ received: data }), {
    headers: { 'Content-Type': 'application/json' },
  });
}
Drag options to blanks, or click blank then click option'
Ajson
BformData
Ctext
DarrayBuffer
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.text() and then manually parsing JSON.
Using req.formData() which is for form submissions.
3fill in blank
hard

Fix the error in the route handler by correctly setting the status code in the Response constructor.

NextJS
export async function DELETE(req: Request) {
  return new Response(null, { status: [1] });
}
Drag options to blanks, or click blank then click option'
A200
B204
C404
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 status code but returning null body.
Using error codes like 404 or 500 for successful deletes.
4fill in blank
hard

Fill both blanks to create a route handler that reads a query parameter 'id' from the URL and returns it in JSON.

NextJS
export async function GET(req: Request) {
  const url = new URL(req.url);
  const id = url.[1].get('[2]');
  return new Response(JSON.stringify({ id }), {
    headers: { 'Content-Type': 'application/json' },
  });
}
Drag options to blanks, or click blank then click option'
AsearchParams
Bid
Cquery
DqueryParams
Attempts:
3 left
💡 Hint
Common Mistakes
Using url.params instead of url.searchParams.
Using wrong parameter name.
5fill in blank
hard

Fill all three blanks to create a POST route handler that reads JSON body, extracts 'name', and returns a greeting message.

NextJS
export async function POST(req: Request) {
  const data = await req.[1]();
  const name = data.[2] ?? 'Guest';
  return new Response(JSON.stringify({ message: `Hello, [3]!` }), {
    headers: { 'Content-Type': 'application/json' },
  });
}
Drag options to blanks, or click blank then click option'
Ajson
Bname
C${name}
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.text() instead of req.json().
Accessing data['name'] incorrectly.
Not using template literals for string interpolation.