The http Module
The http module is Node's built-in toolkit for the HTTP protocol — both serving requests (a web server) and making them (a client). It sits directly on top of the net/TCP layer: an HTTP server is a TCP server that parses the incoming byte stream into requests and formats responses back out. Everything from Express to Next.js ultimately runs on this module. Understanding it raw makes every framework feel like a thin convenience layer — because that's what they are.
What HTTP actually is
HTTP is a text-based request/response protocol over TCP. A client sends a request (method, path, headers, optional body); the server returns a response (status code, headers, optional body). The http module's job is parsing those bytes into JavaScript objects and serializing them back — so you work with req and res objects instead of raw text.
A raw HTTP/1.1 request and response (what flows over TCP)
GET /users/42 HTTP/1.1 ← request line: method, path, version
Host: example.com ← headers
Accept: application/json
← blank line ends headers
← (GET has no body)
HTTP/1.1 200 OK ← status line: version, code, reason
Content-Type: application/json ← response headers
Content-Length: 27
{"id":42,"name":"Ada Lovelace"} ← response bodyThe smallest possible server
import { createServer } from 'node:http'
const server = createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello, World!\n')
})
server.listen(3000, () => console.log('http://localhost:3000'))The pieces of the module
Export | Role |
|---|---|
| Create a server; handler gets |
| Make an outbound request (full control) |
| Shorthand for a GET request |
| The server class (an EventEmitter) |
| The |
| The |
| Manages connection pooling / keep-alive |
req and res are streams
import { createServer } from 'node:http'
createServer(async (req, res) => {
if (req.method === 'POST') {
let body = ''
for await (const chunk of req) body += chunk // read the streamed body
console.log('received:', body)
}
res.end('ok')
}).listen(3000)http vs https vs http2
Module | Use for |
|---|---|
| Plain HTTP/1.1 — dev, or behind a TLS-terminating proxy |
| HTTP over TLS — needs a certificate; see HTTPS Server |
| HTTP/2 — multiplexing, server push (separate API) |
A note on frameworks
You can build a whole app on raw http — and the next several pages do, deliberately, so you understand routing, headers, and bodies from first principles. But raw http has no routing, no body parsing, no middleware; you build all of it yourself. Frameworks like Express add those conveniences on top of this exact module. Learn the foundation here; reach for the framework when productivity matters.