Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Remember: A status code tells the client the result of the request. The response body may provide additional details.

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
Easy Trick: 1xx = Information, 2xx = Success, 3xx = Redirection, 4xx = Client Error, 5xx = 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.

Remember: Status codes describe the result. Headers describe additional information. The response body contains the actual response data.

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

JavaScript
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

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

JavaScript
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

JavaScript
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

Terminal
node server.js

Step 4: Test the URL

Browser / Postman
GET http://localhost:3000/student

Step 5: Expected Response

JSON 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

Browser / Postman
GET http://localhost:3000/unknown

Expected Response

JSON 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

JavaScript
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

Browser
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.