Express Middleware

Michael Chen
2 min readSep 27, 2020

First we will briefly talk about what a middleware is, then we will talk about some common middlewares, and finally we will do some examples.

Using Middleware

Software, firmware, spyware, malware, ransomware, kitchenware, silverware, and now middleware?

Don’t let the name “middleware” intimidate you. While the word might seem intimidating and complicated, it is actually very simple. Middleware in Express are functions that gets executed in the middle of the request as the name suggests.

Initial request > Middleware functions > Final route from server.

If you’ve used Express before, you’ve used middleware before. An Express application is essentially a series of middleware function calls. These middlewares have access to the request object, the response object, and the next middleware function.

An Express application can use the following types of middleware:

  • Application-level middleware (app.use())
  • Router-level middleware (router.use())
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

…will add more examples soon…

A few things to remember when dealing with middleware:

  • The order of middleware functions is important — middlewares that are loaded first are also executed first, in sequential order.

Some Commonly Used Middleware In Express

  • cors — Enables cross-origin resource sharing (CORS) with various options.
  • cookie-parser — Parse cookie header and populate req.cookies.
  • body-parser — Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
  • morgan — Middleware for generating request logs in the server.
  • passports
  • authentications

Examples of Some Custom Middleware

--

--