Blog>
Snippets

Analytics Event Tracking Middleware

Set up a middleware that listens for specific actions and sends corresponding events to an analytics service, demonstrating side-effect management in Redux 5.0.0.
const analyticsMiddleware = store => next => action => {
  // Call the next dispatch method in the middleware chain.
  const returnValue = next(action)

  // Define the analytics events to track
  const eventsMap = {
    'ADD_TO_CART': trackAddToCart,
    'COMPLETE_PURCHASE': trackCompletePurchase
  };

  // If the action type is in the eventsMap, call the respective function
  if (eventsMap[action.type]) {
    eventsMap[action.type](action);
  }
  return returnValue;
};

// Example analytic event functions
function trackAddToCart(action) {
  // Implement the logic to send the 'add to cart' event data
  console.log('Tracking add to cart:', action);
}

function trackCompletePurchase(action) {
  // Implement the logic to send the 'complete purchase' event data
  console.log('Tracking complete purchase:', action);
}
This JavaScript code sets up a Redux middleware function that listens for specific actions (like 'ADD_TO_CART' or 'COMPLETE_PURCHASE') and triggers corresponding analytic event tracking functions. Each action type has a corresponding function that handles the event tracking logic.
// To apply the middleware to your Redux store
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';

// Create the Redux store and apply the analyticsMiddleware
const store = createStore(
  rootReducer,
  applyMiddleware(analyticsMiddleware)
);
This JavaScript code snippet shows how to import the Redux `createStore` and `applyMiddleware` functions to create and configure the Redux store while applying the `analyticsMiddleware` defined in the previous snippet.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Redux Analytics Event Tracking</title>
  <!-- Include Redux and other required script tags here -->
</head>
<body>
  <!-- Your application's HTML goes here -->
</body>
</html>
This is the basic HTML structure where your Redux application will reside. Remember to include Redux and any other scripts that your application will require, such as React, Babel, or any other dependencies.
body {
  font-family: 'Arial', sans-serif;
}
A simple CSS snippet that sets the default font for the body of the document to Arial. Include more styles as needed for your application.