Are you ready to create your first backend project with Node.js? In this post, you’ll learn how to build a basic Node.js HTTP server that handles different routes and sends back responses — all using core Node modules (no frameworks like Express yet!).
Let’s break it down step by step and explain exactly what’s happening behind the scenes. 💡
🛠️ Step 1: Set Up Your Project
Before writing any code, we need a place to put it:
mkdir my-nodejs-server
cd my-nodejs-server
npm init -y
This creates a new project folder and initializes it with a default package.json
file.
✨ Step 2: Create Your Server File
Now let’s create the file that will run your server:
touch server.js
Open server.js
in your code editor (VS Code, Vim, or anything else you like).
💻 Step 3: Write Your First HTTP Server
🔹 1. Import the HTTP Module
const http = require('http');
👉 This brings in Node.js’s built-in http
module, which lets us create web servers. No need to install anything extra!
🔹 2. Create the Server
const server = http.createServer((req, res) => {
// Request handler logic goes here
});
-
req
: The request object (contains details about the request — like the URL and method). -
res
: The response object (we’ll use this to send data back to the browser).
🔹 3. Handle Routes
Now let’s respond based on the URL path requested:
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World! 🌍\n');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('About Us 📖\n');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Page Not Found 🚨\n');
}
});
What’s happening here?
- We inspect
req.url
to determine which page was requested. - We respond with appropriate text for
/
,/about
, or anything else (which returns a 404).
🔹 4. Start Listening for Requests
Finally, let’s make our server start listening:
const port = 3000;
const hostname = '127.0.0.1';
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/ 🎉`);
});
✅ 127.0.0.1
is your localhost IP.
✅ 3000
is the port where the server will run.
✅ The callback confirms when the server is up.
📜 Full Code: server.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World! 🌍\n');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('About Us 📖\n');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Page Not Found 🚨\n');
}
});
const port = 3000;
const hostname = '127.0.0.1';
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/ 🎉`);
});
⚡ Step 4: Run and Test Your Server
Start the server:
node server.js
Now open your browser and visit:
- ✅ http://127.0.0.1:3000/ → Should show
Hello, World! 🌍
- ✅ http://127.0.0.1:3000/about → Should show
About Us 📖
- ❌ http://127.0.0.1:3000/contact → Should show
Page Not Found 🚨
To stop the server, hit Ctrl + C
in your terminal.
🧠 How It All Works Behind the Scenes
Here’s a simplified flow:
- The browser sends a GET request to your server.
- Node’s
http
module captures it. - Your code checks the requested route (
req.url
). - A response is built and returned with
res.end()
. - The browser receives and displays it.
🛤️ Key Takeaways
Concept | Description |
---|---|
req.url |
The path the client is requesting (/ , /about , etc.) |
res.statusCode |
Sets HTTP status like 200 (OK) or 404 (Not Found) |
res.setHeader() |
Tells the browser what type of content it’s getting |
res.end() |
Ends the response and sends it to the client |
🎉 Final Words
You just built a fully functioning Node.js HTTP server with zero dependencies. 🎉
It’s a simple project — but a foundational one. From here, you can build more complex backend systems and eventually integrate databases, authentication, REST APIs, and beyond.
Happy coding! 💻✨
Top comments (0)