Understanding the basics of Express Middleware
Published: 2022-12-28 09:23:24

In this article, we will understand what Express middleware is and how to use it in a NodeJS application.

As the name in itself is self explanatory, Express works as a middleware in an application. Typically an application is accessed from a client system to retrieve some information from a server. So, here there is a **Request** that is sent by the client to the server and there is a **Response** sent by the server back to the requesting client.

So, **Express Middleware** consists of functions that are executed after a **Request** is sent by client and before the **Response** is sent by the server. Something, that we want to execute in the middle of the **Request** and **Response**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fyxdlagmzn8xf8b28c1.png)

We can have multiple middlewares that can also modify the request object and then pass it to the next function in the sequence.

---

The base of Express is the **Application** object which is typically used as app. This app object exposes different methods and here we will take a look at the **listen**, **use**, **HTTP methods (get, put, post etc.)**.

## Create a server with app object

Whenever a website is created, it has a link / URL that we use to access the website. And as the website stays on a server, there is a client that comes into picture that calls the website's URL. So, now as the website is being called, there must be someone who is listening to the calls right? In this case, the server is the listener. And that is the purpose of the listen method of app. There is a port number where these calls from a client are getting listened by the server.

The syntax for creating a server using the app object is as below:

```
const express = require('express')

const app = express()
const port = 3000

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

Now the above code will make the server up and running at the port 3000. When we run the application we can see the message given in the console.log as below.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u2xea6e3yz83466h7n7.png)

---

Now, we need to define some endpoints (path/URI) in the code that will allow the users to call different pages of the website. For, eg. a website can have a Home Page, a Contact Page, an About Page and so on. Ideally, the URL would be something like https://somedomain/Home, https://somedomain/About, https://somedomain/Contact and so on. The part of the URL like /Home, /About, /Contact etc. is what is termed as the endpoint that we should be adding in our code using the app object. Here, the HTTP methods (get,put,post etc.) come into picture. Whenever we try to access the website's page, we get some information that is displayed in the browser. So, for the above mentioned pages, we should use the get method of app.

This is termed as **Routing**. Below is the definition of Routing from express official documentation.

> _Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on)._

The basic structure of a route is as following:

`app.METHOD(PATH, HANDLER)`

> 
**Where**:
> 
**app** is an instance of express.
**METHOD** is an HTTP request method, in lowercase.
**PATH** is a path on the server.
**HANDLER** is the function executed when the route is matched.

---

## Let's see how we can use the HTTP methods

Following example shows the **get** method:

```
app.get('/Home', (req, res) => {
  res.send('Welcome to the Home Page!')
})
```
The code snippet would be as below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hecl4q9thh6dozqqpwa.png)

It can be accessed in the browser using URL http://localhost:3000/home and we can see the following message:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ajc5lgurvhskxe18c6xx.png)

**An important point to note here is that if we try to access the link as http://localhost:3000, we will get an error that says _Cannot GET /_**

What does this error mean? It means that we have not specified the base path which is "/" in our code and we are still trying to access it in the browser.

Let us add the code for base path and see how it works. Following code snippet shows a new get method for base path.

```
app.get('/', (req, res) => {
    res.send('This is the base call!')
  })
```
The complete code till now looks like below:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhwflt3h2t8kxeenid96.png)

In the browser now if we access the URL as http://localhost:3000/, we see the below output.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6qlq3n57u41wiqgq3tq.png)

---
**The purpose of app.use method**

Now, let's understand what is the app.use method used for. From the definition app.use ->

> _Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path._

So, in a simple language, if we want to execute some logic before the a specific path is matched and the respective handler is executed, we can configure it using the app.use method.

For eg. app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on. So, if we call "apple/images", it will first execute handler of "/apple" and then the handler of "/apple/images"

If we configure a middleware **without a path** then it gets executed for **every request** to the app. For eg. the following function will be executed for every request.

```
app.use(function (req, res, next) {
  console.log('Time: %d', Date.now())
  next()
})
```
**_Middleware functions are executed sequentially, therefore the order of middleware inclusion is important._**

The sequential execution of functions is achieved using the **next()** function. As used in the above code snippet, we are using the next() call to ensure that the next function in the sequence is executed.

Following code illustrates this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emr95onrl6817m96lrgr.png)

**NOTE: You have to call the URL http://localhost:3000/ in the browser to see the output**

Let's see what happens if we remove the next() call from the function.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sdi1r6dsby4m2ogb8jci.png)

See, the log that we were seeing earlier after the Time was displayed (This is the base call!) does not appear now. This simply means that the control does not pass to the next function in sequence. So, it is important to decide the sequence of executing the functions and add those appropriately.

_I hope you have enjoyed this article and hope that it helped you in understanding the basics of Express. For more information you can definitely go through the official express documentation [here](https://expressjs.com/)._