Middleware in ExpressJs

I. What is Middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next() function.

We can create our custome middleware or use Express built-in middleware and middleware from 3rd party packages.

Middleware can

  • Make changes to request and response objects
  • Excecute functions or any codes
  • End response cycle
  • Call next() middleware in the stack

To use middleware, we apply:


II. Apply Middleware

When we initialize an application with ExpressJS, we will have an object representing that app, usually assigned with the variable app.

This object can declare middleware through the functions: app.use().

A Middleware function after finishing its operation, if it is not the last in the sequence of functions to be performed, will need to call next() to move to the next function. Otherwise the processing will be suspended at that function.

The example below describes a function that does not declare a specific path, so it will be executed every time a request is made:

const express = require('express')
const app = express();

const logger = (req, res, next) => {
  console.log('Time:', Date.now())


Log each member

The example below uses the use function to the path /user/:id. This function will be executed every time the request reaches the /user/:id path or any path starts with /user/:id.

const app = express();

const logger = (req, res, next) => {
  console.log('Time:', Date.now())

app.use('/user/:id', logger)

III. Apply multiple middleware

To apply more than one middleware, we can use square branket []

app.use([a, b])

The execution order of the middleware will be a, b.

IV. Built-in middleware

Express has the following built-in middleware functions:

  • express.static serves static assets such as HTML files, images, and so on.
  • express.json parses incoming requests with JSON payloads.
  • express.urlencoded parses incoming requests with URL-encoded payloads.

V. Third-party middleware

Using 3rd-party middleware will help us add functionality to our app without much effort to implement.

We will need to install the module via npm, then declare it in the app object.

For example, this code will install and use a middlware called cookie-parser to read the request’s cookies:

npm install cookie-parser
const express = require('express')
csont app = express()
csont cookieParser = require('cookie-parser')

// Use cookie-parsing middleware

Note: Check this list for commonly used middleware.

In the next artilce, we’ll look at the express.Router().