Express.js (or "Express") is a NodeJS web framework used on the back-end (or server-side) of websites and web applications. Express is flexible and minimalistic, which means that it doesn’t have an extensive collection of unnecessary libraries and packages, nor does it dictate how you should build your application.

The Express framework builds APIs that facilitate communication through HTTP requests and responses. One of the remarkable things about Express is that it gives developers complete control over the requests and responses that are associated with each of its app’s methods.

In this tutorial, you’ll learn how and why you should use Express in your own projects.

Installing Express in Your Project

Before you can use the Express framework, you’ll need to install it in your project directory. This is a straightforward process that requires NodeJS and npm.

The first thing you’ll need to do is create a package.json file (within your project directory/folder) using the following command:

        npm init

Executing the command above will initiate a process that’ll prompt you for the following inputs:

  • Package name
  • Version
  • Description
  • Entry point
  • Test command
  • Keywords
  • Author
  • License

The package name, version, entry point, and license fields all have default values that you can easily override by providing your values. However, if you want to keep the default values you can simply use the following command instead:

        npm init -y

Executing the command above will generate the following package.json file in your project directory:

        {

"name": "myapp",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"keywords": [],

"author": "",

"license": "ISC",

}

Now you can install Express using the following command:

        npm install express --save

Installing Express will generate a package-lock.json file as well as a node_modules folder.

Understanding the package.json File

The reason you need to create a package.json file before installing Express is that the package.json file acts as a a repository, storing important metadata about your NodeJS projects. Dependencies is the name of one of these metadata fields, and Express is a dependency.

Installing Express in your project directory will automatically update your package.json file.

The Updated package.json File

        {

"name": "myapp",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"keywords": [],

"author": "",

"license": "ISC",

"dependencies": {

"express": "^4.17.1"

}
}

Now you have a “dependencies” field that has one dependency—Express. And the dependencies object stores software that your project depends on to function correctly, which in this case is the Express framework.

Creating a Server With Express

Having an API that handles the storage and movement of data is a requirement for any full-stack application, and Express makes the server creation process fast and easy.

Look back at the package.json file above and you’ll see a “main” field. This field stores the entry point to your application, which is “index.js” in the example above. When you want to execute your application (or in this instance, the server that you’re about to build), you’ll have to execute the index.js file using the following command:

        node index.js

However, before you get to the execution stage, you’ll need to create the index.js (or server app) file in your project directory.

Creating the index.js File

        const express = require('express');



const app = express();

const port = 5000;



app.get('/', (req, res) => {

res.send('Your server is operational')

})



app.listen(port, () => {

console.log(`Server is running at: http://localhost:${port}`);

})

The file above imports Express then uses it to create an Express application. The Express application then provides access to the get and listen methods that are a part of the Express module. The app.listen() method is the first one you need to set up. Its purpose is to list for connections on a specific port of the host computer, which is port 5000 in the example above.

The purpose of the app.get() method is to get data from a specific resource. This method has two arguments: a path and a callback function. The path argument in the example above has a forward slash that represents the root position. Therefore, navigating to the http://localhost:5000 URL (which is the root of your application), while your index.js app above is running, will produce the following output in your browser:

Express server app

The app.get() method callback function generates the output above. This callback function has two arguments—request and response. The response (which is res in the example above) is the HTTP object that an Express app sends after an HTTP request (which is what you do by typing the URL above in your browser).

Serving a Static Website With Your Express Server

Servers play a significant role in the development of APIs that help store and transfer dynamic data, and that’s where you’ll most likely use an Express server in your own projects.

However, an Express server can also serve static files. For example, if you wanted to create a static website (such as one for a personal trainer, a life coach, or a stylist), then you can use your Express server to host the website.

A Static HTML Website Example

        <!DOCTYPE html>

<html lang="en">

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">

<link href="https://fonts.googleapis.com/css?family=Lato|Staatliches" rel="stylesheet">

<link rel="stylesheet" href="css/style.css">

<title>Personal Stylist Website</title>

</head>

<body>

<nav id="navbar">

<div class="container">

<div>

<h1><i class="fas fa-vest"></i> Personal Stylist</h1>

</div>

<div class="social">

<a href="http://facebook.com" target="_blank"><i class="fab fa-facebook"></i></a>

<a href="http://twitter.com" target="_blank"><i class="fab fa-twitter"></i></a>

<a href="http://instagram.com" target="_blank"><i class="fab fa-instagram"></i></a>

<a href="http://youtube.com" target="_blank"><i class="fab fa-youtube"></i></a>

</div>

<ul>

<li><a class="current" href="#home">Home</a></li>

<li><a href="#">About</a></li>

<li><a href="#">Services</a></li>

<li><a href="#">Contact</a></li>

</ul>

</div>

</nav>



<!-- home -->

<header id="home">

<div class="container">

<div class="showcase-container">

<div class="showcase-content">

<h2>Welcome</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Possimus rerum officia quibusdam mollitia deserunt animi soluta laudantium. Quam sapiente a dolorum magnam necessitatibus quis tempore facere totam. Dolor, sequi distinctio!</p>

<a href="#articles" class="btn ">View Services</a>

</div>

</div>

</div>

</header>



</body>

</html>

The HTML code above creates a pleasant static home page of a personal stylist website by linking to the following style.css file:

        *{

margin: 0;

padding: 0;

box-sizing: border-box;

}



body {

font-family: 'Lato', sans-serif;

line-height: 1.5;

}



a {

color: #333;

text-decoration: none;

}



ul {

list-style: none;

}



p {

margin: .5rem 0;

}

h1{

margin-left: 2rem;

}



/* Utility */

.container {

max-width: 1100px;

margin: auto;

padding: 0 2rem;

overflow: hidden;

}



.btn {

display: inline-block;

border: none;

background: #910505;

color: #fff;

padding: 0.5rem 1rem;

border-radius: 0.5rem;

}



.btn:hover {

opacity: 0.9;

}



/* Navbar */

#navbar {

background: #fff;

position: sticky;

top: 0;

z-index: 2;

}



#navbar .container {

display: grid;

grid-template-columns: 6fr 3fr 2fr;

padding: 1rem;

align-items: center;

}



#navbar h1 {

color: #b30707;

}



#navbar ul {

justify-self: end;

display: flex;

margin-right: 3.5rem;

}



#navbar ul li a {

padding: 0.5rem;

font-weight: bold;

}



#navbar ul li a.current {

background: #b30707;

color: #fff;

}



#navbar ul li a:hover {

background: #f3f3f3;

color: #333;

}



#navbar .social {

justify-self: center;

}



#navbar .social i {

color: #777;

margin-right: .5rem;

}



/* home */

#home {

color: #fff;

background: #333;

padding: 2rem;

position: relative;

}



#home:before {

content: '';

background: url(https://source.unsplash.com/random) no-repeat center center/cover;

position: absolute;

top: 0;

left: 0;

width: 100%;

height: 100%;

opacity: 0.4;

}



#home .showcase-container {

display: grid;

grid-template-columns: repeat(2, 1fr);

justify-content: center;

align-items: center;

height: 100vh;

}



#home .showcase-content {

z-index: 1;

}



#home .showcase-content p {

margin-bottom: 1rem;

}

Serving the Website With the Express Server

        const express = require('express');



const app = express();

const port = 5000;



app.use(express.static('public'));



app.get('/', (req, res) => {

res.sendFile('index.html')

})



app.listen(port, () => {

console.log(`Server is running at: http://localhost:${port}`);

})

The HTML and CSS files above are in a public folder in the main project directory. The HTML file’s location makes it accessible to the Express server and its functions.

One of the new functions in the Express server above is the app.use() method. It mounts the express.static() middleware, which serves static files. This makes it possible to use the res.sendFile() function to serve the static index.html file above.

Navigating to the http://localhost:5000 location in your browser will display something similar to the following output:

Serving static website

Explore Backend Development

The Express framework allows you to make specific HTTP requests and receive appropriate responses using a set of predefined methods. It’s also one of the most popular backend frameworks today.

Learning how to use the Express framework is a great move. But if you genuinely want to become a professional backend developer, there’s a lot more you need to learn.