Webserver Creation
Last Updated : 2026
We are going to create a basic webserver to understand how it works.To understand better we divided it into 3 Parts:
- Setup and Server Creation
- GET Request
- POST Request
Setup and Server Creation
So let's start with the following steps to setup our project:
Step 1: Create a folder for your project
Run this in your terminal:
mkdir your-project-name
Step 2: Change directory to your project folder
Run this in your terminal:
cd your-project-name
Step 3: make a file called server.js
Run this in your terminal:
touch server.js
Step 4: Initialize package.json
Run this in your terminal:
npm init -y
Step 5: Install nodemon as a development dependency
nodemon is a tool that allows you to automatically restart your Node.js server when you make changes to your code.
Run this in your terminal:
npm i -D nodemon
Step 6: Add nodemon as a scripts in package.json and type: module after version
{
"name": "your-project-name",
"version": "1.0.0",
"type": "module",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
...
...
...
}
Step 7: install dotenv
dotenv is a zero-dependency module that loads environment variables from a .env file into process.env
Run this in your terminal:
npm i dotenv
Step 8: Create a .env file
Run this in your terminal:
touch .env
Step 9: Add PORT in .env file
PORT=80
Step 10: On server.js, add the following code:
import http from "node:http";
import dotenv from "dotenv";
dotenv.config();
const server = http.createServer((req, res) => {
res.end("Hello World!");
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Note : Always remember dotenv.config(); should be before creating a server
Step 11: Run npm run dev to start the server
Step 12: Open your browser and go to http://localhost:80
Step 13: You should see "Hello World!"
That is it! You have successfully setup your project for webserver creation.
GET Request
Step 1: Create a file called getRequests.js
Run this in your terminal:
touch getRequests.js
Step 2: Add the following code:
import fs from "node:fs/promises";
import path from "node:path";
export const getRequests = async (req, res) => {
switch (req.url) {
case "/":
res.writeHead(200, { "Content-Type": "text/html" });
res.end(`
<h1>Home Page</h1>
<ul>
<li><a href="/about">About</a></li>
<li><a href="/code.js">Code</a></li>
<li><a href="/style.css">Style</a></li>
<li><a href="/data.json">Data</a></li>
<li><a href="/image.png">Image</a></li>
</ul>
`);
break;
case "/about":
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>About Page</h1>");
break;
case "/code.js":
res.writeHead(200, { "Content-Type": "text/javascript" });
res.end("console.log('This is code.js')");
break;
case "/style.css":
res.writeHead(200, { "Content-Type": "text/css" });
res.end("h1 { color: red; }");
break;
case "/data.json":
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
name: "Sadhu",
age: 3,
}),
);
break;
case "/image.png":
res.writeHead(200, { "Content-Type": "image/png" });
const imgStream = await fs.readFile(path.resolve("tl.png"));
res.end(imgStream);
break;
default:
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Page not found</h1>");
break;
}
};
let's understand this code:
- we are using fs module to read the file and send it to the client
- we are using path module to get the path of the file
- we are using switch statement to handle different routes with different responses and methods
- / is the home page
- /about is the about page
- /code.js is the code page
- /style.css is the style page
- /data.json is the data page
- /image.png is the image page
- default is the 404 page
Step 3: Import emitter to see the request on server.js and also import getRequests.Add the following code on server.js:
import http from "node:http";
import dotenv from "dotenv";
import path from "node:path";
import emitter from "events";
import { getRequests } from "./getRequests.js";
dotenv.config();
const myEmitter = new emitter();
myEmitter.on("log", (msg) => console.log(msg));
const server = http.createServer((req, res) => {
myEmitter.emit("log", `Request for ${req.url}\t Request Type: ${req.method}`);
if (req.method === "GET") {
getRequests(req, res);
}
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
POST Request
Step 1: Create a file called postRequests.js
Run this in your terminal:
touch postRequests.js
Step 2: Add the following code:
const fakeData = [];
export const postRequests = async (req, res) => {
let body = "";
switch (req.url) {
case "/":
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
const newData = JSON.parse(body);
fakeData.push(newData);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(fakeData));
});
break;
default:
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
};
Let's understand this code:
- Make a variable called fakeData to store the data
- we are using switch statement to handle different routes with different responses and methods
- / is to add new Data Parse from the body
- default is the 404 page
Step 3: Modify createServer function in server.js and import postRequests.Add the following code:
const server = http.createServer((req, res) => {
myEmitter.emit("log", `Request for ${req.url}\t Request Type: ${req.method}`);
if (req.method === "GET") {
getRequests(req, res);
} else if (req.method === "POST") {
postRequests(req, res);
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
Step 4: Run the server and test it.
Note: To Make a POST request, you can use any tool like Postman or Insomnia or ThunkClient etc.
