Understanding Node.js's native http module is like learning to drive a manual car before switching to automatic—it gives you complete control and deep insight into how web servers actually work. While frameworks like Express.js abstract away complexity, mastering the core http module is essential for building performant backend applications and troubleshooting production issues.
What is the HTTP Module?
The http module is Node.js's built-in library for creating HTTP servers and handling network requests. It provides low-level access to the HTTP protocol without any framework overhead.
import http from 'http';
Creating Your First HTTP Server
The createServer() method is your entry point. It accepts a request handler function and returns a server instance:
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js HTTP server!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
What's happening:
-
createServer()creates a server that listens for incoming HTTP requests - The callback receives two objects:
req(request) andres(response) -
listen(3000)binds the server to port 3000
Understanding Request and Response Objects
The Request Object (req)
Contains all incoming request data:
const server = http.createServer((req, res) => {
console.log('Method:', req.method); // GET, POST, etc.
console.log('URL:', req.url); // /about, /api/users
console.log('Headers:', req.headers); // All request headers
res.end('Request logged');
});
The Response Object (res)
Used to send data back to the client:
const server = http.createServer((req, res) => {
// Set status code and headers
res.writeHead(200, {
'Content-Type': 'application/json',
'X-Custom-Header': 'MyValue'
});
// Send response body
res.end(JSON.stringify({ message: 'Success' }));
});
Building a Simple Router
Here's how to handle different routes manually:
import http from 'http';
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home Page</h1>');
}
else if (req.url === '/api/users' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ users: ['Alice', 'Bob'] }));
}
else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
server.listen(3000);
Handling POST Requests with Body Data
Reading request body requires handling data streams:
import http from 'http';
const server = http.createServer((req, res) => {
if (req.url === '/api/data' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: data }));
});
}
});
server.listen(3000);
Key Takeaways
When to use the native HTTP module:
- Learning Node.js fundamentals and HTTP protocol basics
- Building microservices with minimal dependencies
- Maximum performance requirements without framework overhead
When to use frameworks like Express:
- Complex routing and middleware requirements
- Rapid application development
- Built-in security features and request parsing
Best Practices:
- Always set appropriate
Content-Typeheaders - Handle errors with proper status codes (404, 500)
- Use
res.end()to finalize responses - Consider security headers for production applications
Next Steps:
- Explore Node.js streams for handling large file uploads
- Learn about the
httpsmodule for SSL/TLS support - Study middleware patterns before diving into Express.js
Mastering the http module gives you the foundation to understand how every Node.js framework works under the hood—making you a more effective backend developer.
Top comments (0)