Node.js has become one of the most popular choices for server-side development since its initial release over a decade ago. While it's still relatively new when compared to PHP and other backend technologies, it's been widely adopted by tech giants such as LinkedIn, PayPal, Netflix, and more.

This article will teach you how you can build and run your own web server with Node.js and the Express.js web framework.

Technologies and Packages Involved

Node.js is a JavaScript runtime built on Chrome's V8 engine that allows you to execute JavaScript code outside the browser. Traditionally, the JavaScript programming language is used for manipulating the Document Object Model (DOM), adding interactivity to websites.

Because of this, JavaScript code was restricted to run solely in the browser since the DOM exists on web pages only. With Node.js, you can run JavaScript in the command-line and on servers. Therefore, it's essential to install Node.js and npm on your machine before you get started.

On the other hand, Express.js is a minimalistic web framework that has become the de facto backend framework for Node.js. However, Express.js is not a necessity. You can still use the built-in http module of Node.js to build your server. Express.js is built on top of the http module and provides a simpler API with all the necessary configurations.

Building a Web Server

To better organize your code, you can start by creating a folder where all the files and dependencies will reside. Since Express.js isn't a built-in Node.js module, you'll have to install it using npm.

Read More: What Is npm?

To install the Express.js package, run the command npm install express on your terminal or command prompt. Make sure you're inside the project directory before installing.

Install express via npm

Once completed, you can open the folder using a text editor or IDE of your choice and create a new file named server.js. To use the Express.js package, you must first import and create an instance of it inside the server.js file like so:

        const express = require('express');
const app = express();

The main aim of a web server is to respond to the requests coming in from different routes with the appropriate handler function. This code handles all GET requests made to the root ("/") path and responds with "Hello World!"

        app.get('/', (req, res) => {
    res.send('<h1>Hello World</h1>');
});

Similarly, you can display dynamic content and perform other operations depending on the path and the type of request you make. This can be done using route parameters, denoted by the semicolon : in front of the parameter.

        app.get('/:name', (req, res) => {
    res.send(`<h1>Welcome to ${req.params.name}!</h1>`);
};

In both examples above, the first line represents the usage of the .get() method of Express.js that takes in 2 parameters: the endpoint or route, and a callback handler function that takes requests and response objects as parameters. These 2 parameters are automatically sent when you make a request.

In the second line, the response is made through the .send() method on the response object. Inside the parenthesis, you can enter whatever text or HTML you want. In the case of dynamic routes, accessing req.params.name (since you've used /:name) of the request object will return the value of the dynamic route parameter (name in this case.)

Finally, to start listening to incoming requests on a port, you can use the .listen() method which takes the port number and an optional callback function to run on successful execution.

        app.listen(5000, console.log('Server is running on port 5000'));

I've used port 5000 in the example, but you can change it to any valid port. That's all the code you need to build a basic web server with Node.js and Express.js. The same concept can be extended further to make other requests such as POST, PUT, or DELETE to other routes. Here's how the server.js file will look like:

ExpressJS code for web server

Testing the Server

To execute the code and start the server, run the node server command on your terminal or command prompt in the project directory. This will execute the callback function you provided on the .listen() method.

Express server running

To confirm that the server is working, open up a web browser and visit http://localhost:5000

Express.js - root route demo

Similarly, if you visit a dynamic route such as http://localhost:5000/muo, the second handler function will run and display:

Express.js - Dynamic route demo

To stop the server, press Ctrl + C on Windows or Cmd + C on macOS.

Node.js Can Do More

JavaScript's popularity is rising sharply as developers utilize it on the frontend as well as the backend. This eliminates the need to learn multiple programming languages and helps you kickstart your journey as a full-stack web developer using only JavaScript.

If you decide you'd rather give Google's programming language a Go, building a basic web server is a great starter project.