HTTP Status Codes and Headers in Node.js
Learn how HTTP status codes and headers work in Node.js, how servers communicate request results, and how to send appropriate responses using the built-in HTTP module.
Whenever a client sends a request to a server, the server needs to communicate the result. For example, Samadhan wants to view student details at CIIT Training Institute. If the student exists, the server can return a successful response. If the requested student does not exist, the server can return a Not Found response.
HTTP status codes describe the result of a request, while HTTP headers provide additional information about the request or response. Node.js allows us to set response status codes and headers using the HTTP response object.
1. What Are HTTP Status Codes?
An HTTP status code is a three-digit number sent by a server in its HTTP response. It helps the client understand whether the request succeeded, requires further action, or encountered a problem.
For example, when Pradnya requests a student record, the
server may return 200 OK if the request succeeds
or 404 Not Found if the requested resource does
not exist.
2. Categories of HTTP Status Codes
HTTP status codes are divided into five categories according to their first digit.
| Status Code Range | Category | Meaning | Example |
|---|---|---|---|
| 100–199 | Informational | Provides information about the request process. | 100 Continue |
| 200–299 | Success | The request was successfully processed. | 200 OK |
| 300–399 | Redirection | Further action may be required. | 301 Moved Permanently |
| 400–499 | Client Error | The request cannot be fulfilled as submitted. | 404 Not Found |
| 500–599 | Server Error | The server failed to complete a valid request. | 500 Internal Server Error |
3. Common HTTP Status Codes
| Status Code | Name | Purpose |
|---|---|---|
200 |
OK | The request succeeded. |
201 |
Created | A resource was created successfully. |
204 |
No Content | The request succeeded and there is no response body. |
301 |
Moved Permanently | The resource has a permanent new location. |
302 |
Found | The resource is temporarily available at another location. |
400 |
Bad Request | The request contains invalid data. |
401 |
Unauthorized | Valid authentication credentials are missing or invalid. |
403 |
Forbidden | The client is not permitted to access the resource. |
404 |
Not Found | The requested resource was not found. |
405 |
Method Not Allowed | The method is not supported for the requested resource. |
500 |
Internal Server Error | An unexpected server-side error occurred. |
503 |
Service Unavailable | The server is temporarily unable to handle the request. |
4. What Are HTTP Headers?
HTTP headers are key-value pairs that provide additional information about an HTTP request or response.
For example, when the Node.js server sends student information
in JSON format, it can set the
Content-Type header to
application/json. This tells the client what
format the response body contains.
5. HTTP Request Headers
Request headers are sent by the client to provide information
about its request. Node.js makes incoming headers available
through req.headers.
| Header | Purpose | Example |
|---|---|---|
Content-Type |
Describes the format of the request body. | application/json |
Accept |
Indicates the response formats the client can accept. | application/json |
Authorization |
May carry authentication credentials. | Bearer token |
Example: Reading Request Headers
const http = require("node:http");
const server = http.createServer((req, res) => {
console.log("Request Method:", req.method);
console.log("Request URL:", req.url);
console.log("Content-Type:", req.headers["content-type"]);
console.log("Accept:", req.headers["accept"]);
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Request headers received successfully");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Expected Terminal Output
Server running on port 3000
Request Method: GET
Request URL: /
Content-Type: undefined
Accept: text/html,...
Explanation: When a browser opens the server URL, it sends a GET request. The browser may send an Accept header but normally does not send a request Content-Type header when there is no request body. Therefore, Content-Type may be undefined in this example.
6. HTTP Response Headers
Response headers are sent by the server to provide additional
information about the response. In Node.js, we can set
response headers using res.setHeader() or
provide them through res.writeHead().
| Header | Purpose | Example |
|---|---|---|
Content-Type |
Describes the response body format. | application/json; charset=utf-8 |
Cache-Control |
Provides caching instructions. | no-store |
Location |
Identifies a target URL, often for redirects or created resources. | /students/1 |
Access-Control-Allow-Origin |
Controls browser access to responses through CORS. | https://example.com |
7. Setting Status Codes and Headers in Node.js
Node.js provides methods for setting the response status code and response headers before completing the response.
Important Methods
| Method or Property | Purpose |
|---|---|
res.statusCode |
Sets the HTTP response status code. |
res.setHeader() |
Sets a response header. |
res.writeHead() |
Sets the status code and can set response headers. |
res.end() |
Completes the response and can send the response body. |
Basic Syntax
res.statusCode = 200;
res.setHeader(
"Content-Type",
"application/json; charset=utf-8"
);
res.end(JSON.stringify({
message: "Request successful"
}));
Explanation:
The status code is set to 200, the Content-Type header
identifies the response as JSON, and
res.end() sends the JSON string and finishes
the response.
8. First Program: Sending a 200 OK Response
Let's create a simple HTTP server that returns student details with status code 200 and a JSON response header.
Step 1: Create a File
Create a JavaScript file named server.js.
Step 2: Write the Program
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/student") {
res.statusCode = 200;
res.setHeader(
"Content-Type",
"application/json; charset=utf-8"
);
res.setHeader("Cache-Control", "no-store");
const student = {
id: 1,
name: "Samadhan",
course: "Node.js",
institute: "CIIT Training Institute"
};
res.end(JSON.stringify({
message: "Student details retrieved successfully",
data: student
}));
} else {
res.statusCode = 404;
res.setHeader(
"Content-Type",
"application/json; charset=utf-8"
);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Step 3: Run the Program
node server.js
Step 4: Test the URL
GET http://localhost:3000/student
Step 5: Expected Response
{
"message": "Student details retrieved successfully",
"data": {
"id": 1,
"name": "Samadhan",
"course": "Node.js",
"institute": "CIIT Training Institute"
}
}
Explanation: The server checks the request method and URL. If the request matches, it sends status code 200, JSON headers and the student details. If the route does not match, it sends a 404 response.
9. Example: Handling a 404 Not Found Response
A 404 response is used when the requested resource or route cannot be found. For example, if Pradnya requests a student route that does not exist, the server can return a 404 status.
Test the URL
GET http://localhost:3000/unknown
Expected Response
{
"message": "Route not found"
}
Explanation:
In the previous program, any request that does not match
GET /student reaches the fallback branch.
That branch sets status code 404 and returns a JSON message.
10. Example: HTTP Redirection
Redirection status codes tell the client that it should navigate to another location. A Location response header identifies the destination.
Example: Redirecting to a New Route
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.url === "/old-page") {
res.writeHead(302, {
"Location": "/new-page"
});
res.end();
} else if (req.url === "/new-page") {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Welcome to the new page");
} else {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Page not found");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Test the URL
http://localhost:3000/old-page
Explanation:
The server returns status code 302 and the Location header
points to /new-page. A browser normally follows
this redirect and displays the new page.
11. How Status Codes and Headers Work Together
The server creates a response by choosing a status code, setting any required headers, and sending a response body when appropriate.
1. Receive Request
Read the method and URL.
2. Process Request
Check the route and perform the operation.
3. Set Status Code
Example: 200, 201 or 404.
4. Set Response Headers
Example: Content-Type and Cache-Control.
5. Send Response
Send the body when appropriate and finish the response.
Note: In Node.js, set status codes and headers before the response headers are sent. Once the response has been sent, they cannot be changed.
12. Important Points
- HTTP status codes indicate the result of a request.
- 2xx codes indicate success, 4xx codes indicate client errors, and 5xx codes indicate server errors.
-
Request headers can be read using
req.headers. -
Response headers can be set using
res.setHeader(). -
res.writeHead()can set the status code and headers. -
res.end()finishes the HTTP response. - Headers and status codes must be set before they are sent.
Summary
In this lesson, we learned about HTTP status code
categories, common response codes, request headers,
and response headers in Node.js. We explored
req.headers, res.statusCode,
res.setHeader(), res.writeHead()
and res.end() through practical examples.
These concepts help us build HTTP servers that return
clear and appropriate responses to clients.