DEV Community

Cover image for Understanding the basics of Express Middleware
Rutika Khaire
Rutika Khaire

Posted on

Understanding the basics of Express Middleware

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

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}`)
})
Enter fullscreen mode Exit fullscreen mode

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


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!')
})
Enter fullscreen mode Exit fullscreen mode

The code snippet would be as below:

Image description

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

Image description

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!')
  })
Enter fullscreen mode Exit fullscreen mode

The complete code till now looks like below:

Image description

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

Image description


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()
})
Enter fullscreen mode Exit fullscreen mode

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

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

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.

Top comments (0)