Your First HTTP Server in Node.js

Your First HTTP Server in Node.js

From Zero to Handling Real Requests

Backend development begins with one simple idea:

Listen → Process → Respond

In Node.js, this is done using the built-in HTTP module. No frameworks needed.

Setting up a Simple Node.js App

Step 1: Initialize Project

mkdir first-server
cd first-server
npm init -y        

Step 2: Create Entry File

touch index.js        

HTTP Module

Node.js provides a built-in module called http to create servers.

Basic Server Example

const http = require("http");

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

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

What’s Happening Here?

  • createServer() → creates server
  • (req, res) → request and response objects
  • res.end() → sends response
  • listen() → starts server

Open browser:

http://localhost:3000        

Understanding Request and Response Objects

Request Object (req)

Contains:

  • URL → req.url
  • Method → req.method
  • Headers → req.headers

Example:

console.log(req.method);
console.log(req.url);        

Response Object (res)

Used to send data back.

Methods:

  • res.write() → write data
  • res.end() → finish response
  • res.setHeader() → set headers
  • res.statusCode → set status

Example:

res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Response sent");        

HTTP Methods

HTTP defines how clients interact with server.

GET (Fetch Data)

Used to retrieve data.

if (req.method === "GET" && req.url === "/") {
  res.end("This is GET request");
}        

POST (Send Data)

Used to send data to server.

if (req.method === "POST" && req.url === "/data") {
  let body = "";

  req.on("data", chunk => {
    body += chunk;
  });

  req.on("end", () => {
    console.log(body);
    res.end("Data received");
  });
}        

PUT (Update Data)

Used to update existing data.

if (req.method === "PUT" && req.url === "/update") {
  res.end("Data updated");
}        

DELETE (Remove Data)

Used to delete data.

if (req.method === "DELETE" && req.url === "/delete") {
  res.end("Data deleted");
}        

Sending and Receiving Data

Receiving Data (Request Body)

Node streams request data in chunks.

let body = "";

req.on("data", chunk => {
  body += chunk;
});

req.on("end", () => {
  console.log("Received:", body);
});        

Sending JSON Response

res.setHeader("Content-Type", "application/json");

res.end(JSON.stringify({
  message: "Success",
  status: 200
}));        

Routing Example (Handling Multiple Routes)

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.method === "GET" && req.url === "/") {
    res.end("Home Page");
  }

  else if (req.method === "GET" && req.url === "/about") {
    res.end("About Page");
  }

  else if (req.method === "POST" && req.url === "/data") {
    let body = "";

    req.on("data", chunk => {
      body += chunk;
    });

    req.on("end", () => {
      res.end("Received Data");
    });
  }

  else {
    res.statusCode = 404;
    res.end("Route Not Found");
  }
});

server.listen(3000);        

Key Observations

  • Node does not provide routing out of the box
  • You manually handle routes using conditions
  • Data handling is stream-based
  • Everything is asynchronous

Common Mistakes Beginners Make

  • Forgetting res.end() → request hangs
  • Not handling request body properly
  • Not setting headers for JSON
  • Blocking event loop with heavy logic

Mental Model

  • Browser sends request → Node receives it →
  • You decide what to do → Node sends response

Everything revolves around:

req → process → res        

Why This Matters

Before using Express or frameworks, this teaches you:

  • How HTTP actually works
  • What frameworks abstract away
  • How servers handle requests

To view or add a comment, sign in

More articles by Prince Chaurasia

  • Express.js for Building Backends

    Making Backend Development Practical, Fast, and Scalable If you’ve ever built a server using Node’s HTTP module, you…

  • Node.js Architecture

    How Modern Backend Systems Handle Concurrency Efficiently ? Node.js is not just a runtime.

  • Introduction to Runtime Environments

    Why JavaScript Needed a Place Beyond the Browser JavaScript was originally created to run inside browsers. It handled…

  • Generics and TypeScript Tooling

    Writing Flexible Types and Setting Up a Strong TypeScript Environment Once you understand basic types, the real power…

  • Understanding the Type System in TypeScript

    From Basic Types to Advanced Composition When you start using TypeScript seriously, you realize it’s not just about…

    1 Comment
  • JavaScript with Types : TypeScript

    Understanding TypeScript and Why It Matters JavaScript is powerful. But it is also dynamically typed.

    1 Comment
  • Advanced JavaScript : Closures, call/apply/bind, contexts and more

    Understanding advanced JavaScript is not about memorizing syntax. It is about understanding how execution, memory, and…

  • The Modern Web’s Messenger: Understanding the Fetch API

    The Modern Web’s Messenger: Understanding the Fetch API In the early days of the web, updating even a small piece of…

    1 Comment
  • Event Handling in JavaScript

    How Web Pages Become Interactive Without events, a website is just a static document. Nothing responds.

  • JavaScript and the DOM

    How Your Code Talks to the Web Page JavaScript becomes powerful when it connects to the page itself. That connection is…

Explore content categories