DEV Community

SOVANNARO
SOVANNARO

Posted on

1

Creating a Node.js Server from Scratch πŸš€

Hey there, awesome devs! πŸ‘‹ Have you ever wondered how web servers work? What if I told you that you can create your own server in just a few lines of JavaScript? 🀯

With Node.js, you don’t need a fancy framework to build a basic server. The built-in HTTP module lets you create a web server that can handle requests and send responsesβ€”just like a real web app! πŸ’‘

In this blog, we’ll go step by step to build a simple Node.js server. By the end, you’ll understand how servers work and feel like a backend ninja! πŸ₯·πŸ”₯


🌍 What is a Web Server?

A web server is a program that listens for requests from a client (like a browser) and responds with data (like an HTML page or JSON). It acts as the middleman between users and your website.

βœ… When you visit example.com, your browser sends a request to a web server.
βœ… The server processes the request and sends back a response (HTML, JSON, files, etc.).
βœ… Your browser displays the response, and voilΓ ! πŸŽ‰

Now, let's build our own server! πŸ—οΈ


πŸš€ Step 1: Setting Up Your Project

First, make sure you have Node.js installed. You can check by running:

node -v
Enter fullscreen mode Exit fullscreen mode

If Node.js is installed, you'll see a version number. If not, download it from nodejs.org. βœ…

Create a new project folder and navigate to it:

mkdir my-node-server && cd my-node-server
Enter fullscreen mode Exit fullscreen mode

Now, let's create our server file:

touch server.js
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Step 2: Creating a Basic Node.js Server

Now, open server.js and add the following code:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, world! 🌍');
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000 πŸš€');
});
Enter fullscreen mode Exit fullscreen mode

βœ… How it works:

  • We import the http module.
  • We use http.createServer() to create a server.
  • When a request comes in, we send a plain text response.
  • The server listens on port 3000.

Run the server with:

node server.js
Enter fullscreen mode Exit fullscreen mode

Now, open your browser and visit http://localhost:3000β€”you should see "Hello, world!" πŸŽ‰


πŸ“‘ Step 3: Handling Different Routes

A real web server should respond differently based on the URL (route). Let's modify our server to handle multiple routes:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    if (req.url === '/') {
        res.end('Welcome to the Home Page! 🏠');
    } else if (req.url === '/about') {
        res.end('About Us Page πŸ“–');
    } else {
        res.writeHead(404);
        res.end('404 Not Found ❌');
    }
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000 πŸš€');
});
Enter fullscreen mode Exit fullscreen mode

βœ… Now try:

  • http://localhost:3000/ 🏠 (Home page)
  • http://localhost:3000/about πŸ“– (About page)
  • http://localhost:3000/contact ❌ (Oops! 404 error)

πŸ–₯️ Step 4: Sending an HTML Response

Instead of plain text, let's send HTML:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to My Node.js Server! πŸš€</h1>');
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000 πŸš€');
});
Enter fullscreen mode Exit fullscreen mode

βœ… Now, visiting http://localhost:3000 will display styled HTML content! 🎨


πŸ”₯ Step 5: Serving JSON (for APIs)

Let's modify our server to respond with JSON data instead:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    const data = { message: 'Hello, this is JSON data! πŸš€' };
    res.end(JSON.stringify(data));
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000 πŸš€');
});
Enter fullscreen mode Exit fullscreen mode

βœ… Now, visiting http://localhost:3000 will return JSON dataβ€”great for building APIs! πŸ“‘


🎯 Conclusion

Boom! You just built a fully functional Node.js server from scratch! πŸŽ‰ Now, you understand how web servers work and can start building real-world applications!

πŸš€ Recap:

  • Created a simple Node.js server with the HTTP module.
  • Handled multiple routes (Home, About, 404 errors).
  • Sent HTML and JSON responses for different use cases.
  • Learned how web servers work under the hood.

In the next article, we’ll explore JSON Response, Stay tuned! πŸ”₯

If you found this blog helpful, make sure to follow me on GitHub πŸ‘‰ github.com/sovannaro and drop a ⭐. Your support keeps me motivated to create more awesome content! 😍

Happy coding! πŸ’»πŸ”₯

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
m__mdy__m profile image
genix β€’

This is very good, but you can inherit from Server for Http protocol and handle it better.
(not good for production environment)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay