1 min read

What is middleware?

Middleware is software that sits between your frontend client and your backend that provides additional functionality to requests and responses. A simple middleware

A few use cases:

  • Authentication: see if a request is made by a user with a valid authentication key
  • Logging: log every request and response

An example:

app.use(function (req, res, next) {
  req.foo = "bar";
  next();
});

This middleware function takes the request object, adds a new property to it, and then passes it to the next step (to another middleware function, or to an API call).

An analogy I liked:

Imagine you go to a restaurant, hence you're a customer. You read the menu and choose what you'd like to eat. The waiter comes and you tell him your order. The waiter let's the kitchen staff know what to prepare. Once your food is ready, they hand it out to the waiter brings and serves you the food.

The customer represents the application, for example your frontend.

Selecting an option from the menu represents your request.

The waiter represents the API. It's purpose is to deliver your request to the kitchen.

The kitchen represents your backend. It could be a database or another application.

The kitchen handles your request, hence prepares your data.

The waiter aka API takes the data and brings it to you / your table / the frontend.

Now, the waiter isn't fully dumb. If you request food that is not on the menu, they will decline your request. If you request wine, they will expect you to prove your age. If you request spaghetti, they will bring you a fork and a spoon without needing the kitchen staff. If you give them a note to pass to the cute cook, they may decide themselves if it's appropriate or not. To follow the restaurant rules, the waiter will make use of certain clothes or certain tools, such as pencil and paper.

Those extra tools, options and decisions that the waiter can either make use of in general or in specific scenarios, are examples of Middleware.

Sources:

Can someone kindly explain Middleware and API (especially REST API) in simple words?
by u/I_Watch_Turtle_P0rn in learnprogramming
ELI5: Middleware. What is it, and when is it necessary to implement?
by u/jayisrad in learnjavascript