๐ŸŒ Day 6: Creating a Basic HTTP Server using Node.js (Without Express)

Payal PorwalPayal Porwal
5 min read

๐Ÿ‘จโ€๐Ÿซ What Youโ€™ll Learn Today

  • What is an HTTP server?

  • Why learn it without Express?

  • How to create a basic server using Node.js

  • Handling routes like /, /about, and /contact

  • Sending HTML responses

  • Real-life example

  • FAQs to clear common doubts


๐Ÿ’ก Why Learn HTTP Server Without Express?

Even though Express is widely used, it is built on top of Node.jsโ€™s native http module.
Understanding the basics helps you:

  • Learn how backend works under the hood

  • Build logic without any dependency

  • Prepare better for interviews

โœ… Once you understand this, using Express becomes even easier!


๐Ÿ“ฆ What is an HTTP Server?

An HTTP server listens for requests from the browser and sends back responses.

When you open http://localhost:3000, your browser sends a request. The server responds with a page or message.


๐Ÿ›  Step-by-Step: Create a Basic HTTP Server


๐Ÿ“ 1. Create a new folder

mkdir basic-http-server
cd basic-http-server

๐Ÿ“„ 2. Create a file: server.js

const http = require('http'); // Core module
const fs = require('fs');
const path = require('path');

const PORT = 3000;

// Create server
const server = http.createServer((req, res) => {
  // Get the requested URL
  const url = req.url;

  if (url === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write("<h2>Welcome to the Home Page</h2>");
    res.end();
  } else if (url === "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write("<h2>This is the About Page</h2>");
    res.end();
  } else if (url === "/contact") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write("<h2>Contact us at: support@example.com</h2>");
    res.end();
  } else {
    res.writeHead(404, { "Content-Type": "text/html" });
    res.write("<h2>404 - Page Not Found</h2>");
    res.end();
  }
});

// Start the server
server.listen(PORT, () => {
  console.log(`โœ… Server is running on http://localhost:${PORT}`);
});

โ–ถ Run the server

node server.js

๐ŸŒ Open Browser:


๐Ÿง  Real-Life Example: Serving an HTML File

Letโ€™s say you want to serve a real HTML file instead of inline HTML.


Step 1: Create home.html

<!-- home.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Node Server</title>
  </head>
  <body>
    <h1>Hello from Node.js Server</h1>
    <p>This page is served using the HTTP module.</p>
  </body>
</html>

Step 2: Update server.js

if (url === "/") {
  const filePath = path.join(__dirname, 'home.html');
  fs.readFile(filePath, 'utf-8', (err, data) => {
    if (err) {
      res.writeHead(500, { "Content-Type": "text/html" });
      res.end("<h2>Server Error</h2>");
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(data);
    }
  });
}

โœ… Now your browser will load a full HTML page served by your Node server!


๐Ÿ“š Students Learn:

ConceptSkill Developed
Core module: httpLearn to handle requests and responses manually
Routing logicUnderstand how URLs map to responses
Serving HTMLFirst step toward full-stack development
Node.js file handlingUse fs.readFile to serve files
Real server setupSee actual output in browser without frontend code

โ“ FAQs โ€“ Common Doubts


1) Whatโ€™s the difference between Express and HTTP module?

FeatureNative httpExpress.js
Speed to writeSlower, more manualFast, easy syntax
RoutingManual (if checks)Built-in .get() etc.
PerformanceRaw powerSlightly heavier

Express is built on top of http and offers more features. But learning http first helps you build strong fundamentals.


2) Do we need to install any packages to use http module?

โŒ No, itโ€™s a built-in core module in Node.js. Just use:

const http = require('http');

3) Can we return CSS, JS, and image files too from HTTP server?

โœ… Yes. But youโ€™ll need to check the request URL, detect the file type, and set proper content-type like:

res.writeHead(200, { "Content-Type": "text/css" });

๐Ÿง  This can become complex โ€” thatโ€™s why frameworks like Express are preferred.


4) Why is fs.readFile used in the server?

To read external files (like HTML) and serve them to the browser.
This is how backend servers send HTML to the frontend.


๐Ÿ“ Practice Tasks for Students

  1. Create /about.html and /contact.html pages and serve them.

  2. Handle the /services route.

  3. Return 404 page with a custom HTML message.

  4. Style your HTML with inline CSS or serve a CSS file (challenge).


โœ… Summary

What You BuiltWhat You Learned
A basic HTTP serverSending browser responses using Node.js
Routing with if logicHandling multiple URLs
Serve external HTMLUsing fs.readFile and path
Real app on localhostOutput visible in browser & console

๐ŸŽ‰ Now youโ€™ve built your first complete backend server using pure Node.js!

Would you like to move on to Day 7: Intro to Express.js and setting up the first route in the same structured style next?


๐Ÿ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas โ€” ๐Ÿ“ฉ Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, ๐ŸŽฅ Donโ€™t forget to subscribe to my YouTube channel โ€“ Knowledge Factory 22 โ€“ for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. ๐Ÿš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: ๐Ÿš€ In-depth explorations of emerging technologies ๐Ÿ’ก Practical tutorials and how-to guides ๐Ÿ”งInsights on software development best practices ๐Ÿš€Reviews of the latest tools and frameworks ๐Ÿ’ก Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letโ€™s connect and grow together! ๐ŸŒŸ