Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 41 ยท Middleware and Selectors

Writing Custom Middleware and Listeners

Write practical Redux middleware: logging, crash reporting, analytics, debouncing and API calls, and learn when RTK's listener middleware is the cleaner choice.

Once you know the middleware signature, writing your own is a matter of picking a job and deciding what to do with next. This lesson builds four small but realistic middleware and then shows the listener middleware that Redux Toolkit provides for "when X happens, do Y" logic.

Everything runs on a stand-in createStore/applyMiddleware (the real Redux packages are not available in the editors). The middleware functions themselves are exactly what you would write for real Redux.

Recipe 1: a timing logger

Log each action with how long the reducers took. A good logger prints the action, the previous state and the next state, and it only runs in development.

JS Logger and crash reporter

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

No output.

crashReporter is placed first so it wraps everything after it, including the logger and the reducer. It reports and rethrows: swallowing errors would hide bugs.

Recipe 2: analytics that ignores most actions

Middleware often cares about only a few action types. Keep the check cheap and put the allow-list in one place.

JavaScript
// Works with real Redux Toolkit (read-only)
const TRACKED = new Set(['cart/added', 'checkout/completed']);

export const analytics = () => (next) => (action) => {
  const result = next(action);              // let the reducer run first
  if (TRACKED.has(action.type)) {
    navigator.sendBeacon('/events', JSON.stringify({ type: action.type, at: Date.now() }));
  }
  return result;
};

Calling next first means the event is only sent for actions that did not throw. Side effects that should precede the state change (validation, logging the raw action) go before next.

Recipe 3: an API middleware

Some teams funnel all requests through one middleware so components only dispatch descriptions of requests. This is the style that predates thunks and RTK Query:

JS An API-call middleware

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

No output.

This works, but it is a private mini-framework you must maintain. Today, prefer createAsyncThunk or RTK Query, and keep custom middleware for cross-cutting concerns: logging, analytics, error reporting, authentication token refresh, persisting state.

The listener middleware

Redux Toolkit's createListenerMiddleware handles a very common need: "after this action (or this state change), run some async logic." You register listeners with an effect function instead of writing middleware plumbing.

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

export const listener = createListenerMiddleware();

listener.startListening({
  actionCreator: todoAdded,                       // or matcher, predicate, effect-by-type
  effect: async (action, listenerApi) => {
    listenerApi.cancelActiveListeners();          // debounce: cancel earlier runs
    await listenerApi.delay(500);
    const { todos } = listenerApi.getState();
    await fetch('/api/todos', { method: 'PUT', body: JSON.stringify(todos.items) });
  },
});

listener.startListening({
  matcher: isAnyOf(loggedOut, sessionExpired),
  effect: (action, api) => { api.dispatch(clearAllCaches()); },
});

// store setup: listeners must come BEFORE other middleware (use prepend)
configureStore({
  reducer,
  middleware: (gdm) => gdm().prepend(listener.middleware),
});

The effect runs after the reducer, with listenerApi giving you getState, getOriginalState, dispatch, delay, condition(predicate) (wait for a later action), take, fork (child tasks), cancelActiveListeners and unsubscribe. It is the Redux-native replacement for most uses of sagas.

Here is a tiny stand-in that shows the "run after the reducer, debounced" behaviour:

JS Listener stand-in with debounce

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

No output.

Three actions arrive within the window; the earlier effects are cancelled, and exactly one save runs with the final state.

Choosing the right tool

Job Use
Fetch data, track status RTK Query, or createAsyncThunk
Run code in response to an action or state change Listener middleware
Cross-cutting concerns for every action Custom middleware
Complex long-running workflows Listener fork/take, or a saga library

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the crash reporter above rethrow the error?

    Report, then rethrow, so callers and DevTools still see the failure.
  2. 2. When should side effects that depend on the NEW state run?

    After next the reducer has run, so getState returns the new state.
  3. 3. What does cancelActiveListeners help implement?

    A new run cancels the earlier pending ones, so only the last survives the delay.
  4. 4. Where should the listener middleware be placed in the middleware list?

    RTK recommends prepend so listeners see actions before other middleware alters or stops them.

Summary

  • Pick a job (log, report, track, call an API) and decide what to do with next.
  • Run effects before next for validation, after next for reactions to new state.
  • Prefer thunks and RTK Query to hand-made API middleware.
  • The listener middleware runs effects after the reducer with delay, condition, fork and cancellation.
  • Order middleware deliberately.

Next: Selectors and memoization