DEV Community

Cover image for Introduction to using middleware in Express
Naftali Murgor
Naftali Murgor

Posted on

Introduction to using middleware in Express

Introduction

This tutorial will learn about middleware and how middleware makes Express powerful and extensible.

What is middleware? A middleware is a function that intercepts requests and or responses as they get in/out of your Express application. Middleware has access to request and response objects.

Middleware functions can run any code, modify the request(req)/response(res) objects, and has access to the request/response cycle

How to use a Middlware in Express

Middlewares can be used as:

  1. Application-wide - a middleware enabled for the entire application
  2. Router level middleware
  3. Error handling middlware
  4. 3rd Party middlware

1. Application-wide Middleware

Application-wide middleware are middleware enabled for the entire application.

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

const middlwareFn = (req, req, next) => {
  console.log(req.method)
  next()
}

// for every request, middlewareFn will always be executed
// it's a middleware enable application-wide
app.use(middlwareFn) 
Enter fullscreen mode Exit fullscreen mode

2. Router Level middleware

Router level middleware work the same as application-wide except that they are bound to an instance of express.Router().

Say you have set up a router like:

const express = require('express')
const Router = express.Router
// instance of router
const router = Router()
// declare a middleware function
const logHTTPMethod = (req, res, next) => {
  console.log(`Method: ${req.method}`)
  next()
}

// enable the middleware
router.use(logHTTPMethod)

Enter fullscreen mode Exit fullscreen mode

The logHTTpMethod middleware will be enabled for router instance an will be run for all requests that are handle inside router.

To enable logHTTPMethod, we will pass the function as an argument after router.METHOD() like:

// code ommitted
// for every request to /accounts resource, we run logHTTPMethod
router.get('/accounts', logHTTPMethod, (req, res) => {
  // route logic
})
Enter fullscreen mode Exit fullscreen mode

3. Error-handling Middlware

Error-handling middleware are similar to other middleware except that the signature is different.

In Error-handling middware, signature require 4 arguments instead of 3.
Parameters for Error-handling middleware: (err, req, res, next)

// code omitted
const ErrorHandler = (err, req, res, next) => {
  res.status(500).send('Internal server Error')
}
app.use(ErrorHandler)
// code omitted
Enter fullscreen mode Exit fullscreen mode

4. 3rd Party middleware

A 3rd party middlware is packaged as an npm module and can be installed as a dependency using yarn or npm
A good example is a middleware that provides logging capabilities like morgan or cookie parsing functionalities like cookie-parser

To use morgan to log request info to the console(standard output):

Add morgan as a dependency:

yarn add morgan
Enter fullscreen mode Exit fullscreen mode

Import the dependency:

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

app.use(morgan('tiny')) // will log request info everytime a request is made to the application.
Enter fullscreen mode Exit fullscreen mode

Summary

Middleware is a function that has access to request (req), response (res) objects. The signature for using middleware is app.use(middlewareFn). Where app is an instance of Express or Router class.
In our next article, create a tiny Express application to demonstrate:

  • Routing
  • Middleware
  • Route params & Route queries
  • Authentication & Authorization

We shall build a tiny e-commerce application, with a Nextjs powered front-end.

Until next week, Adios!


Found this article helpful? You may follow my handle on twitter @nkmurgor where I tweet about interesting topics on web development.

Top comments (0)