How does the HTTP module work in Node.js?
The HTTP Module
The http module is a core Node.js module that allows you to create HTTP servers and make HTTP requests without any external dependencies. It's the foundation upon which frameworks like Express.js are built.
Creating an HTTP Server
js
const http = require('http');
const server = http.createServer((req, res) => {
// req = IncomingMessage (readable stream)
// res = ServerResponse (writable stream)
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});Request Object (IncomingMessage)
js
const server = http.createServer((req, res) => {
console.log(req.method); // GET, POST, PUT, DELETE
console.log(req.url); // /api/users?page=1
console.log(req.headers); // { host: '...', 'content-type': '...' }
// Parse URL
const url = new URL(req.url, `http://${req.headers.host}`);
console.log(url.pathname); // /api/users
console.log(url.searchParams.get('page')); // '1'
});Handling POST Body
The request body arrives as a stream — you must collect chunks:
js
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/api/users') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ created: data }));
});
}
});Simple Router
js
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === 'GET' && url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home</h1>');
} else if (method === 'GET' && url === '/api/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: 'John' }]));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});Making HTTP Requests
js
const http = require('http');
// GET request
http.get('http://api.example.com/data', (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
// POST request
const postData = JSON.stringify({ name: 'John' });
const options = {
hostname: 'api.example.com',
port: 80,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
req.write(postData);
req.end();http vs https vs http2
| Module | Protocol | Use Case |
|---|---|---|
http | HTTP/1.1 | Development, internal services |
https | HTTPS (TLS) | Production, public APIs |
http2 | HTTP/2 | Performance (multiplexing, server push) |
js
const https = require('https');
const fs = require('fs');
const server = https.createServer({
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}, (req, res) => {
res.writeHead(200);
res.end('Secure!');
});Why Use Express Instead?
| Feature | Raw http | Express.js |
|---|---|---|
| Routing | Manual if/else | app.get('/path') |
| Body parsing | Manual stream handling | Built-in middleware |
| Middleware | No built-in support | First-class support |
| Static files | Manual | express.static() |
Tip: Understanding the raw
httpmodule helps you understand what Express does under the hood. In production, use Express or Fastify for developer productivity, but know the fundamentals.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.