Native http Server
Overview
Unlike PHP (which strictly requires Apache or NGINX to intercept network traffic), Node.js is powerful enough to be its own native web server. The built-in http module allows Node to physically bind to an open port on the Operating System (like Port 80 for HTTP) and directly listen to incoming TCP network packets, completely eliminating the need for an external web server proxy in many architectures.
Syntax
const http = require('http');
// 1. Create the Server
// This callback fires every single time a user hits the server!
const server = http.createServer((req, res) => {
// Check which URL the user requested
if (req.url === '/' && req.method === 'GET') {
// Send the HTTP Status Code (200 OK) and Headers
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the physical data and close the connection
res.end('Welcome to the Home Page!');
} else {
// Handle 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Route not found.');
}
});
// 2. Bind the server to the OS Network Port
server.listen(3000, () => {
console.log('Server is listening on http://localhost:3000');
});Common Pitfalls
- Building massive production apps strictly with the native
httpmodule. While it is incredibly fast, it provides zero utilities for parsing JSON, handling URL parameters, or managing cookies. You will end up writing thousands of lines of boilerplateif/elsestring-matching logic. This is exactly why Express.js was invented. - Forgetting to call
res.end(). If you send headers but forget to formally end the response stream, the user's browser will spin indefinitely, waiting for data that will never arrive, eventually resulting in a generic 'Timeout' error.
Interview Questions
http server directly to the public internet on Port 80?Historically, no. Node was notoriously bad at handling Slowloris attacks or serving static assets (like images/CSS). The industry standard is still to place a robust Reverse Proxy (like NGINX or AWS ALB) in front of Node.js to handle SSL termination and static files, proxying only the dynamic API traffic to Node.
Real-World Example
How WebSockets (like Socket.io) 'hijack' the native HTTP server to upgrade the connection.
const http = require('http');
const server = http.createServer();
// Instead of a standard request, we intercept the 'upgrade' event!
// This allows us to convert the standard HTTP pipeline into a persistent WebSocket.
server.on('upgrade', (req, socket, head) => {
console.log("Upgrading connection to WebSocket!");
// Pass the raw TCP socket to the WebSocket library...
});Check Your Knowledge
Test your understanding of Native http Server with these quick questions.