Bird
Raised Fist0
NextJSframework~10 mins

Response modification in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Response modification
Request received
Run server action or API handler
Create initial Response object
Modify Response (headers, status, body)
Return modified Response
Client receives updated response
This flow shows how Next.js server code creates and changes a response before sending it back to the client.
Execution Sample
NextJS
import { NextResponse } from 'next/server'

export async function GET() {
  let res = new NextResponse('Hello Next.js')
  res.headers.set('X-Custom-Header', 'MyValue')
  res.status = 201
  return res
}
This code creates a response, changes its header and status, then returns it.
Execution Table
StepActionResponse StatusHeadersBodyResult
1Create Response with body 'Hello Next.js'200 (default){}'Hello Next.js'Response object created
2Set header 'X-Custom-Header' to 'MyValue'200{X-Custom-Header: 'MyValue'}'Hello Next.js'Header added
3Change status to 201201{X-Custom-Header: 'MyValue'}'Hello Next.js'Status updated
4Return modified Response201{X-Custom-Header: 'MyValue'}'Hello Next.js'Response sent to client
💡 Response returned after modifications with status 201 and custom header
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
res.statusundefined200200201201
res.headersempty{}{X-Custom-Header: 'MyValue'}{X-Custom-Header: 'MyValue'}{X-Custom-Header: 'MyValue'}
res.bodyundefined'Hello Next.js''Hello Next.js''Hello Next.js''Hello Next.js'
Key Moments - 2 Insights
Why does the response status start at 200 before we set it?
By default, the Response object has status 200 unless changed, as shown in step 1 and step 3 of the execution_table.
Can we add multiple headers after creating the Response?
Yes, headers can be added or changed anytime before returning the response, like in step 2 where a custom header is added.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response status after step 2?
A200
B201
Cdefault undefined
D400
💡 Hint
Check the 'Response Status' column at step 2 in the execution_table.
At which step is the custom header 'X-Custom-Header' added to the response?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Headers' column in the execution_table to see when the header appears.
If we did not change the status to 201 in step 3, what would be the final response status?
A201
B404
C200
D500
💡 Hint
Refer to the default status shown in step 1 of the execution_table.
Concept Snapshot
Next.js response modification:
- Create Response object with body
- Use res.headers.set() to add/change headers
- Use res.status = 201 to set HTTP status
- Return the modified Response
- Client receives updated status, headers, and body
Full Transcript
In Next.js, when a request arrives, the server runs a handler that creates a Response object. This Response starts with a default status of 200 and empty headers. You can add headers using res.headers.set() and change the status using res.status = 201. After making these changes, returning the Response sends it to the client with the updated status, headers, and body. This process lets you control exactly what the client receives.

Practice

(1/5)
1. In Next.js, what does modifying the response headers allow you to do?
easy
A. Change the React component state on the client
B. Control caching and security policies sent to the browser
C. Modify the URL path of the current page
D. Update the database directly from the response

Solution

  1. Step 1: Understand response headers role

    Response headers tell the browser how to handle the data, like caching or security rules.
  2. Step 2: Identify what modifying headers affects

    Changing headers controls browser behavior, not client state or URLs.
  3. Final Answer:

    Control caching and security policies sent to the browser -> Option B
  4. Quick 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
A. res.setHeader('X-Custom-Header', 'value')
B. res.headers['X-Custom-Header'] = 'value'
C. res.header('X-Custom-Header', 'value')
D. res.addHeader('X-Custom-Header', 'value')

Solution

  1. Step 1: Recall Next.js API response methods

    Next.js uses Node.js response objects where setHeader is the standard method.
  2. Step 2: Compare options to Node.js response API

    Only setHeader is a valid method; others are incorrect or undefined.
  3. Final Answer:

    res.setHeader('X-Custom-Header', 'value') -> Option A
  4. Quick 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
A. 500
B. 200
C. 404
D. 302

Solution

  1. Step 1: Identify the status method usage

    The code calls res.status(404) to set the HTTP status code to 404.
  2. Step 2: Understand the effect of res.status()

    This sets the response status code before sending JSON data.
  3. Final Answer:

    404 -> Option C
  4. Quick 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
A. res.json() cannot be used with status()
B. res.status(200) is missing a return statement
C. res.setHeader() should be called after res.json()
D. Headers must be set before sending the response body

Solution

  1. Step 1: Review response order rules

    Headers must be set before sending the response body with res.json().
  2. Step 2: Identify incorrect header setting

    res.setHeader() is called after res.json(), which is too late to modify headers.
  3. Final Answer:

    Headers must be set before sending the response body -> Option D
  4. Quick 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
A. if (isAuth) { res.setHeader('Cache-Control', 'private, max-age=3600'); }
B. if (!isAuth) { res.setHeader('Cache-Control', 'private, max-age=3600'); }
C. res.setHeader('Cache-Control', 'public, max-age=3600');
D. res.status(401).json({ error: 'Unauthorized' });

Solution

  1. Step 1: Understand the condition for caching

    Caching headers should be added only if the user is authenticated (isAuth is true).
  2. 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.
  3. Final Answer:

    if (isAuth) { res.setHeader('Cache-Control', 'private, max-age=3600'); } -> Option A
  4. Quick 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