Node.js HTTP Module
The HTTP module is one of the most important core modules in Node.js. It allows developers to create web servers and handle HTTP requests and responses without using any external libraries.
Using the HTTP module, you can build backend services, APIs, and web applications directly in Node.js. It forms the foundation for frameworks like Express.js, which are built on top of it.
What is the HTTP Module?
The http module is a built-in module in Node.js used to transfer data over the web using the HTTP protocol.
It enables you to create a server that can listen for incoming requests and respond accordingly.
You do not need to install this module separately because it comes bundled with Node.js.
Creating a Basic HTTP Server
You can create a simple web server using the http.createServer() method.
This method takes a callback function that runs whenever a request is received.
In this example:
require("http")imports the HTTP modulecreateServer()creates a serverreqrepresents the request objectresrepresents the response objectres.write()sends data to the clientres.end()ends the responselisten(3000)starts the server on port 3000
Open browser → http://localhost:3000 → Hello World
Understanding Request and Response
Request Object (req)
The request object contains information about the incoming request such as URL, method, headers, and more.
Response Object (res)
The response object is used to send data back to the client.
Sending HTML Response
You can send HTML content instead of plain text by setting the correct headers.
Handling Different Routes
You can use req.url to handle different routes:
Setting Status Codes
Status codes indicate the result of a request:
Why Use HTTP Module?
- Build web servers without external dependencies
- Understand core backend concepts
- Full control over request and response handling
- Foundation for frameworks like Express.js
Limitations of HTTP Module
While the HTTP module is powerful, it can become complex for large applications. Developers often use frameworks like Express.js to simplify routing and middleware handling.
- Manual routing required
- No built-in middleware support
- More boilerplate code
Real-World Use Cases
- Building REST APIs
- Creating web servers
- Handling HTTP requests and responses
- Backend for web applications
Best Practices
- Always set proper headers
- Handle errors and invalid routes
- Use modular structure for large applications
- Move to Express.js for scalability
Common Mistakes
- Forgetting
res.end() - Not handling routes properly
- Not setting content-type headers
Conclusion
The HTTP module is the backbone of web development in Node.js. It allows you to create servers and handle client requests efficiently.
By understanding this module, you build a strong foundation for backend development and can easily move to advanced frameworks like Express.js.

