How to Set Response Headers in Node.js: Simple Guide
In Node.js, you set response headers using the
res.setHeader(name, value) method on the response object. This method lets you specify the header name and its value before sending the response to the client.Syntax
The basic syntax to set a response header in Node.js is:
res.setHeader(name, value): Sets a single header wherenameis the header name (string) andvalueis the header value (string or array of strings).- You must call this before sending the response body.
javascript
res.setHeader('Content-Type', 'text/html');
Example
This example shows a simple HTTP server that sets the Content-Type and Cache-Control headers before sending a response.
javascript
import http from 'http'; const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/plain'); res.setHeader('Cache-Control', 'no-cache'); res.writeHead(200); res.end('Hello, world!'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Output
Server running at http://localhost:3000/
Common Pitfalls
Common mistakes when setting response headers include:
- Calling
res.setHeaderafterres.end()orres.writeHead()which sends the headers immediately. - Setting the same header multiple times without using an array for multiple values.
- Using incorrect header names or values that do not follow HTTP standards.
javascript
import http from 'http'; const server = http.createServer((req, res) => { // Wrong: setting header after response is sent res.end('Done'); res.setHeader('Content-Type', 'text/plain'); // This will have no effect });
Quick Reference
| Method | Description |
|---|---|
| res.setHeader(name, value) | Sets a response header before sending the response |
| res.getHeader(name) | Retrieves the value of a response header |
| res.removeHeader(name) | Removes a previously set header |
| res.writeHead(statusCode, headers) | Sets status code and headers at once before sending response |
Key Takeaways
Always set headers using res.setHeader() before sending the response body.
Headers must be valid HTTP header names and values.
Do not set headers after calling res.end() or res.writeHead().
Use res.writeHead() to set status and headers together if preferred.
Check headers with res.getHeader() and remove with res.removeHeader() if needed.