Blog>
Snippets

Custom Logging Middleware in Redux v5.0.0

Create a custom logging middleware compatible with Redux v5.0.0 to log actions and state changes.
const customLoggerMiddleware = store => next => action => {
  console.log('dispatching', action);
  let result = next(action);
  console.log('next state', store.getState());
  return result;
};
This is a logging middleware function that logs every action dispatched and the state of the store after the action has been processed. It follows Redux middleware signature using currying.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Logging Middleware</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/5.0.0/redux.min.js"></script>
<script>
  // Assume customLoggerMiddleware is defined as in the previous code snippet
  function reducer(state = {}, action) {
    // Reducer logic here
    return state;
  }

  const store = Redux.createStore(
    reducer,
    Redux.applyMiddleware(customLoggerMiddleware)
  );

  // Actions for example purpose
  store.dispatch({ type: 'ACTION_TYPE' });
</script>
</head>
<body>
<h1>Check the console for logged actions and state changes</h1>
</body>
</html>
An HTML document with embedded Redux script tag. It includes a store created with a reducer and the custom logging middleware. The store dispatches an example action to demonstrate the logging in action.
body { font-family: Arial, sans-serif; }
A minimal CSS styling for the HTML body to use Arial font.