9. HTTP Module – Create Your First Server in Node.js

The HTTP module in Node.js allows you to create web servers. It is the foundation of backend development and is used to handle client requests and send responses.

With just a few lines of code, you can build your own server without any framework.

Node.js HTTP module workflow

1. What is HTTP Module?

The http module is a built-in Node.js module used to create servers and handle HTTP requests and responses.

const http = require("http");

2. Creating Your First Server

const http = require("http");

const server = http.createServer((req, res) => {
  res.write("Hello World");
  res.end();
});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

Open your browser: http://localhost:3000

3. Understanding the Code

  • createServer() → Creates server
  • req → Request
  • res → Response
  • res.write() → Send data
  • res.end() → End response

4. Handling Routes

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.end("Home Page");
  } else if (req.url === "/about") {
    res.end("About Page");
  } else {
    res.end("404 Not Found");
  }
});

5. Setting Response Headers

res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js");
The HTTP module is powerful but basic. For large apps, use Express.js.

Conclusion

Now you can create your own web server using Node.js.

Your Hero to Zero Node.js journey just created a server 🌐🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال