Nodejs Day#2: Building a Basic Backend with Pure Node.js (Without Express.js)

Day#2 Node.js: Building Basic Backend with Pure Nodejs

Sandeep Singh (Full Stack Dev.)
10 min readAug 16, 2023

Welcome to the exciting world of server-side programming with Node.js! In this comprehensive guide, we’ll embark on a journey to create a server from scratch using pure Node.js — no external libraries involved.

Whether you’re a developer student eager to learn or someone new to server-side concepts, we’ll break down the process in detail, with beginner-friendly code examples and real-world scenarios. Let’s dive in!

Note: In this article we will not use any external library like express.js for creating server backend. we will be using “Pure Nodejs for creating basic backend server

In further article we will use express.js for backend but intent of this article is to make your foundation stronger and make you understand how pure Nodejs backend works

so this article is very important for beginners to make foundation stronger

Understanding the Basics

Before we dive into the coding, let’s understand what a server is and what role it plays in web development.

In simple terms, a server is a computer program that receives and responds to requests from clients (usually web browsers). It’s the powerhouse that serves up web pages, data, and other resources.

If you are new to this series please consider reading our previous tutorial article for better understanding this article:

Link: https://sandydev.medium.com/node-js-day-1-unraveling-file-handling-magic-basics-of-node-js-ccbee5e8c70c

Setting Up the Environment

First, ensure you have Node.js installed on your system. If not, you can download it from the official website. Once installed, you’re ready to start building your server.

Start a project

  • Create a new folder and open with VS code
  • Now open terminal and run this “npm init -y” command in terminal to initialize nodejs project.
How to initialize Node.js Project

Creating a Basic Server

Let’s start by creating a basic server that listens for incoming requests on a specific port. Open your favorite code editor and create a file named server.js.

// server.js
// Import the 'http' module
const http = require('http');
// Create the server using the 'http.createServer()' method
const server = http.createServer((req, res) => {
// The server's response configuration starts here
// Set the response header with a status code of 200 (OK)
// and a content type of 'text/plain'
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body with the text 'Hello, Node.js Server!'
res.end('Hello, Node.js Server!');
// The server's response configuration ends here
});
// Define the port number the server will listen on
const PORT = 3000;
// Start the server and listen on the specified port
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

In this code, we’ve used the http module, which is built into Node.js, to create a server. When a request is received, we send back a simple "Hello, Node.js Server!" response.

If you don’t know about modules, Please consider our previous tutorial in which we have discussed about modules:

Link: https://sandydev.medium.com/node-js-day-1-unraveling-file-handling-magic-basics-of-node-js-ccbee5e8c70c

Note: In this article we will not use any external library like express.js for creating server backend. we will be using pure Nodejs for creating basic backend server

In further article we will use express.js for backend but intent of this article is to make your foundation stronger and make you understand how pure Nodejs backend works

so this article is very important for beginners to make foundation stronger

Routing Requests

In web development, routing refers to directing requests to the appropriate handler based on the URL. Let’s create a basic routing mechanism for our server.

In this code example, we’re enhancing our server to handle different URLs by implementing a basic routing mechanism. Let’s break it down step by step:

// Import the 'http' module
const http = require('http');
// Create the server using the 'http.createServer()' method
const server = http.createServer((req, res) => {
// Check the URL of the incoming request
if (req.url === '/') {
// If the URL is '/', set the response header and send the message
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the homepage!');
} else if (req.url === '/about') {
// If the URL is '/about', set the response header and send the message
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About us: We are a group of passionate Node.js enthusiasts.');
} else {
// For any other URL, set a 404 response header and send a 'Page not found.' message
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found.');
}
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

We continue to use the http.createServer() method to create our server instance.

Inside the callback function, we examine the req.url property to determine the URL of the incoming request.

We use a series of if and else if statements to handle different scenarios based on the URL:

  • If the URL is '/' (root), we set the response header to indicate a status code of 200 (OK) and a content type of 'text/plain'. We then send the message 'Welcome to the homepage!' as the response body.
  • If the URL is '/about', we again set the response header with a status code of 200 (OK) and a content type of 'text/plain'. This time, we send the message 'About us: We are a group of passionate Node.js enthusiasts.'.
  • If the URL doesn’t match either of the above cases, we set a 404 response header to indicate that the requested page was not found. We send the message ‘Page not found.’ as the response body.

The remainder of the code, including defining the server’s listening port and starting the server, remains the same as in the previous example.

Handling Requests and Responses

In this code example, we’re taking request and response handling to the next level by considering the HTTP request methods (GET, POST, PUT, DELETE). Let’s explore each step in detail:

// Import the 'http' module
const http = require('http');
// Create the server using the 'http.createServer()' method
const server = http.createServer((req, res) => {
// Check the HTTP request method of the incoming request
if (req.method === 'GET') {
// For GET requests
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the homepage!');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About us: We are a dedicated Node.js enthusiasts group.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found.');
}
} else if (req.method === 'POST') {
// For POST requests (handle the logic here)
// we will discuss about POST requests in upcoming tutorials,
//for now just undertsand how API requests and responses handles in pure NODE.JS

} else if (req.method === 'PUT') {
// For PUT requests (handle the logic here)

// we will discuss about PUT requests in upcoming tutorials,
//for now just undertsand how API requests and responses handles in pure NODE.JS

} else if (req.method === 'DELETE') {
// For DELETE requests (handle the logic here)

// we will discuss about DELETE requests in upcoming tutorials,
//for now just undertsand how API requests and responses handles in pure NODE.JS
}
});


const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

We continue to use the http.createServer() method to create our server instance.

Inside the callback function, we examine the req.method property to identify the HTTP request method of the incoming request.

We use a series of if and else if statements to handle different scenarios based on the request method:

  • For GET requests, we check the URL just as we did in the previous example. If the URL is '/', we send a welcome message. If it's '/about', we send information about the group. Otherwise, we send a 404 response for unknown URLs.
  • For POST requests, there’s a placeholder comment (// For POST requests (handle the logic here)). This is where you would write the logic to handle incoming POST data and respond accordingly.
  • For PUT requests, similarly, there’s a placeholder comment (// For PUT requests (handle the logic here)). This is where you would handle incoming data for updating resources.
  • For DELETE requests, you guessed it, a placeholder comment (// For DELETE requests (handle the logic here)). Here, you'd manage the logic for deleting resources.

As before, the remainder of the code — defining the server’s listening port and starting the server — remains unchanged.

How to Test this Backend Server & API Routes

  • Add this lines to package.json file.
add custom commands in package.json in Node.js project
  • Now run this command in terminal in VS code
How to start nodejs server
  • After running the command our server will start and will showing this output in terminal
Server started output in nodejs
  • Now lets test out GET request with browser (Note: All other requests(PUT, DELETE, POST,etc.) will test in upcoming tutorials, These requests can’t be directly test from browser we will require Postman like tools for them, will discuss further)
GET request API test with browser in Nodejs
Test APIs created with Nodejs

Real-World Application: Creating an API

Let’s bring it all together by creating a simple API that provides information about users. We’ll use JSON for data representation.

In this code example, we’re taking the theory we’ve covered so far and applying it to create a practical API that serves user data. Here’s a step-by-step explanation:

// Import the 'http' module
const http = require('http');

// Our array of users
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// Create the server using the 'http.createServer()' method
const server = http.createServer((req, res) => {
// Check the HTTP request method of the incoming request
if (req.method === 'GET') {
// For GET requests
if (req.url === '/users') {
// Set the response header to indicate JSON content
res.writeHead(200, { 'Content-Type': 'application/json' });
// Convert the 'users' array to JSON and send it as the response
res.end(JSON.stringify(users));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Endpoint not found.');
}
}
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

We continue to use the http.createServer() method to create our server instance.

We’ve defined an array named users that contains user data. This data represents our source of information for the API.

Inside the callback function, we examine the req.method property to identify the HTTP request method of the incoming request.

For GET requests, we once again check the URL. If the URL is '/users', we prepare to send a response with JSON content.

We set the response header to 'application/json' using the res.writeHead() method. This informs the client that the response will be in JSON format.

We use the JSON.stringify() method to convert the users array to a JSON string. This makes it ready for sending as the response body.

Finally, we send the JSON-formatted users array as the response.

For any other URL, we send a 404 response with the message 'Endpoint not found.'.

The remainder of the code, including defining the server’s listening port and starting the server, remains the same as in the previous examples.

Note: In this article we will not use any external library like express.js for creating server backend. we will be using pure Nodejs for creating basic backend server

In further article we will use express.js for backend but intent of this article is to make your foundation stronger and make you understand how pure Nodejs backend works

so this article is very important for beginners to make foundation stronger

Conclusion

Congratulations! You’ve successfully built a basic server in Node.js from scratch, learned about routing, and explored how to handle different types of requests and responses. You’ve also created a simple API, showing how these concepts come together in real-world scenarios.

Remember, this is just the beginning of your journey into server-side programming. As you delve deeper, you’ll uncover more advanced topics and techniques that will empower you to build robust, feature-rich applications. Keep exploring, practicing, and expanding your knowledge — the world of Node.js awaits your creativity and innovation.

Note: In this article we will not use any external library like express.js for creating server backend. we will be using pure Nodejs for creating basic backend server

In further article we will use express.js for backend but intent of this article is to make your foundation stronger and make you understand how pure Nodejs backend works

so this article is very important for beginners to make foundation stronger

FAQs

Can I use libraries like Express.js for routing?

Absolutely! While this guide focused on building without libraries to make your foundation stronger, we will be using Express.js for upcoming tutorial articles+videos.

But making your foundation stronger is really very important fro moving forward to libraries and frameworks. Express.js is a popular choice that simplifies routing and provides additional features.

How can I deploy my server to the internet?

To deploy your server online, you can explore platforms like Heroku, DigitalOcean, or AWS. They offer guides to help you get started.

Are there security considerations when handling requests?

Yes, security is crucial. Ensure you validate and sanitize user input to prevent attacks like SQL injection and cross-site scripting (XSS).

Can I add authentication to my server?

Yes, you can implement authentication using techniques like JSON Web Tokens (JWT) or OAuth. It’s an important aspect for securing your applications.

What’s next after building this server?

Congratulations, you’re on the right track! Consider expanding your knowledge by learning about databases, authentication, and more advanced server-side concepts.

--

--

Sandeep Singh (Full Stack Dev.)

Fullstack Developer | MERN & Flutter | Passionate about Open Source | Engaged in Contributing & Collaborating for a Better Tech Community. 🚀