Blog>
Snippets

Implementing Middleware for Logging Actions

Create a custom logging middleware that logs every action dispatched to the store, useful for debugging and tracking application state changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Middleware Logger</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<style>
  body {
    font-family: Arial, sans-serif;
  }
</style>
</head>
<body>
<script>
  // Middleware for logging actions
  const logger = store => next => action => {
    console.log('dispatching', action);
    let result = next(action);
    console.log('next state', store.getState());
    return result;
  };
  
  // Reducer
  const reducer = (state = {}, action) => {
    switch(action.type) {
      case 'INCREMENT':
        return { ...state, count: (state.count || 0) + 1 };
      case 'DECREMENT':
        return { ...state, count: (state.count || 0) - 1 };
      default:
        return state;
    }
  };
  
  // Create Redux store with middleware
  const { createStore, applyMiddleware } = Redux;
  const store = createStore(reducer, applyMiddleware(logger));
  
  // Dispatch actions
  store.dispatch({ type: 'INCREMENT' });
  store.dispatch({ type: 'INCREMENT' });
  store.dispatch({ type: 'DECREMENT' });
</script>
</body>
</html>
This HTML document includes a Redux logger middleware example. The middleware logs every dispatched action along with the state before and after the action is processed. The Redux store is created with this middleware, and some example actions are dispatched to demonstrate the middleware in action.