Learn how to create a functional server in NodeJS using libraries like express to create the backend. You will learn how to run a server, create routes, and middlewares.
What is Node.js?
Node.js is a JavaScript runtime environment built on Google Chrome’s V8 engine. It allows you to execute JavaScript code outside the browser, making it an excellent choice for creating server-side applications, such as APIs, web servers, and real-time applications.
One of Node.js’s key features is its focus on asynchronous programming, meaning it can handle multiple requests efficiently without blocking other operations. This makes it particularly useful for applications that need to manage a high volume of traffic or work with real-time data.
Prerequisites
Before you start creating a server in Node.js, make sure you have the following:
- Node.js installed on your system. You can download it from nodejs.org.
- A code editor, such as Visual Studio Code or any other of your choice.
- Basic knowledge of JavaScript and your operating system’s terminal.
Installing Node.js
If you don’t have Node.js installed, follow these steps:
- Download Node.js: Visit the official Node.js website and download the latest LTS (Long Term Support) version.
- Install: Open the downloaded file and follow the installation instructions. During the process, npm (Node Package Manager) will also be installed, which is useful for installing additional packages.
To check if the installation was successful, open your terminal and type the following commands:
node -v
This command should return the installed Node.js version. Then, check npm installation with:
npm -v
Both should show version numbers, confirming that Node.js and npm are correctly installed.
Creating a Server in Node.js
Now that you have everything set up, let’s move on to the exciting part: creating your own server. We will start with the basics and then add functionality.
Step 1: Initial setup
First, create a folder for your project. Open the terminal and run:
mkdir my-server
cd my-server
Then, initialize a Node.js project with the following command:
npm init -y
This command will create a package.json
file in your project, which is used to manage dependencies and scripts.
Step 2: Creating the server file
In your code editor, within the project folder, create a file called server.js
. This will be the main file that contains our server code.
In the server.js
file, write the following basic code to set up a server:
const http = require('http');
// Create the server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// Listen on port 3000
const port = 3000;
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Code Explanation
require('http')
: This command loads the HTTP module, which is built into Node.js. We need it to create a server.http.createServer()
: This method creates a server. The function passed as a parameter receives two objects:req
(the client request) andres
(the response we’ll send back to the client).res.statusCode = 200
: Sets the response status. Status code 200 indicates that everything went well.res.setHeader('Content-Type', 'text/plain')
: Sets the type of content the server will send. In this case, it’s plain text.res.end()
: Ends the response by sending the message “Hello, World!”.server.listen(port, callback)
: This method makes the server listen on the specified port (in this case, port 3000).
Step 3: Running the server
To run your server, go back to the terminal, make sure you’re in the project folder, and execute the following command:
node server.js
You should see the message in the console:
Server is running at http://localhost:3000
Open your browser and visit http://localhost:3000
. You should see the message “Hello, World!”.
Improving the Server: Simple Routes
The server we’ve created so far is very basic. Let’s improve it by adding a few routes so we can handle different requests.
Modify the code in the server.js
file as follows:
const http = require('http');
// Create the server
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain');
if (req.url === '/') {
res.statusCode = 200;
res.end('Welcome to the homepage\n');
} else if (req.url === '/about') {
res.statusCode = 200;
res.end('About us\n');
} else {
res.statusCode = 404;
res.end('Page not found\n');
}
});
// Listen on port 3000
const port = 3000;
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Explanation of the new code
req.url
: This object contains the URL requested by the client. Usingif
andelse if
, we handle different routes.- Routes handled:
/
: The homepage./about
: An “About Us” page.- If the user tries to access any other URL, we’ll respond with a 404 error.
Run the server again with node server.js
and test the routes http://localhost:3000/
and http://localhost:3000/about
. You can also try entering a non-existent route, like http://localhost:3000/unknown
, and you’ll see the 404 error message.
Using Express to Simplify Server Creation
Although Node.js’s native HTTP module is useful, managing many routes and requests manually in larger projects can become tedious. This is where Express, a minimalistic web framework, comes in handy. With Express, we can simplify the process of creating servers.
Installing Express
First, install Express by running the following command in your terminal:
npm install express
Creating a server with Express
Once Express is installed, let’s rewrite our server using this framework. Modify your server.js
file as follows:
const express = require('express');
const app = express();
// Homepage route
app.get('/', (req, res) => {
res.send('Welcome to the homepage');
});
// "About" route
app.get('/about', (req, res) => {
res.send('About us');
});
// Handle 404 errors
app.use((req, res) => {
res.status(404).send('Page not found');
});
// Listen on port 3000
const port = 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Explanation of the code with Express
express()
: Initializes a new Express application.app.get()
: Defines routes to handle GET requests. It simplifies route management compared to using the HTTP module.app.use()
: Handles any undefined route and sends a 404 error message.app.listen()
: Sets the port where the application will listen for requests.
Conclusion
In this article, we have learned how to create a server in Node.js using the basic HTTP module, and then we saw how we can improve our server by using Express to simplify route and response management. Both approaches have their advantages depending on the size and complexity of your project.
Node.js is a powerful and flexible tool that can help you create fast and scalable applications. If you are new to server development, I encourage you to experiment and expand the functionalities of your server, such as adding databases, authentication, and more.