Whenever you open a website, submit a login form, or fetch data from an API, your browser communicates with a server using the HTTP protocol.
For example:
- Visiting Google
- Opening YouTube
- Logging into Facebook
- Calling a REST API
- Downloading a file
All of these operations happen over HTTP (HyperText Transfer Protocol).
Node.js provides a built-in HTTP module that allows developers to create web servers without installing any external libraries.
Although most modern applications use frameworks like Express.js, understanding the HTTP module helps you understand how web servers work behind the scenes.
In this article, we'll build a simple web server from scratch and explore the most important features of the HTTP module.
Let's get started!
What is the HTTP Module?
The HTTP module is a built-in Node.js module used to:
- Create HTTP servers
- Handle incoming requests
- Send responses
- Read request headers
- Read query parameters
- Create REST APIs
- Serve files
- Handle routing
Since it's built into Node.js, you don't need to install any package.
Importing the HTTP Module
const http = require("http");
Or, using ES Modules:
import http from "node:http";
What is an HTTP Server?
An HTTP server listens for incoming client requests and sends responses back.
The flow looks like this:
Browser
↓
HTTP Request
↓
Node.js Server
↓
HTTP Response
↓
Browser
Every time a browser sends a request, the server processes it and returns a response.
Creating Your First HTTP Server
Create a file named:
server.js
Add the following code:
const http = require("http");
const server = http.createServer((request, response) => {
response.end("Hello, Node.js!");
});
server.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
Run:
node server.js
Output:
Server is running on http://localhost:3000
Open your browser:
http://localhost:3000
Output:
Hello, Node.js!
Congratulations! 🎉
You've just created your first web server.
Understanding the Code
Import the HTTP Module
const http = require("http");
Imports the built-in HTTP module.
Create the Server
const server = http.createServer((request, response) => {});
createServer() creates a new HTTP server.
It accepts a callback function.
Every incoming request executes this callback.
Send a Response
response.end("Hello, Node.js!");
response.end() sends the response to the client and closes the connection.
Start the Server
server.listen(3000);
The server starts listening on port 3000.
Understanding the Request Object
The first parameter is the request object.
(request, response)
It contains information about the client's request.
Examples include:
- URL
- HTTP Method
- Headers
- Query Parameters
Read the Request URL
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.url);
res.end("Success");
});
server.listen(3000);
Visit:
http://localhost:3000/about
Console Output:
/about
Read the HTTP Method
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.method);
res.end("Success");
});
server.listen(3000);
Visit the page.
Output:
GET
Read Request Headers
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.headers);
res.end("Headers Received");
});
server.listen(3000);
Example Output:
{
host: "localhost:3000",
connection: "keep-alive",
"user-agent": "Mozilla/5.0"
}
Headers contain information about the client making the request.
Understanding the Response Object
The response object is used to send data back to the client.
Common methods include:
write()end()setHeader()writeHead()
Sending Plain Text
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Welcome to Node.js");
});
server.listen(3000);
Sending HTML
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/html");
res.end("<h1>Welcome to Node.js</h1>");
});
server.listen(3000);
Browser Output:
<h1>Welcome to Node.js</h1>
The browser renders it as a heading.
Sending JSON
const http = require("http");
const server = http.createServer((req, res) => {
const user = {
id: 1,
name: "John",
};
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(user));
});
server.listen(3000);
Output:
{
"id": 1,
"name": "John"
}
Setting a Status Code
const http = require("http");
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.end("Success");
});
server.listen(3000);
Using writeHead()
Instead of setting properties separately:
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
You can write:
res.writeHead(200, {
"Content-Type": "application/json",
});
res.end(JSON.stringify({ message: "Success" }));
Routing
Different URLs should return different responses.
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
return res.end("Home Page");
}
if (req.url === "/about") {
return res.end("About Page");
}
if (req.url === "/contact") {
return res.end("Contact Page");
}
res.statusCode = 404;
res.end("Page Not Found");
});
server.listen(3000);
Try visiting:
/
↓
/about
↓
/contact
↓
/unknown
Handling Multiple HTTP Methods
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "GET") {
return res.end("GET Request");
}
if (req.method === "POST") {
return res.end("POST Request");
}
res.end("Other Request");
});
server.listen(3000);
Reading Query Parameters
Visit:
http://localhost:3000/users?id=101&name=John
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
console.log(url.searchParams.get("id"));
console.log(url.searchParams.get("name"));
res.end("Query Received");
});
server.listen(3000);
Console Output:
101
John
Returning Different Content Types
Plain Text
res.setHeader("Content-Type", "text/plain");
HTML
res.setHeader("Content-Type", "text/html");
JSON
res.setHeader("Content-Type", "application/json");
Build a Simple REST API
const http = require("http");
const users = [
{
id: 1,
name: "John",
},
{
id: 2,
name: "Emma",
},
];
const server = http.createServer((req, res) => {
if (req.url === "/users") {
res.setHeader("Content-Type", "application/json");
return res.end(JSON.stringify(users));
}
res.statusCode = 404;
res.end("Not Found");
});
server.listen(3000);
Visit:
http://localhost:3000/users
Output:
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Emma"
}
]
Build a Simple JSON API with Routing
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
return res.end("Welcome");
}
if (req.url === "/api") {
res.setHeader("Content-Type", "application/json");
return res.end(
JSON.stringify({
success: true,
})
);
}
res.writeHead(404, {
"Content-Type": "text/plain",
});
res.end("Route Not Found");
});
server.listen(3000);
Real-World Use Cases
The HTTP module is commonly used for:
- Building web servers
- Creating REST APIs
- Serving static files
- Proxy servers
- Webhooks
- Microservices
- Learning backend fundamentals
Although frameworks like Express simplify these tasks, they are built on top of the HTTP module.
Common HTTP Methods
GET - Retrieve data
POST - Create data
PUT - Update entire resource
PATCH - Partially update a resource
DELETE - Delete data
Common Response Methods
end() - Ends the response
write() - Writes data to the response
setHeader() - Sets a response header
writeHead() - Sets status code and headers together
Best Practices
When working with the HTTP module:
- Always send an appropriate status code.
- Set the correct
Content-Typeheader. - Handle unknown routes with a
404response. - Keep routing logic organized as your application grows.
- Use the
URLclass to parse query parameters instead of manually splitting strings. - Return JSON for API responses.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Forgetting to call
response.end(). - Sending multiple responses for the same request.
- Not setting the correct
Content-Type. - Ignoring HTTP status codes.
- Parsing URLs manually instead of using the
URLclass.
Final Thoughts
The HTTP module is the foundation of web development in Node.js. It provides everything you need to build web servers and APIs without relying on external frameworks.
In this article, you learned:
- What the HTTP module is
- How to create a web server
- How to handle requests and responses
- How to read request URLs, methods, headers, and query parameters
- How to send HTML, JSON, and plain text responses
- How to implement basic routing
- How to build a simple REST API
- Best practices for working with HTTP servers
While most production applications use frameworks like Express.js, understanding the HTTP module gives you a solid foundation for backend development and helps you understand what happens behind the scenes.
Happy Coding! 🚀