Discover how a simple step can make your app's data flow smooth and bug-free!
Why Response modification in NextJS? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you fetch data from an API and want to change the response before showing it on your website. You try to do this by manually editing the data after it arrives, but it feels messy and slow.
Manually changing responses after fetching means extra code everywhere, repeated logic, and harder debugging. It's easy to forget to update all places, causing inconsistent data and bugs.
Next.js lets you modify responses centrally before sending them to the user. This keeps your code clean, consistent, and easy to maintain.
const data = await fetch(url).then(res => res.json());
data.items = data.items.map(item => ({ ...item, price: item.price * 0.9 }));export async function GET(request) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
data.items = data.items.map(item => ({ ...item, price: item.price * 0.9 }));
return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });
}You can control and customize all responses easily, making your app smarter and more reliable.
For example, an online store can apply discounts or hide sensitive info in API responses before showing products to customers.
Manual response changes are repetitive and error-prone.
Next.js lets you modify responses in one place cleanly.
This improves code quality and user experience.
Practice
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]
- Thinking headers change client-side state
- Confusing headers with URL routing
- Assuming headers update databases
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]
- Using res.headers as an object directly
- Calling non-existent methods like header() or addHeader()
- Confusing client-side and server-side APIs
export default function handler(req, res) {
res.status(404).json({ error: 'Not found' });
}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]
- Assuming default 200 status without checking code
- Confusing 404 with 500 or redirect codes
- Ignoring the status() method effect
export default function handler(req, res) {
res.status(200);
res.json({ message: 'Hello' });
res.setHeader('X-Test', 'value');
}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]
- Setting headers after res.json()
- Thinking res.status() sends response immediately
- Ignoring response flow order
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' });
}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]
- Setting cache headers when not authenticated
- Using public cache instead of private
- Returning 401 without setting headers when required
