Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 41 ยท Middleware and Selectors

How Redux Middleware Works

Understand the Redux middleware signature store => next => action, how applyMiddleware composes a pipeline, and where middleware sits between dispatch and the reducer.

Between the moment you call dispatch(action) and the moment the reducer runs, there is a gap. Middleware is code that plugs into that gap. It can log the action, delay it, change it, swallow it, or dispatch more actions. Thunks, RTK Query's cache handling, the listener middleware and Redux Toolkit's development checks are all middleware.

Middleware looks intimidating because of its triple-arrow signature, but the idea is a simple pipeline, exactly like Express or Koa middleware, around dispatch.

Redux is not available in the live editors here. This lesson builds a working stand-in of createStore and applyMiddleware (the real one is almost identical), so you can run everything. Real Redux Toolkit setup is shown read-only.

The signature

JavaScript
const middleware = (storeApi) => (next) => (action) => {
  // before
  const result = next(action);   // pass the action on
  // after
  return result;
};

Each of the three layers receives something different, at a different time:

  1. storeApi (once, at setup): an object with getState and dispatch.
  2. next (once, at setup): the next function in the chain. For the last middleware it is the store's real dispatch.
  3. action (on every dispatch): the thing being dispatched.

The nesting exists so that applyMiddleware can wire the chain up once and then every dispatch just runs a plain function.

flowchart LR
  D["dispatch(action)"] --> M1["logger"]
  M1 --> M2["thunk"]
  M2 --> M3["analytics"]
  M3 --> S["store dispatch<br/>reducer runs"]
  S --> R["new state"]

Each middleware decides whether and when to call next. Not calling it stops the action.

Building applyMiddleware

Here is a complete stand-in. applyMiddleware is an enhancer: it receives createStore, creates the store, and returns a store whose dispatch is replaced by the composed chain.

JS createStore and applyMiddleware

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output top to bottom: logger runs first (its "before" line), calls next, which is tagger; tagger calls the real dispatch; the reducer runs; control comes back up through tagger and finally logger's "after" line shows the new state. The order of the array you pass to applyMiddleware is the order of the "before" parts.

What middleware can do

A middleware has complete control over next:

  • Pass through unchanged: call next(action). This is the default.
  • Transform: call next with a different action (as tagger did).
  • Block: do not call next at all. Useful for validation or permission checks.
  • Delay or repeat: call next later (debounce) or several times.
  • Dispatch new actions: call api.dispatch(other). That goes through the whole chain again, from the start, while next goes only to the following middleware.
  • Answer instead: return something other than the action. Thunk returns the value of the function it ran.

That difference between api.dispatch and next is the most important detail. Mixing them up leads to infinite loops (dispatching the same action from the top of the chain) or to skipped middleware.

JS Blocking and re-dispatching

Press Run (or Ctrl + Enter) to see the console output here.

No output.

guard returns early without calling next, so pear never reaches the reducer. splitter dispatches count through the full chain, so guard also sees that action.

Middleware in Redux Toolkit

With Redux Toolkit you rarely call applyMiddleware yourself. configureStore builds the chain and gives you a default set (thunk, plus the immutability and serializability checks in development):

JavaScript
// Real Redux Toolkit code (read-only)
import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(logger, api.middleware),
});

Use .concat() and .prepend() on the default array instead of replacing it, otherwise you silently lose thunk. Order matters: put middleware that must see raw actions (for example a crash reporter) first and anything that depends on the final state last.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In (store) => (next) => (action) => ..., when does the innermost function run?

    The outer layers run once during setup; the action handler runs on each dispatch.
  2. 2. What is the difference between next(action) and store.dispatch(action) inside middleware?

    dispatch re-enters the pipeline from the first middleware; next continues down it.
  3. 3. How can middleware stop an action from reaching the reducer?

    If next is never called, the action stops there.
  4. 4. Why use getDefaultMiddleware().concat(x) instead of middleware: [x]?

    Replacing the array drops the defaults.

Summary

  • Middleware wraps dispatch: store => next => action.
  • Setup layers run once; the action layer runs on every dispatch.
  • Call next(action) to continue, skip it to block, use store.dispatch to start a new pass.
  • applyMiddleware composes the chain right to left.
  • In Redux Toolkit, extend the defaults with concat/prepend.

Next: Writing custom middleware