Paramclasses Academy - Blog

Tutorials Details

←
Post 16 of 40
→

Build a Web Server in Node.js Using the HTTP Module

Build a Web Server in Node.js Using the HTTP Module

October 29, 2026

✦ Build a Web Server in Node.js Using the HTTP Module

❖ Introduction

A web server is an essential part of web development. Whenever you open a website, your browser sends an HTTP request to a server, and the server returns a response containing HTML, JSON, images, or other content.

Node.js allows developers to create web servers using its built-in http module. You do not need Express.js or any external framework to create a basic server.

Learning the HTTP module is a great starting point for understanding how backend applications work. In this tutorial, we will build a web server from scratch, handle different URLs, send HTML and JSON responses, process request methods, and create a simple API using Node.js.

✦ What Is the HTTP Module in Node.js?

The http module is a built-in Node.js module used to create HTTP servers and communicate with HTTP clients.

Because it is included with Node.js, you do not need to install an additional package.

The HTTP module allows you to:

  • Create a web server.

  • Receive HTTP requests from browsers and applications.

  • Read request URLs and methods.

  • Send HTML, text, and JSON responses.

  • Create basic REST API endpoints.

  • Set HTTP status codes and response headers.

❖ Step 1: Install Node.js

First, ensure Node.js is installed on your computer.

Open Command Prompt or your terminal and run:

node -v
npm -v

If both commands display version numbers, you can proceed.

Create a project folder:

mkdir node-http-server
cd node-http-server

Create a file named server.js.

✦ Step 2: Create Your First Node.js Web Server

Add the following code to server.js:

const http = require("http");

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });

    res.end("Welcome to Param Classes!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Run the server:

node server.js

Open this address in your browser:

http://localhost:3000

You should see:

Welcome to Param Classes!

❖ How Does This Code Work?

1. Import the HTTP module

const http = require("http");

This loads Node.js's built-in HTTP module.

2. Create the server

const server = http.createServer((req, res) => {
    // Request handling code
});

The callback runs when a request reaches the server. The req object contains request information, while res is used to send a response.

3. Set the response status and header

res.writeHead(200, {
    "Content-Type": "text/plain; charset=utf-8"
});

Status code 200 means the request succeeded. The Content-Type header tells the client that the response contains plain text.

4. Finish the response

res.end("Welcome to Param Classes!");

The res.end() method sends the response body and signals that the response is complete.

5. Start listening for requests

server.listen(3000);

The server listens on port 3000 on the local machine.

✦ Step 3: Handle Different URLs

A useful web server should return different responses for different URLs.

Update your server.js file:

const http = require("http");

const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/plain; charset=utf-8");

    if (req.url === "/") {
        res.statusCode = 200;
        res.end("Home Page");
    } else if (req.url === "/about") {
        res.statusCode = 200;
        res.end("About Param Classes");
    } else if (req.url === "/contact") {
        res.statusCode = 200;
        res.end("Contact Page");
    } else {
        res.statusCode = 404;
        res.end("404 - Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Test these URLs:

URL Expected response
http://localhost:3000/ Home Page
http://localhost:3000/about About Param Classes
http://localhost:3000/contact Contact Page
http://localhost:3000/services 404 - Page Not Found

This example demonstrates basic routing without Express.js.

For larger applications, you would normally use a routing framework or create a more structured routing system.

✦ Step 4: Send an HTML Response

A server can return HTML instead of plain text. This is useful when you want the browser to display a formatted web page.

Replace your code with:

const http = require("http");

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/html; charset=utf-8"
    });

    res.end(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Node.js Web Server</title>
        </head>
        <body>
            <h1>Welcome to Param Classes</h1>
            <p>Learn Node.js backend development with practical examples.</p>
        </body>
        </html>
    `);
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Refresh http://localhost:3000 in your browser.

You will see a heading and paragraph rendered as an HTML page.

The Content-Type header is important because it tells the browser how to interpret the response.

✦ Step 5: Create a JSON API

Node.js can also return JSON data, which is commonly used by frontend applications, mobile apps, and other services.

Create a simple student API:

const http = require("http");

const students = [
    { id: 1, name: "Rahul", course: "Node.js" },
    { id: 2, name: "Priya", course: "JavaScript" },
    { id: 3, name: "Amit", course: "PHP" }
];

const server = http.createServer((req, res) => {
    if (req.url === "/api/students" && req.method === "GET") {
        res.writeHead(200, {
            "Content-Type": "application/json; charset=utf-8"
        });

        res.end(JSON.stringify(students));
    } else {
        res.writeHead(404, {
            "Content-Type": "application/json; charset=utf-8"
        });

        res.end(JSON.stringify({
            success: false,
            message: "Endpoint not found"
        }));
    }
});

server.listen(3000, () => {
    console.log("API running at http://localhost:3000");
});

Open:

http://localhost:3000/api/students

The browser will display JSON similar to:

[
  {
    "id": 1,
    "name": "Rahul",
    "course": "Node.js"
  },
  {
    "id": 2,
    "name": "Priya",
    "course": "JavaScript"
  },
  {
    "id": 3,
    "name": "Amit",
    "course": "PHP"
  }
]

The data is stored in a JavaScript array, so it will reset when the server restarts. A real student management system would typically retrieve records from a database.

✦ Step 6: Understand HTTP Request Methods

HTTP request methods describe the action a client wants to perform.

Method Common purpose
GET Retrieve information
POST Submit or create information
PUT Replace a resource
PATCH Update part of a resource
DELETE Delete a resource

In Node.js, you can inspect the request method using:

console.log(req.method);

For example:

if (req.url === "/api/students" && req.method === "GET") {
    // Return student records
} else if (req.url === "/api/students" && req.method === "POST") {
    // Handle creation of a student
}

Important: To implement a complete POST endpoint, you must also read and validate the incoming request body. Do not assume request data is valid simply because the method is POST.

✦ Step 7: Handle Query Parameters

Query parameters allow clients to send additional information through a URL.

For example:

http://localhost:3000/search?name=Rahul

You can parse the URL using the built-in URL class:

const http = require("http");

const server = http.createServer((req, res) => {
    const requestUrl = new URL(req.url, "http://localhost:3000");

    if (requestUrl.pathname === "/search") {
        const name = requestUrl.searchParams.get("name");

        res.writeHead(200, {
            "Content-Type": "application/json; charset=utf-8"
        });

        res.end(JSON.stringify({
            message: "Search request received",
            name: name
        }));
    } 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");
});

When you visit the example URL, the server returns the submitted name in JSON format.

In a production application, validate query parameters and avoid trusting user-provided values.

✦ Best Practices for Node.js HTTP Servers

❖ Use appropriate status codes. Return 200 for successful requests, 404 for missing resources, and suitable error codes for failures.

❖ Set the correct Content-Type. Tell the client whether the response contains text, HTML, or JSON.

❖ Validate incoming data. Treat all request data as untrusted.

❖ Handle errors. Avoid leaving requests unanswered when unexpected problems occur.

❖ Avoid hardcoding configuration. Use environment variables for settings such as the server port.

❖ Protect sensitive information. Do not return database credentials, API keys, or internal stack traces to clients.

❖ Use HTTPS in production. Deploy behind an appropriately configured HTTPS endpoint or use a suitable secure server setup.

❖ Keep code organized. As an application grows, separate routing, business logic, configuration, and database operations.

✦ Frequently Asked Questions (FAQs)

1. What is the HTTP module in Node.js?

It is a built-in module that allows developers to create HTTP servers and communicate with HTTP clients.

2. Do I need Express.js to create a Node.js server?

No. You can create a basic server using the built-in HTTP module. Express.js provides additional routing and middleware features that can simplify larger applications.

3. What is the difference between req and res?

req contains information about the incoming request. res provides methods for sending the response to the client.

4. What does res.end() do?

It ends the response and can send the final response body.

5. How do I return JSON from Node.js?

Set the response Content-Type to application/json and send a JSON string using JSON.stringify().

6. Can I build a REST API with the HTTP module?

Yes. You can implement routes, inspect HTTP methods, process requests, and return JSON. More complex APIs may be easier to maintain using Express.js or another framework.

✦ Conclusion

The Node.js HTTP module provides the foundation for creating web servers and APIs. By learning how to handle requests, send responses, manage URLs, and return JSON data, you can understand the core concepts behind backend web development.

Practise these examples and then connect your server to a database to build a student management API or another real-world application.

Keep learning and keep building with Param Classes!

←
Post 16 of 40
→