Response modification lets you change what the server sends back to the browser. This helps you add headers, change status codes, or modify the content before the user sees it.
Response modification in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
export async function GET(request) { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=3600' } }); }
You create a new Response object to modify what is sent back.
Headers, status, and body can all be changed in the Response constructor.
Examples
NextJS
export async function GET() { return new Response('Hello World', { status: 200, headers: { 'Content-Type': 'text/plain' } }); }
NextJS
export async function GET() { return new Response(null, { status: 404, statusText: 'Not Found' }); }
NextJS
export async function GET() { const headers = new Headers(); headers.set('Set-Cookie', 'user=123; Path=/; HttpOnly'); return new Response('Cookie set', { status: 200, headers }); }
Sample Program
This Next.js API route fetches data from an external API, then modifies the response by adding a custom header before sending it back to the client.
NextJS
export async function GET() { // Fetch data from external API const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); // Modify response: add custom header and change status return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyHeaderValue' } }); }
Important Notes
Always set the correct Content-Type header to match your response body.
You can create and modify Headers objects for more control.
Remember to handle errors when fetching or modifying responses.
Summary
Response modification lets you control what the server sends back.
You can change headers, status codes, and the response body.
This helps improve security, caching, and user experience.
Practice
1. In Next.js, what does modifying the response headers allow you to do?
easy
Solution
Step 1: Understand response headers role
Response headers tell the browser how to handle the data, like caching or security rules.Step 2: Identify what modifying headers affects
Changing headers controls browser behavior, not client state or URLs.Final Answer:
Control caching and security policies sent to the browser -> Option BQuick Check:
Headers control browser policies = A [OK]
Hint: Headers control browser rules like caching and security [OK]
Common Mistakes:
- Thinking headers change client-side state
- Confusing headers with URL routing
- Assuming headers update databases
2. Which of the following is the correct way to set a custom header in a Next.js API route response?
easy
Solution
Step 1: Recall Next.js API response methods
Next.js uses Node.js response objects where setHeader is the standard method.Step 2: Compare options to Node.js response API
Only setHeader is a valid method; others are incorrect or undefined.Final Answer:
res.setHeader('X-Custom-Header', 'value') -> Option AQuick Check:
Use setHeader to set headers = D [OK]
Hint: Use res.setHeader() to set headers in Next.js API [OK]
Common Mistakes:
- Using res.headers as an object directly
- Calling non-existent methods like header() or addHeader()
- Confusing client-side and server-side APIs
3. What will be the HTTP status code of this Next.js API response?
export default function handler(req, res) {
res.status(404).json({ error: 'Not found' });
}medium
Solution
Step 1: Identify the status method usage
The code calls res.status(404) to set the HTTP status code to 404.Step 2: Understand the effect of res.status()
This sets the response status code before sending JSON data.Final Answer:
404 -> Option CQuick Check:
res.status(404) sets status code 404 [OK]
Hint: res.status(code) sets HTTP status code [OK]
Common Mistakes:
- Assuming default 200 status without checking code
- Confusing 404 with 500 or redirect codes
- Ignoring the status() method effect
4. Identify the error in this Next.js API route code that tries to modify the response:
export default function handler(req, res) {
res.status(200);
res.json({ message: 'Hello' });
res.setHeader('X-Test', 'value');
}medium
Solution
Step 1: Review response order rules
Headers must be set before sending the response body with res.json().Step 2: Identify incorrect header setting
res.setHeader() is called after res.json(), which is too late to modify headers.Final Answer:
Headers must be set before sending the response body -> Option DQuick Check:
Set headers before body = C [OK]
Hint: Set headers before sending response body [OK]
Common Mistakes:
- Setting headers after res.json()
- Thinking res.status() sends response immediately
- Ignoring response flow order
5. You want to add caching headers to a Next.js API response only if the user is authenticated. Which code snippet correctly modifies the response based on this condition?
export default function handler(req, res) {
const isAuth = req.headers.authorization === 'secret-token';
// Add caching headers only if authenticated
???
res.status(200).json({ data: 'Secure data' });
}hard
Solution
Step 1: Understand the condition for caching
Caching headers should be added only if the user is authenticated (isAuth is true).Step 2: Choose the correct conditional header setting
if (isAuth) { res.setHeader('Cache-Control', 'private, max-age=3600'); } sets caching headers only when isAuth is true, matching the requirement.Final Answer:
if (isAuth) { res.setHeader('Cache-Control', 'private, max-age=3600'); } -> Option AQuick Check:
Set cache header only if authenticated = B [OK]
Hint: Use if (isAuth) to conditionally set headers [OK]
Common Mistakes:
- Setting cache headers when not authenticated
- Using public cache instead of private
- Returning 401 without setting headers when required
