Skip to main content
This is the React InstantSearch v7 documentation. If you’re upgrading from v6, see the upgrade guide. If you were using React InstantSearch Hooks, this v7 documentation applies—just check for necessary changes. To continue using v6, you can find the archived documentation.
Even though Algolia provides analytics that are tailored to your search implementation, you might want to integrate your search into your existing analytics tools. You can implement a custom middleware to do that. First, follow the steps on how to set up the Google Analytics library in your page. Then you can create a middleware. Then in the event listener, you can send events to Google Analytics or any solution. In this example, we are debouncing the event for 3 seconds, but you can adjust this to your needs.
JavaScript
function googleAnalyticsMiddleware() {
  let timer;
  const sendEventDebounced = () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      gtag('event', 'page_view', {
        page_location: window.location.pathname + window.location.search,
      });
    }, 3000);
  });

  return {
    onStateChange() {
      sendEventDebounced();
    },
    subscribe() {},
    unsubscribe() {},
  };
}
Once the middleware is created, you can inject it into the InstantSearch lifecycle:
React
import { useInstantSearch } from "react-instantsearch";

function Middleware() {
  const { addMiddlewares } = useInstantsearch();

  useLayoutEffect(() => {
    return addMiddlewares(googleAnalyticsMiddleware);
  }, []);

  return null;
}

function Search() {
  return (
    <InstantSearch searchClient={searchClient} indexName="instant_search">
      <Middleware />
    </InstantSearch>
  );
}
I