🌐 Creating a Basic HTTP Server using Node.js http Module

Introduction

The http module is one of Node.js's built-in core modules that allows you to create HTTP servers and clients without installing any external packages. It is an excellent starting point for understanding how web servers work before moving on to frameworks such as Express.

Information

The http module is included with Node.js, so no installation is required beyond having Node.js installed.

How an HTTP Server Works

Every HTTP server follows a simple request-response cycle. A client (usually a web browser) sends a request to the server, the server processes it, and then returns an appropriate response.

👤 Client sends an HTTP request
📡 Request reaches the Node.js server
âš™ī¸ Server processes the request
📨 Response is sent back to the client
Read URL
Prepare response
Set status code and headers

Creating Your First HTTP Server

Step 1: Import the HTTP Module

Import the built-in http module using require().

Import the HTTP module

const http = require("http");

Step 2: Create the Server

Use the createServer() method to create a server. The callback receives two objects:

  • req — Contains information about the incoming request.
  • res — Used to build and send the response.

Create a basic HTTP server

const http = require("http");

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello, World!");
});

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

Step 3: Run the Server

Save the file as server.js and execute it using Node.js.

Run the server

node server.js

Open your browser and visit http://localhost:3000. You should see the message:

>>Hello, World!

Understanding the Server Code

CodePurpose
require("http")Imports the built-in HTTP module.
createServer()Creates a new HTTP server.
reqRepresents the incoming client request.
resRepresents the outgoing server response.
statusCodeSets the HTTP status code.
setHeader()Sets HTTP response headers.
end()Sends the response and closes it.
listen()Starts the server on a specified port.

Handling Different Routes

You can inspect the request URL to serve different responses.

Basic routing

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("Home Page");
  } else if (req.url === "/about") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("About Page");
  } else {
    res.writeHead(404, {
      "Content-Type": "text/plain"
    });
    res.end("404 - Page Not Found");
  }
});

server.listen(3000);

Route Flow

Incoming Request
URL = "/"
URL = "/about"
Any Other URL
Return Home Page
Return About Page
Return 404 Response

Working with Request Information

The request object provides useful information such as the HTTP method, requested URL, and headers.

Inspect request data

const server = http.createServer((req, res) => {
  console.log(req.method);
  console.log(req.url);
  console.log(req.headers);

  res.end("Request received");
});

Sending Different Content Types

Content TypeMIME TypeTypical Usage
Plain Texttext/plainSimple messages
HTMLtext/htmlWeb pages
JSONapplication/jsonREST APIs
CSStext/cssStylesheets

Return JSON

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

res.end(JSON.stringify({
  message: "Hello",
  success: true
}));

Project Structure

Project Folder
server.js
package.json (optional)

Testing the Server

  1. Start the server using node server.js.
  2. Open a browser.
  3. Visit http://localhost:3000.
  4. Test additional routes like /about.
  5. Observe terminal logs for incoming requests.

Tip

Press Ctrl + C in the terminal to stop the running server.

Best Practices

  • Always set an appropriate HTTP status code.
  • Return the correct Content-Type header.
  • Handle unknown routes with a 404 response.
  • Keep request handlers simple and modular.
  • Log errors during development for easier debugging.

Best Practice

As applications grow, consider separating routing, business logic, and configuration into different files for better maintainability.

Common HTTP Status Codes

Status CodeMeaning
200OK
201Created
301Moved Permanently
400Bad Request
401Unauthorized
404Not Found
500Internal Server Error

Further Learning

After mastering the core http module, explore routing libraries, middleware, REST API development, file serving, asynchronous programming, and web frameworks like Express to build more scalable applications.

Official Node.js HTTP Module Documentation

Summary

Summary

You learned how to create an HTTP server using Node.js's built-in http module, start a server, handle incoming requests, return different content types, implement simple routing, inspect request data, and apply basic best practices for building reliable web servers.