Skip to content

Middleware

Introduction

Express middleware functions are in the middle of the client's request and the server's response. So they are executed in the middle of the request-response cycle. Middleware functions has access to the request and response objects. These functions are used to authentication, detect request headers, parsing request bodies, handling errors, etc...

graph LR A[Request] --> B[Middleware] --> C[Response]

Note

Middleware functions are executed in that order how they exists in the code.

In an Express each handler function is a middleware function - the signature of the handler function is identical to that of a middleware function. A middleware function might be something like a logging function, which logs the date and time of the request before passing it forward to the next middleware in the chain.

Logger example middleware

Below is a simple function that can be used as a middleware in Express. The next() function is required for transferring the handling of the request to the next middleware or alternatively response can be sent to the client.

logger middleware
1
2
3
4
5
6
7
8
9
const logger = (req, res, next) => {
  const dateNow = new Date()
  const dateString = `${dateNow.toLocaleDateString()} 
                      ${dateNow.toLocaleTimeString()}`
  console.log('Date:', dateString)
  console.log('Method:', req.method)
  console.log('Url:  ', req.url)
  next()
}

Route level middleware

Created middleware function is assigned to a variable named logger and can be used in application routes (route level).

index.js
1
2
3
app.get('/api/users', logger, (req, res) => {
  res.status(200).json({success:true,data:users})
})

Application level middleware

Express application has use() method which can be used to invoke middleware before wanted routes. This way middleware will be invoked before matched route.

index.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ..
// logger is executed every time the app receives a request
app.use(logger)

// one route
app.get('/api/users', logger, (req, res) => {
  console.log('route function')
  res.status(200).json({success:true,data:users})
})

// another routes
...

Above middleware should print following text to console with GET request to /api/users route. Notice how middleware function is called before the route function is called (prints route function text to the console).

1
2
3
4
Date: 20/12/2022 12:41:24
Method: GET
Url: /api/users
route function

Usually middlewares are loaded before routes (not always, you need to know what you are doing and which order middlewares are needed to run). They send control to next middleware with next() function.

A few middlewares

Here a a list of middlewares to check out:

  • cors(), enable cors
  • express.json(), change request JSON string to JSON object and put it to request.body
  • morgan, HTTP request logger middleware

Read more

Goals of this topic

Understand

  • The concept of middleware in the context of Express.