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 custom middleware or use Express built-in middleware and middleware from 3rd party packages.

Middleware can

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

To use middleware, we apply the following:

app.use();

II. Apply Middleware

When we initialize an application with ExpressJS, we will have an object representing that app, usually assigned to 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())
  next()
})

app.use(logger)

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())
  next()
})

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

III. Apply multiple Middleware

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

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, etc.
  • 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.

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 middleware called cookie-parser to read the request’s cookies:

npm install cookie-parser
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");

// Use cookie-parsing middleware
app.use(cookieParser());

Note: Check this list for commonly used middleware.

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