Why do we use Middlewares?

Prasun Acharjee
Alien Brains
Published in
5 min readJul 6, 2020
Image by TekStream

If you have worked on some of the new web frameworks, it is very much likely that you have encountered the term Middleware. In this article, I will explain what is middleware and why do we use it. Some of the examples that I will be using will be mostly in the context of redux.

Let me start with what is middleware?

A comparison from Briteskies

Middleware is some code or application that is used between the web-framework receiving a request, and the framework generating a response.

Seems pretty simple right?

Well, this definition is based more on the web aspect of middleware. But in reality, middlewares are everywhere, starting from websites to our phone, laptops, databases even when we are playing games some middlewares are providing us services like graphic rendering and physical simulations.

Why use middleware?

To understand why middleware is important and why we use it, let me take an example.

Imagine a friend of yours from Japan is coming over to your place. You need to help her in shopping but she’s not familiar with you native language. To make her journey successful and to be a good friend, you would have to fill the role of translators and help her in shopping.

Middleware is doing the same thing, that it enables a system or application to communicate with each other. Middleware is important because it makes synergy and integration across those applications possible.

Now, let us look into where middleware in other industries and how it affects it.

Uses of Middleware

We have already seen that middleware acts as a link between different software.

But what exactly does it do apart from acting as a conduit between the different software?

Here are some of the uses and types of middleware used in different industries :

  1. Transaction management :

As the name suggests this middleware is massively used in the business or banking industry. Transactional middleware can be used to manage and control individual transactions and ensure that any problems do not corrupt the system or database. It does this by controlling transaction apps, pushing database updates related to the transaction, and enforcing the business rules and logic of the transaction.

2. Message queues :

The middleware that is used here is called Message Oriented Middleware (MOM). What it does is it allows messages to be sent and received between applications or systems. In addition to enabling the transmission of messages across different applications, message-oriented middleware also has a queuing mechanism that allows the interaction between the server and the client to happen synchronously when the target node is busy or slow.

3. Web server :

Middleware can also accept client requests from web browsers and channel them to the main server/database and then deliver the responses to the browsers.

You can read more about different types of middleware from here.

Now, let us look into how middleware is used in the redux framework.

Middleware in Redux

In redux , middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.

Rather than middleware being a software, in case of the redux framework, it is more like a few lines of code. The most famous middlewares that are being used with redux are redux-logger, redux-thunk, and redux-saga. Usually, in redux, the action/reducer flow is very clean for updating the state within an application.

This is a simple redux flow.

This redux-flow takes place when there are no asynchronous calls taking place in the application. But what happens when we try to fetch some data from a server or communicate with an external API? Or suppose you just want to see what is being dispatched and how the state is changing. We need a way to run these side effects without disrupting out redux flow. So what should be used to solve these problems? …

Yes, you guessed right, we use middlewares to allow these side effects to run beside the normal flow without blocking the state updates.

Where does Middleware fit into the redux flow?

First, let’s look into a normal redux pattern without middleware :

  1. An event takes place (like a button click or form submit).
  2. An action is dispatched to handle the event.
  3. Reducer which contains the new state change it based on the action which was dispatched.
  4. A new state is passed into the application via props and the UI changes accordingly.

Adding middleware gives us a place to take in the dispatch actions and lets us run the side effect after the action occurs.

So our new redux pattern with middleware will look like :

  1. An event takes place.
  2. An action is dispatched.
  3. Middleware receives the action and runs the side effects.
  4. Reducer updates the state.
  5. The UI gets updated.
Redux flow with middleware.

For understanding redux more clearly you can visit their official docs and read from here.

Here’s an example that logs every actions and state:

const logger = store => next => action => {  //logs the dispatched action
console.log(‘dispatching’, action)
//logs the previous state
console.log('previous state', store.getState())
let result = next(action) //logs the updated state
console.log(‘next state’, store.getState())
return result}

What next does here is it continues the propagation of the current action. It’s important to not alter the action and to call it once and only once within the middleware.

We can consider middleware like a pipeline :

dispatch -> middleware 1 -> middleware 2 -> ... -> reducer

We dispatch one action, it runs through the middleware one at a time, ending in the reducer.

And here’s how to apply it to redux store :

import { createStore, combineReducers, applyMiddleware } from ‘redux’const reduxApp = combineReducers(reducers)const store = createStore(  reduxApp,  // applyMiddleware() tells createStore() how to handle middleware  applyMiddleware(logger))

Wrapping Up

At first, when using middleware in your applications might seem a little confusing but it makes up for a very powerful tool to handle side effects in your application and making you code handling faster and easier.

References

  1. https://expressjs.com/en/guide/using-middleware.html
  2. https://en.wikipedia.org/wiki/Middleware
  3. https://developer.okta.com/blog/2018/09/13/build-and-understand-express-middleware-through-examples#:~:text=Middleware%20literally%20means%20anything%20you,or%20path)%20it's%20attached%20to
  4. https://redux.js.org/advanced/middleware

I hope you have understood what middlewares are why we use them.

Thanks for reading !!

Happy Hacking 😄

--

--