The middleware pattern in Javascript is a close variation of the Chain of Responsibility (CoR) pattern in which a chain of functions are used to handle an incoming event, often in the form of a request.

Functions in the chain forward the event along the chain until one of the functions handles the event. This pattern offers some interesting benefits:

  • It decouples the sender of the event/request from the receiver by allowing one or several functions handle the event and process the data. Hence, intercepting the event data and acting as a filter.
  • No explicit knowledge between sender and receiver is required.
  • The chain of functions can be changed in run-time acting as an event pipeline.

In Javascript, the middleware pattern is extensively used by the Express, Connect and Koa frameworks.

The code below shows one possible implementation of the Middleware pattern.