đŸ›Ŗī¸ Implementing Basic Routing with the Node.js http Module

Introduction

Routing is the process of determining how a server responds to different client requests based on the requested URL and HTTP method. In Node.js, the built-in http module allows you to implement basic routing without relying on external frameworks. Understanding manual routing provides a strong foundation before learning web frameworks like Express.

Information

The http module does not provide built-in routing features. Developers implement routing by inspecting properties such as req.url and req.method.

What is Routing?

A route defines the logic that should execute when a client requests a specific URL. Each route usually consists of:

  • A URL path (such as / or /about)
  • An HTTP method (such as GET or POST)
  • A response returned by the server
🌐 Client Request
📍 Check Requested URL
📌 Check HTTP Method
âš™ī¸ Match a Route
📨 Send the Appropriate Response

Understanding the Request Object

The request object contains information needed for routing. The two most commonly used properties are:

PropertyDescription
req.urlContains the requested URL path.
req.methodContains the HTTP request method.

Inspecting request information

const http = require("http");

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

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

server.listen(3000);

Creating a Basic Router

The simplest way to implement routing is by using conditional statements that compare the request URL.

Routing using if...else

const http = require("http");

const server = http.createServer((req, res) => {

  if (req.url === "/") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("Welcome to the Home Page");

  } else if (req.url === "/about") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("About Us");

  } else if (req.url === "/contact") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("Contact Page");

  } else {
    res.writeHead(404, {
      "Content-Type": "text/plain"
    });
    res.end("404 - Page Not Found");
  }

});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

Route Flow

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

Routing Based on HTTP Methods

In many applications, the same URL behaves differently depending on the HTTP method. For example, a GET request retrieves data, while a POST request submits new data.

Routing by URL and HTTP method

const http = require("http");

const server = http.createServer((req, res) => {

  if (req.url === "/users" && req.method === "GET") {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });
    res.end("Fetching users");

  } else if (req.url === "/users" && req.method === "POST") {
    res.writeHead(201, {
      "Content-Type": "text/plain"
    });
    res.end("Creating a new user");

  } else {
    res.writeHead(404, {
      "Content-Type": "text/plain"
    });
    res.end("Route not found");
  }

});

server.listen(3000);

Serving HTML Pages

Routes can return HTML content instead of plain text by setting the appropriate Content-Type header.

Returning HTML

if (req.url === "/") {
  res.writeHead(200, {
    "Content-Type": "text/html"
  });

  res.end("<h1>Welcome to the Home Page</h1>");
}

Returning JSON Responses

JSON responses are commonly used when building APIs.

Returning JSON data

if (req.url === "/api") {

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

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

}

Handling 404 Errors

Every server should handle unknown routes gracefully by returning a 404 Not Found response.

404 handler

res.writeHead(404, {
  "Content-Type": "text/plain"
});

res.end("404 - Page Not Found");

Important

Always include a fallback route to ensure clients receive a meaningful response when requesting an undefined URL.

Common HTTP Status Codes

Status CodeMeaningTypical Usage
200OKSuccessful request
201CreatedResource successfully created
400Bad RequestInvalid client request
404Not FoundRequested route does not exist
500Internal Server ErrorUnexpected server error

Testing Routes

  1. Start the server using node server.js.
  2. Open a web browser or an API testing tool.
  3. Visit http://localhost:3000/.
  4. Test additional routes like /about, /contact, and /api.
  5. Request an unknown URL to verify the 404 response.

Example Request Flow

🌍 Browser Requests /about
Server Receives the Request
Compare req.url
Route Matches /about
Return HTTP 200 Response
Display About Page

Advantages of Basic Routing

  • Simple to understand for beginners.
  • No external dependencies are required.
  • Provides insight into how web frameworks implement routing.
  • Suitable for small applications and learning purposes.

Limitations

  • Large numbers of routes become difficult to maintain.
  • Dynamic routes require additional parsing logic.
  • No built-in middleware support.
  • Manual handling of request parsing and responses.

Warning

For medium and large applications, manually managing routes with multiple conditional statements becomes cumbersome. Frameworks like Express provide organized routing, middleware support, and improved scalability.

Best Practices

  • Always check both req.url and req.method when appropriate.
  • Set the correct Content-Type for every response.
  • Return meaningful HTTP status codes.
  • Include a default 404 handler.
  • Keep routing logic clean and separate from business logic as your application grows.

Best Practice

As the number of routes increases, consider organizing route handlers into separate modules or migrating to a framework that offers structured routing capabilities.

Official Documentation

Node.js HTTP Module Documentation

Summary

Summary

Basic routing with the Node.js http module involves inspecting req.url and req.method to determine how the server should respond. By combining conditional logic, proper status codes, appropriate response headers, and a fallback 404 handler, you can build simple web servers and APIs while gaining a solid understanding of the fundamentals of HTTP request handling.