Consider this Next.js API route handler that modifies the response before sending:
export async function GET() {
const res = new Response(JSON.stringify({ message: 'Hello' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
res.headers.set('X-Custom-Header', 'TestValue');
return res;
}What will the client receive in the response headers?
export async function GET() { const res = new Response(JSON.stringify({ message: 'Hello' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); res.headers.set('X-Custom-Header', 'TestValue'); return res; }
Think about how the Response object headers can be modified before returning.
The Response object allows header modification before returning. Setting X-Custom-Header adds it to the response headers along with the original Content-Type.
Given this Next.js API route snippet, which option correctly changes the response status to 404?
export async function GET() {
const res = new Response('Not Found');
// Modify status here
return res;
}export async function GET() { const res = new Response('Not Found'); // Modify status here return res; }
Remember that Response objects are immutable for status after creation.
The Response object status cannot be changed after creation. You must create a new Response with the desired status.
Examine this Next.js API route code:
export async function GET() {
const res = new Response('OK');
res.headers.append('Set-Cookie', 'token=abc123; HttpOnly');
return res;
}Why might the cookie not be set in the browser?
export async function GET() { const res = new Response('OK'); res.headers.append('Set-Cookie', 'token=abc123; HttpOnly'); return res; }
Consider when headers can be set on the Response object.
The Response headers are immutable after creation. To set cookies, you must include the 'Set-Cookie' header in the Response constructor options.
Given this Next.js middleware code:
import { NextResponse } from 'next/server';
export function middleware(request) {
const response = NextResponse.next();
response.headers.set('X-Middleware', 'Active');
return response;
}What will the client receive in the response headers?
import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); response.headers.set('X-Middleware', 'Active'); return response; }
Think about how NextResponse.next() allows header modification.
NextResponse.next() returns a mutable response object. You can set headers on it before returning, so the client receives the custom header.
Choose the correct statement about modifying responses in Next.js App Router server actions or route handlers.
Think about immutability of Response objects in web standards.
Response objects follow web standards and are immutable after creation. To modify status or headers, you must create a new Response object with the desired properties.