Integrate Google Analytics in InstantSearch.js
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. 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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:
1
2
3
4
5
6
const search = instantsearch({
searchClient,
indexName,
});
search.use(googleAnalyticsMiddleware);