Concepts / Building Search UI / Integrate Google Analytics
May. 10, 2019

Integrate Google Analytics

Google Analytics with Vue InstantSearch

Even though Algolia provides an analytics tailored to your search, you might want to integrate your search into your existing analytics tools. Vue InstantSearch doesn’t provide a built-in widget to implement analytics with other providers.

But you can follow the same strategy that we use for the routing.

Integrating with Google Analytics requires 2 steps:

  • set up the Google Analytics library in your page
  • setup the routing
  • listen within the routing

To set up Google Analytics, the best way is to actually follow the reference guide.

Once the GA library is installed on your website, you can add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
  <ais-instant-search
    index-name="instant_search"
    :search-client="searchClient"
    :routing="routing"
  >
    <ais-search-box />
    <ais-hits />
  </ais-instant-search>
</template>

<script>
import { history as historyRouter } from 'instantsearch.js/es/lib/routers';
import { simple as simpleMapping } from 'instantsearch.js/es/lib/stateMappings';
// use the existing router
const router = historyRouter();
const _write = router.write.bind(router);
// override write
router.write = routeState => {
  _write(routeState);
  const page = router.createURL(routeState);
  // send to Google analytics
  window.ga('send', 'pageView', page);
};
export default {
  data() {
    return {
      routing: {
        router,
        stateMapping: simpleMapping(),
      },
    }
  }
}
</script>

Here we only send the full URL to Google Analytics but you are free to implement your own function. You can take a look at the ais-state-results reference to have an idea of the structure.

Did you find this page helpful?