Bird
Raised Fist0
Node.jsframework~10 mins

Setting response headers in Node.js - 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 - Setting response headers
Start HTTP request
Create response object
Set response headers
Write response body
Send response to client
End request handling
This flow shows how a Node.js server sets headers on the response before sending it back to the client.
Execution Sample
Node.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('X-Custom-Header', 'MyValue');
  res.end('Hello World');
});
server.listen(3000);
This code creates a simple HTTP server that sets two headers before sending a plain text response.
Execution Table
StepActionHeader SetHeader ValueResponse State
1Start request handling--No headers set
2Set headerContent-Typetext/plainHeaders: {Content-Type: text/plain}
3Set headerX-Custom-HeaderMyValueHeaders: {Content-Type: text/plain, X-Custom-Header: MyValue}
4Write and send response--Response sent with headers and body
5End request handling--Request complete
💡 Response sent and request handling finished
Variable Tracker
VariableStartAfter Step 2After Step 3Final
res.headers{}{Content-Type: 'text/plain'}{Content-Type: 'text/plain', X-Custom-Header: 'MyValue'}{Content-Type: 'text/plain', X-Custom-Header: 'MyValue'}
Key Moments - 2 Insights
Why do we set headers before calling res.end()?
Headers must be set before sending the response body because once res.end() is called, the response is sent and headers cannot be changed. See execution_table steps 3 and 4.
What happens if we set the same header twice?
Setting the same header twice overwrites the previous value. Only the last value is sent. This is why each header key appears once in res.headers as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what headers are set after step 3?
A{}
B{Content-Type: 'text/html'}
C{Content-Type: 'text/plain', X-Custom-Header: 'MyValue'}
D{X-Custom-Header: 'MyValue'}
💡 Hint
Check the 'Header Set' and 'Response State' columns at step 3 in the execution_table.
At which step is the response body sent to the client?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look for the action 'Write and send response' in the execution_table.
If we set a header after calling res.end(), what happens?
AThe header is added successfully
BThe header is ignored because response is already sent
CThe header overwrites previous headers
DThe server crashes
💡 Hint
Refer to key_moments about why headers must be set before res.end() and execution_table steps 4 and 5.
Concept Snapshot
Setting response headers in Node.js:
- Use res.setHeader(name, value) before res.end()
- Headers define metadata like content type
- Setting headers after res.end() has no effect
- Overwriting headers replaces previous values
- Always set all headers before sending response body
Full Transcript
This example shows how a Node.js HTTP server sets response headers before sending the response. The server starts handling a request, sets the Content-Type and a custom header, then sends the response body with res.end(). Headers must be set before calling res.end() because after that the response is sent and headers cannot be changed. Setting the same header twice overwrites the previous value. The execution table tracks each step, showing headers added and when the response is sent. The variable tracker shows how the headers object changes after each setHeader call. This helps beginners understand the order and effect of setting headers in Node.js.

Practice

(1/5)
1. What is the purpose of setting response headers in a Node.js server?
easy
A. To execute JavaScript code on the server
B. To provide the browser with important information about the response
C. To store data permanently on the server
D. To create new files on the server

Solution

  1. Step 1: Understand what response headers do

    Response headers tell the browser details about the response, like content type or caching rules.
  2. Step 2: Identify the correct purpose

    Only To provide the browser with important information about the response describes this role correctly; other options describe unrelated server tasks.
  3. Final Answer:

    To provide the browser with important information about the response -> Option B
  4. Quick Check:

    Response headers = browser info [OK]
Hint: Headers tell browser about response before body [OK]
Common Mistakes:
  • Thinking headers run code on server
  • Confusing headers with server storage
  • Believing headers create files
2. Which of the following is the correct syntax to set a response header named Content-Type to application/json in Node.js?
easy
A. response.setHeader('Content-Type', 'application/json');
B. response.header('Content-Type', 'application/json');
C. response.set('Content-Type', 'application/json');
D. response.addHeader('Content-Type', 'application/json');

Solution

  1. Step 1: Recall Node.js method for setting headers

    Node.js uses response.setHeader(name, value) to set headers.
  2. Step 2: Match syntax with options

    Only response.setHeader('Content-Type', 'application/json'); uses setHeader correctly; others use incorrect method names.
  3. Final Answer:

    response.setHeader('Content-Type', 'application/json'); -> Option A
  4. Quick Check:

    Use setHeader(name, value) [OK]
Hint: Use setHeader method exactly as shown [OK]
Common Mistakes:
  • Using header() instead of setHeader()
  • Using set() or addHeader() which don't exist
  • Wrong method name casing
3. What will be the value of the Content-Type header sent to the client after running this code snippet?
const http = require('http');
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Content-Type', 'application/json');
  res.end('{}');
});
server.listen(3000);
medium
A. 'text/html'
B. Both 'text/html' and 'application/json'
C. No Content-Type header is sent
D. 'application/json'

Solution

  1. Step 1: Understand header overwriting behavior

    Setting the same header twice overwrites the previous value in Node.js.
  2. Step 2: Identify final header value

    The second setHeader call sets 'Content-Type' to 'application/json', replacing 'text/html'.
  3. Final Answer:

    'application/json' -> Option D
  4. Quick Check:

    Last setHeader call wins [OK]
Hint: Last setHeader call overwrites previous [OK]
Common Mistakes:
  • Thinking both headers are sent
  • Assuming first header stays
  • Believing no header is sent
4. Identify the error in this Node.js code that tries to set a response header:
const http = require('http');
const server = http.createServer((req, res) => {
  res.write('Hello');
  res.setHeader('Content-Type', 'text/plain');
  res.end();
});
server.listen(3000);
medium
A. res.end() is missing a parameter
B. The method setHeader does not exist on res
C. Headers must be set before writing the response body
D. The server.listen port number is invalid

Solution

  1. Step 1: Check order of header setting and response writing

    Headers must be set before sending any part of the response body.
  2. Step 2: Identify the error in code order

    res.write('Hello') sends body first, so setHeader after it causes error.
  3. Final Answer:

    Headers must be set before writing the response body -> Option C
  4. Quick Check:

    Set headers before body [OK]
Hint: Set headers before any res.write or res.end [OK]
Common Mistakes:
  • Setting headers after writing body
  • Thinking setHeader is invalid method
  • Assuming res.end needs data always
5. You want to set multiple headers including Content-Type as application/json and Cache-Control as no-cache in a Node.js server. Which code snippet correctly sets both headers before sending the response?
hard
A. res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' }); res.end(JSON.stringify(data));
B. res.end(JSON.stringify(data)); res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'no-cache');
C. res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(data)); res.setHeader('Cache-Control', 'no-cache');
D. res.setHeader({'Content-Type': 'application/json', 'Cache-Control': 'no-cache'}); res.end(JSON.stringify(data));

Solution

  1. Step 1: Understand setting multiple headers at once

    writeHead allows setting status and multiple headers before sending response.
  2. Step 2: Check order and correctness

    res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' }); res.end(JSON.stringify(data)); sets both headers before res.end, correctly using writeHead.
  3. Step 3: Identify errors in other options

    res.setHeader({'Content-Type': 'application/json', 'Cache-Control': 'no-cache'}); res.end(JSON.stringify(data)); incorrectly passes an object to setHeader (expects name, value); B and C set headers after res.end (which sends headers).
  4. Final Answer:

    res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' }); res.end(JSON.stringify(data)); -> Option A
  5. Quick Check:

    Use writeHead for multiple headers before response [OK]
Hint: Use writeHead to set many headers at once before response [OK]
Common Mistakes:
  • Using setHeader with object (like Express)
  • Setting headers after res.end
  • Confusing setHeader and writeHead usage