🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
Guides / Building Search UI / Going further

Integrate Google Analytics in React InstantSearch

This is the React InstantSearch v7 documentation. React InstantSearch v7 is the latest version of React InstantSearch and the stable version of React InstantSearch Hooks.

If you were using React InstantSearch v6, you can upgrade to v7.

If you were using React InstantSearch Hooks, you can still use the React InstantSearch v7 documentation, but you should check the upgrade guide for necessary changes.

If you want to keep using React InstantSearch 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, you follow the steps on how to set up the Google Analytics library in your page.

Then you can create a middleware. The In the event listener, you can send events to Google Analytics or any solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import debounce from 'lodash.debounce';

function googleAnalyticsMiddleware() {
  const sendEventDebounced = debounce(() => {
    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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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>
  );
}
Did you find this page helpful?