Introduction
The http module is one of Node.js's built-in core modules that allows you to create HTTP servers and clients without installing any external packages. It is an excellent starting point for understanding how web servers work before moving on to frameworks such as Express.
Information
How an HTTP Server Works
Every HTTP server follows a simple request-response cycle. A client (usually a web browser) sends a request to the server, the server processes it, and then returns an appropriate response.
Creating Your First HTTP Server
Step 1: Import the HTTP Module
Import the built-in http module using require().
Import the HTTP module
const http = require("http");Step 2: Create the Server
Use the createServer() method to create a server. The callback receives two objects:
- req â Contains information about the incoming request.
- res â Used to build and send the response.
Create a basic HTTP server
const http = require("http");
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});Step 3: Run the Server
Save the file as server.js and execute it using Node.js.
Run the server
node server.jsOpen your browser and visit http://localhost:3000. You should see the message:
Understanding the Server Code
| Code | Purpose |
|---|---|
| require("http") | Imports the built-in HTTP module. |
| createServer() | Creates a new HTTP server. |
| req | Represents the incoming client request. |
| res | Represents the outgoing server response. |
| statusCode | Sets the HTTP status code. |
| setHeader() | Sets HTTP response headers. |
| end() | Sends the response and closes it. |
| listen() | Starts the server on a specified port. |
Handling Different Routes
You can inspect the request URL to serve different responses.
Basic routing
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Home Page");
} else if (req.url === "/about") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("About Page");
} else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("404 - Page Not Found");
}
});
server.listen(3000);Route Flow
Working with Request Information
The request object provides useful information such as the HTTP method, requested URL, and headers.
Inspect request data
const server = http.createServer((req, res) => {
console.log(req.method);
console.log(req.url);
console.log(req.headers);
res.end("Request received");
});Sending Different Content Types
| Content Type | MIME Type | Typical Usage |
|---|---|---|
| Plain Text | text/plain | Simple messages |
| HTML | text/html | Web pages |
| JSON | application/json | REST APIs |
| CSS | text/css | Stylesheets |
Return JSON
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
message: "Hello",
success: true
}));Project Structure
Testing the Server
- Start the server using node server.js.
- Open a browser.
- Visit http://localhost:3000.
- Test additional routes like /about.
- Observe terminal logs for incoming requests.
Tip
Best Practices
- Always set an appropriate HTTP status code.
- Return the correct Content-Type header.
- Handle unknown routes with a 404 response.
- Keep request handlers simple and modular.
- Log errors during development for easier debugging.
Best Practice
Common HTTP Status Codes
| Status Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 301 | Moved Permanently |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Internal Server Error |
Further Learning
After mastering the core http module, explore routing libraries, middleware, REST API development, file serving, asynchronous programming, and web frameworks like Express to build more scalable applications.
Official Node.js HTTP Module Documentation