Introduction
HTTP headers are key-value pairs exchanged between a client and a server as part of every HTTP request and response. They carry important metadata such as content type, authentication information, caching rules, cookies, and more. In Node.js, the built-in http module provides easy access to both request and response headers.
Information
Prerequisites
- Node.js installed
- Basic understanding of the HTTP protocol
- Knowledge of creating a basic server using the http module
What Are HTTP Headers?
Headers provide additional information about an HTTP request or response. They help clients and servers understand how to process data, negotiate content formats, manage caching, maintain authentication, and much more.
Common HTTP Headers
| Header | Purpose | Direction |
|---|---|---|
| Content-Type | Specifies the format of the message body. | Request & Response |
| Content-Length | Specifies the size of the message body. | Request & Response |
| Authorization | Provides authentication credentials. | Request |
| Accept | Indicates the content types the client accepts. | Request |
| User-Agent | Identifies the client application. | Request |
| Cache-Control | Controls caching behavior. | Response |
| Set-Cookie | Sends cookies to the client. | Response |
Accessing Request Headers
Incoming request headers are available through the req.headers object. Header names are automatically converted to lowercase by Node.js.
Reading Request Headers
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.headers);
res.end("Headers received.");
});
server.listen(3000);Reading a Specific Header
You can access an individual header using its lowercase name.
Accessing the User-Agent Header
const userAgent = req.headers["user-agent"];
console.log(userAgent);| Header Name | Example Value |
|---|---|
| host | localhost:3000 |
| user-agent | Mozilla/5.0 ... |
| accept | text/html, application/json |
Setting Response Headers
Use the setHeader() method to add headers before sending the response.
Setting Response Headers
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!");
});
server.listen(3000);Setting Multiple Headers
Multiple Response Headers
res.setHeader("Content-Type", "application/json");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Powered-By", "Node.js");
res.end(JSON.stringify({
message: "Success"
}));Using writeHead()
The writeHead() method allows you to send the status code and multiple headers together in a single call.
Using writeHead()
res.writeHead(200, {
"Content-Type": "application/json",
"Cache-Control": "no-store"
});
res.end(JSON.stringify({
success: true
}));setHeader() vs writeHead()
| Feature | setHeader() | writeHead() |
|---|---|---|
| Sets one header at a time | â Yes | â No |
| Can set multiple headers | Using multiple calls | â Yes |
| Sets status code | â No | â Yes |
| Common usage | Flexible updates | Initial response setup |
Retrieving Response Headers
Node.js allows you to inspect response headers before they are sent.
Getting a Response Header
res.setHeader("Content-Type", "application/json");
console.log(res.getHeader("Content-Type"));Removing Response Headers
If a header is no longer needed before the response is sent, it can be removed.
Removing a Header
res.setHeader("Cache-Control", "no-cache");
res.removeHeader("Cache-Control");Example: Returning JSON
JSON API Response
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
id: 1,
name: "Alice",
role: "Developer"
}));
});
server.listen(3000);Example: Simple Authentication Header
The following example checks whether an Authorization header is present.
Checking Authorization Header
const auth = req.headers.authorization;
if (!auth) {
res.writeHead(401, {
"Content-Type": "text/plain"
});
res.end("Unauthorized");
}
else {
res.end("Access Granted");
}Request and Response Lifecycle
Frequently Used Response Content Types
| Content Type | Used For |
|---|---|
| text/plain | Plain text responses. |
| text/html | HTML documents. |
| application/json | REST APIs and JSON data. |
| application/xml | XML documents. |
| image/png | PNG images. |
| text/css | CSS stylesheets. |
| application/javascript | JavaScript files. |
Best Practices đĄ
- Always set the correct Content-Type for every response.
- Read request headers in lowercase since Node.js normalizes header names.
- Set all required headers before calling res.end().
- Return appropriate HTTP status codes along with response headers.
- Avoid exposing sensitive information through custom headers.
Best Practice
Common Mistakes â ī¸
- Trying to modify headers after calling res.end().
- Using incorrect header names or values.
- Forgetting to set the Content-Type header.
- Assuming header names are case-sensitive in Node.js.
- Sending confidential information in HTTP headers.