Skip to main content

The HTTP Module

Node.js allows developers to build web servers without needing external server software like Apache or Nginx. This is done using the built-in http module.

A Raw HTTP Server

You can construct a basic server directly using the createServer method. The callback function receives a request object (req) containing details about the client's connection, and a response object (res) used to send data back to the client.

import http from 'node:http';

const server = http.createServer((req, res) => {
// Setting the HTTP Status Code and Content Type Header
res.writeHead(200, { 'Content-Type': 'application/json' });

// Constructing specific routes manually
if (req.url === '/api/users') {
res.end(JSON.stringify({ name: "Alice", id: 1 }));
} else {
res.end(JSON.stringify({ message: "Hello, World!" }));
}
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is actively running on port ${PORT}`);
});

The Routing Problem

While the raw http module is fast, constructing complex applications using nested if / else statements to parse URLs and HTTP methods (GET, POST, PUT, DELETE) scales very poorly.

For production web servers, developers almost universally adopt a specialized routing framework like Express.js.