InstantSearch / Angular / V4 / Guides

Integrate Google Analytics in Angular InstantSearch

Google Analytics with Angular InstantSearch

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

But you can follow the same strategy that Algolia uses for the routing.

Integrating with Google Analytics requires 3 steps:

  • Set up the Google Analytics library in your page
  • Set up 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
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
  gtag('event', 'page_view', {
    page_location: page,
  });
};

@Component({
  template: `
    <ais-instantsearch
      [config]="{
        appId: 'latency',
        apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
        indexName: 'instant_search',
        routing: routing
      }"
    >
    </ais-instantsearch>
  `,
})
export class AppComponent {
  public routing = { router, stateMapping: simpleMapping() };
}

Here, only the full URL is sent to Google Analytics but you are free to implement your own function.

Did you find this page helpful?