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?
export async function POST(request) { const data = await request.json(); return new Response(JSON.stringify({ received: data.message }), { headers: { 'Content-Type': 'application/json' } }); }
Remember that request.json() parses the JSON body and returns the object.
The handler reads the JSON body, extracts the message property, and returns it inside a new JSON object with key received.
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?
export async function GET(request) { // extract query params here }
Think about how to get query parameters from the full URL string.
In Next.js route handlers, request.url is a full URL string. Creating a URL object allows access to searchParams to get query parameters.
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?
export async function POST(request) { const data = request.json(); return new Response(JSON.stringify({ name: data.name }), { headers: { 'Content-Type': 'application/json' } }); }
Check if the JSON parsing is asynchronous and how the result is used.
request.json() returns a Promise. Without await, data is a Promise, so accessing data.name causes an error.
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?
export async function POST(request) { const formData = await request.formData(); const username = formData.get('username'); return new Response(`Hello, ${username}!`); }
Remember how to extract values from form data.
formData.get('username') returns the string value for the key 'username'. The response includes that value in the greeting.
Choose the correct statement about parsing requests in Next.js route handlers.
Think about asynchronous parsing methods and standard Web API request properties.
request.json() is asynchronous and returns a Promise resolving to the parsed JSON. Other options are incorrect because request.body is a stream, request.query does not exist, and formData() returns a Promise.