Skip to main content

HTTP Module

The http module allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). It is the foundation for web servers in Node.js—every framework you will use later (Express, Fastify, Koa) is built on top of this module. Understanding the raw http module is like learning to drive a manual transmission before switching to automatic. You will rarely use it directly in production, but knowing how it works gives you the ability to debug framework-level issues, understand what middleware is actually doing under the hood, and make informed decisions about when a framework is helping versus getting in your way.

Creating a Server

The http.createServer() method includes a request listener function which is automatically added to the 'request' event.
Common pitfall — forgetting res.end(): If you never call res.end(), the client will hang indefinitely waiting for a response, and the connection stays open consuming resources. In a production server, this leads to connection pool exhaustion where your server appears frozen even though it is actually running.
Run this script and navigate to http://localhost:5000 in your browser.

The Request and Response Objects

The callback function receives two arguments:
  1. req (Request): Contains information about the incoming request (URL, method, headers, etc.).
  2. res (Response): Used to send a response back to the client.

Inspecting the Request

Setting Headers and Status Code

Basic Routing

You can use req.url to handle different routes.

Serving JSON

To serve an API, you typically return JSON data.

Serving HTML Files

To serve actual HTML files, we combine the http module with the fs module.

Handling POST Requests

Unlike GET requests, POST data comes in chunks and must be collected. This is because HTTP request bodies can be arbitrarily large (file uploads, for example), so Node.js streams the data to you piece by piece rather than buffering the entire body into memory.

Query Parameters

Headers Deep Dive

Request Headers

Response Headers

Building a Simple Router

HTTPS Server

For production, you need HTTPS:

Summary

  • The http module creates web servers without external dependencies
  • Use req.url and req.method for routing—but this gets unwieldy fast, which is why frameworks like Express exist
  • POST data arrives in chunks via 'data' and 'end' events—always limit body size to prevent memory exhaustion attacks
  • Parse query strings with the URL class (not the deprecated url.parse())
  • Set appropriate Content-Type headers for responses—mismatched headers cause subtle client-side bugs
  • Always call res.end() to avoid hanging connections
  • Use https module with SSL certificates for production—in practice, most teams terminate TLS at a reverse proxy (Nginx, load balancer) rather than in Node.js directly
  • Frameworks like Express.js abstract this complexity while still using http under the hood