Blog>
Snippets

Implementing a simple logging middleware

Demonstrate how to create a logging middleware that logs action types and payloads before they reach the reducers.
const loggerMiddleware = store => next => action => {
  console.log('dispatching', action.type);
  console.log('payload', action.payload);
  let result = next(action);
  return result;
};
Defines a logging middleware that logs the action type and payload. It uses Redux middleware format.
const createStoreWithMiddleware = applyMiddleware(loggerMiddleware)(createStore);
Applies the loggerMiddleware to the createStore function using Redux's applyMiddleware.
const store = createStoreWithMiddleware(rootReducer);
Creates the Redux store and includes the logging middleware along with the root reducer.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Logging Middleware Example</title>
</head>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.js"></script>
    <script>
       // Place the previous JavaScript snippets here.
    </script>
</body>
</html>
Basic HTML template for testing the middleware. Include Redux library and the JavaScript snippets in the script tag.