Skip to content

Introduction to Express

Express

Express is a free and open-source Node.js web application server framework which is specifically designed for the building a web applications. It is the most popular choice to building web applications with a Node.js. Express is basically a fairly simple server application framework. It's one of the more stable packages in the JavaScript ecosystem, meaning that it doesn't get a new release every two weeks. It's been a safe bet in many real life projects.

It's a framework that let's you structure a server application to handle multiple different HTTP requests at a specific url. It integrates with "view" rendering engines in order to generate responses by inserting data into templates. However in this course we only create a lot of endpoints to return data to the client, but of course you can use it's template engine to generate a views too.

Express adds additional request processing "middleware" at any point within the request handling pipeline. While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

However there are other similar frameworks and libraries (such as hapi, fastify and koa) that fill the role of express - many of them might be more well-suited to certain types of server applications. However since express is so common and almost the de-facto standard, we'll be using it during the course. It also helps that pretty much every other library and framework owes a lot to express in the form of its middleware oriented design.

With Express you are building server applications / backend applications. As a backend application, Node.js application, it is like a glue between frontend application and database or other data source in backend.

Install Express

You can install Express in your app directory and save it in the dependencies list with below command:

1
npm i express

Above command will install the express module into node_modules in the current directory. And it will include express dependency in your package.json file. Express version was 4.18.2 when this material is written.

1
2
3
4
5
6
{
  // ...
  "dependencies": {
    "express": "^4.18.2"
  }
}

Running a web server

Create Node.js project and modify index.js to use express (require it and create express app) and start a web server. This is basicly a template which will be created in every project when start using an express. Now functionality is minimal and this will scaled up to handle more endpoints later.

index.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const express = require('express') 
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.status(200).send('<h1>Home Page</h1>')
})

app.listen(port, () => {
  console.log(`Server is listening on port ${port}...`)
})

This app starts a server and listens on port 3000 for connections. The app responds with Home Page for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

Once you start your application on the command line with node index.js, you should be able to see the output in the command line:

1
2
node index.js
Server is listening on port 3000...

Remember, that you should edit your package.json and create a new start script to launch your project.

1
2
3
4
"scripts": {
    "start": "node index.js"
    //...
  },

Now launch your project with npm start command.

1
2
3
4
5
6
npm start

> webserver1@1.0.0 start /Users/pasi/Node/express/webserver1
> node index.js

Server is listening on port 3000...

Your Express web server is up and running. Application is available at http://localhost:3000 in the browser and should display Home Page header.

Tip

Install nodemon to automatically restarting the node application when file changes in the directory are detected.

  • Give command npm install --save-dev nodemon
  • Edit package.json file to start nodemon
1
2
3
4
5
"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
},
  • Start your project with npm run dev

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

index.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const express = require('express') 
const path = require('path')
const app = express()
const port = 3000

// store static files to public folder
app.use(express.static('./public'))

app.listen(port, () => {
  console.log(`Server is listening on port ${port}...`)
})

And put all the static files to public folder inside your project.

public/index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Express serve static files</title>
</head>
<body>
  <h1>Express - serve static files</h1>
  <p>
    <img src="mapas.jpeg"/>
  </p>
</body>
</html>

Using environmental variables

Now we are used only hardcoded values in your code - like application port. In a real-life applications we have configuration that varies from environment to environment - from local development all the way to the production environment.

You can use dotenv package, which is a zero-dependency module that loads environment variables from a .env file into process.env. You can use process.env property to return your value.

You can install dotenv as a dependency:

1
npm i dotenv

Now dotenv will be included your package.json dependencies:

1
2
3
4
5
6
7
{
  //...
  "dependencies": {
    "express": "^4.18.2",
    "dotenv": "^16.0.3"
  }
}

Create .env file to your project folder and add a port number used.

1
PORT=3000

Then in your index.js file you'll require it.

1
2
require('dotenv').config()
const express = require("express")

Modify your code to use defined port.

1
2
3
app.listen(process.env.PORT, () => {
  console.log(`Server is listening on port ${process.env.PORT}...`)
})

Environment variables are used things like credentials, which is not wanted to be exposed to the outside world.

Note

Remember add .env to .gitignore file.

Continue learning!

The main purpose why we are using an Express is to create REST API's. You will learn that in next.

Read more

Goals of this topic

Understand

  • What Express is.
  • Know how to create a simple Express application.
  • Know what environmental variables are and how to use them.