applyMiddleware(…middleware)

Middleware is the suggested way to extend Redux with custom functionality. Middleware lets you wrap the store's dispatch method for fun and profit. The key feature of middleware is that it is composable. Multiple middleware can be combined together, where each middleware requires no knowledge of what comes before or after it in the chain.

The most common use case for middleware is to support asynchronous actions without much boilerplate code or a dependency on a library like Rx. It does so by letting you dispatch async actions in addition to normal actions.

For example, redux-thunk lets the action creators invert control by dispatching functions. They would receive dispatch as an argument and may call it asynchronously. Such functions are called thunks. Another example of middleware is redux-promise. It lets you dispatch a Promise async action, and dispatches a normal action when the Promise resolves.

Middleware is not baked into createStore and is not a fundamental part of the Redux architecture, but we consider it useful enough to be supported right in the core. This way, there is a single standard way to extend dispatch in the ecosystem, and different middleware may compete in expressiveness and utility.

Arguments

  • …middleware (arguments): Functions that conform to the Redux middleware API. Each middleware receives Store's dispatch and getState functions as named arguments, and returns a function. That function will be given the next middleware's dispatch method, and is expected to return a function of action calling next(action) with a potentially different argument, or at a different time, or maybe not calling it at all. The last middleware in the chain will receive the real store's dispatch method as the next parameter, thus ending the chain. So, the middleware signature is ({ getState, dispatch }) => next => action.

Returns

(Function) A store enhancer that applies the given middleware. The store enhancer signature is createStore => createStore but the easiest way to apply it is to pass it to createStore() as the last enhancer argument.

Example: Custom Logger Middleware

  1. import { createStore, applyMiddleware } from 'redux'
  2. import todos from './reducers'
  3. function logger({ getState }) {
  4. return next => action => {
  5. console.log('will dispatch', action)
  6. // Call the next dispatch method in the middleware chain.
  7. const returnValue = next(action)
  8. console.log('state after dispatch', getState())
  9. // This will likely be the action itself, unless
  10. // a middleware further in chain changed it.
  11. return returnValue
  12. }
  13. }
  14. const store = createStore(todos, ['Use Redux'], applyMiddleware(logger))
  15. store.dispatch({
  16. type: 'ADD_TODO',
  17. text: 'Understand the middleware'
  18. })
  19. // (These lines will be logged by the middleware:)
  20. // will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }
  21. // state after dispatch: [ 'Use Redux', 'Understand the middleware' ]

Example: Using Thunk Middleware for Async Actions

  1. import { createStore, combineReducers, applyMiddleware } from 'redux'
  2. import thunk from 'redux-thunk'
  3. import * as reducers from './reducers'
  4. const reducer = combineReducers(reducers)
  5. // applyMiddleware supercharges createStore with middleware:
  6. const store = createStore(reducer, applyMiddleware(thunk))
  7. function fetchSecretSauce() {
  8. return fetch('https://www.google.com/search?q=secret+sauce')
  9. }
  10. // These are the normal action creators you have seen so far.
  11. // The actions they return can be dispatched without any middleware.
  12. // However, they only express “facts” and not the “async flow”.
  13. function makeASandwich(forPerson, secretSauce) {
  14. return {
  15. type: 'MAKE_SANDWICH',
  16. forPerson,
  17. secretSauce
  18. }
  19. }
  20. function apologize(fromPerson, toPerson, error) {
  21. return {
  22. type: 'APOLOGIZE',
  23. fromPerson,
  24. toPerson,
  25. error
  26. }
  27. }
  28. function withdrawMoney(amount) {
  29. return {
  30. type: 'WITHDRAW',
  31. amount
  32. }
  33. }
  34. // Even without middleware, you can dispatch an action:
  35. store.dispatch(withdrawMoney(100))
  36. // But what do you do when you need to start an asynchronous action,
  37. // such as an API call, or a router transition?
  38. // Meet thunks.
  39. // A thunk is a function that returns a function.
  40. // This is a thunk.
  41. function makeASandwichWithSecretSauce(forPerson) {
  42. // Invert control!
  43. // Return a function that accepts `dispatch` so we can dispatch later.
  44. // Thunk middleware knows how to turn thunk async actions into actions.
  45. return function(dispatch) {
  46. return fetchSecretSauce().then(
  47. sauce => dispatch(makeASandwich(forPerson, sauce)),
  48. error => dispatch(apologize('The Sandwich Shop', forPerson, error))
  49. )
  50. }
  51. }
  52. // Thunk middleware lets me dispatch thunk async actions
  53. // as if they were actions!
  54. store.dispatch(makeASandwichWithSecretSauce('Me'))
  55. // It even takes care to return the thunk's return value
  56. // from the dispatch, so I can chain Promises as long as I return them.
  57. store.dispatch(makeASandwichWithSecretSauce('My wife')).then(() => {
  58. console.log('Done!')
  59. })
  60. // In fact I can write action creators that dispatch
  61. // actions and async actions from other action creators,
  62. // and I can build my control flow with Promises.
  63. function makeSandwichesForEverybody() {
  64. return function(dispatch, getState) {
  65. if (!getState().sandwiches.isShopOpen) {
  66. // You don't have to return Promises, but it's a handy convention
  67. // so the caller can always call .then() on async dispatch result.
  68. return Promise.resolve()
  69. }
  70. // We can dispatch both plain object actions and other thunks,
  71. // which lets us compose the asynchronous actions in a single flow.
  72. return dispatch(makeASandwichWithSecretSauce('My Grandma'))
  73. .then(() =>
  74. Promise.all([
  75. dispatch(makeASandwichWithSecretSauce('Me')),
  76. dispatch(makeASandwichWithSecretSauce('My wife'))
  77. ])
  78. )
  79. .then(() => dispatch(makeASandwichWithSecretSauce('Our kids')))
  80. .then(() =>
  81. dispatch(
  82. getState().myMoney > 42
  83. ? withdrawMoney(42)
  84. : apologize('Me', 'The Sandwich Shop')
  85. )
  86. )
  87. }
  88. }
  89. // This is very useful for server side rendering, because I can wait
  90. // until data is available, then synchronously render the app.
  91. import { renderToString } from 'react-dom/server'
  92. store
  93. .dispatch(makeSandwichesForEverybody())
  94. .then(() => response.send(renderToString(<MyApp store={store} />)))
  95. // I can also dispatch a thunk async action from a component
  96. // any time its props change to load the missing data.
  97. import { connect } from 'react-redux'
  98. import { Component } from 'react'
  99. class SandwichShop extends Component {
  100. componentDidMount() {
  101. this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson))
  102. }
  103. componentDidUpdate(prevProps) {
  104. if (prevProps.forPerson !== this.props.forPerson) {
  105. this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson))
  106. }
  107. }
  108. render() {
  109. return <p>{this.props.sandwiches.join('mustard')}</p>
  110. }
  111. }
  112. export default connect(state => ({
  113. sandwiches: state.sandwiches
  114. }))(SandwichShop)

Tips

  • Middleware only wraps the store's dispatch function. Technically, anything a middleware can do, you can do manually by wrapping every dispatch call, but it's easier to manage this in a single place and define action transformations on the scale of the whole project.

  • If you use other store enhancers in addition to applyMiddleware, make sure to put applyMiddleware before them in the composition chain because the middleware is potentially asynchronous. For example, it should go before redux-devtools because otherwise the DevTools won't see the raw actions emitted by the Promise middleware and such.

  • If you want to conditionally apply a middleware, make sure to only import it when it's needed:

  1. let middleware = [a, b]
  2. if (process.env.NODE_ENV !== 'production') {
  3. const c = require('some-debug-middleware')
  4. const d = require('another-debug-middleware')
  5. middleware = [...middleware, c, d]
  6. }
  7. const store = createStore(
  8. reducer,
  9. preloadedState,
  10. applyMiddleware(...middleware)
  11. )

This makes it easier for bundling tools to cut out unneeded modules and reduces the size of your builds.

  • Ever wondered what applyMiddleware itself is? It ought to be an extension mechanism more powerful than the middleware itself. Indeed, applyMiddleware is an example of the most powerful Redux extension mechanism called store enhancers. It is highly unlikely you'll ever want to write a store enhancer yourself. Another example of a store enhancer is redux-devtools. Middleware is less powerful than a store enhancer, but it is easier to write.

  • Middleware sounds much more complicated than it really is. The only way to really understand middleware is to see how the existing middleware works, and try to write your own. The function nesting can be intimidating, but most of the middleware you'll find are, in fact, 10-liners, and the nesting and composability is what makes the middleware system powerful.

  • To apply multiple store enhancers, you may use compose().