Guides / Building Search UI / Going further

Send Events with Angular InstantSearch

If you’re using InstantSearch and want to send Insights events, it’s best to do so directly from your InstantSearch implementation.

The InstantSearch Insights library allows developers to send click, conversion, and view events. For search-related events, it correlates the event with the queryIDs generated when you’ve set the clickAnalytics parameter to true.

Algolia uses valid search-related events for Click and Conversion Analytics. Click and Conversion Analytics form the foundation for more advanced features like A/B Testing and Dynamic Re-Ranking. Algolia uses all valid events for Personalization. Even if you aren’t planning on implementing Personalization right away, it’s helpful to consider sending events as if you were. This lets you implement Personalization later on with a robust corpus of well-formatted user data.

Requirements

Installing the search-insights library

To send events using InstantSearch, you must first add the search-insights library to your application.

You can load the search-insights library with either the jsDelivr CDN or your static file server. If you choose the latter, you must update the ALGOLIA_INSIGHTS_SRC variable to point to the file URL on your file server.

Load the library by adding this snippet in the <head> of your HTML file.

1
2
3
4
5
6
7
8
<script>
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@2.0.3";

  !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
  (e[s].queue=e[s].queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],
  i.async=1,i.src=n,c.parentNode.insertBefore(i,c)
  }(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");
</script>
1
2
3
4
5
6
7
8
9
10
11
12
aa('init', {
  appId: 'YourApplicationID',
  apiKey: 'YourSearchOnlyAPIKey',
});

// Since search-insights@2.0.0, cookie is not used for anonymous user token.
// If you wish to continue, you can pass `useCookie: true`.
aa('init', {
  appId: 'YourApplicationID',
  apiKey: 'YourSearchOnlyAPIKey',
  useCookie: true,
})

jsDelivr is a third-party CDN. Algolia can’t provide support for such third-party services.

Using insights with Node.js

$
$
$
npm install search-insights
# or
yarn add search-insights
1
2
3
const aa = require('search-insights');
// or
import aa from 'search-insights';

Connecting InstantSearch with the Insights client for JavaScript

Once you’ve installed the search-insights library, you need to connect it to your Angular application.

1
2
3
4
5
6
7
8
9
10
11
12
import algoliasearch from 'algoliasearch/lite'

@Component({
  template: ` <ais-instantsearch [config]="config"> </ais-instantsearch> `,
})
export class AppComponent {
  config = {
    indexName: 'instant_search',
    searchClient: algoliasearch('YourApplicationID', 'YourAPIKey'),
    insightsClient: (window as any).aa,
  }
}

Sending events

Once you’ve registered your index with the application ID and the API key, you can start sending events. For examples of the different kinds of events and what user behaviors translate into them, refer to the guide on capturing user behaviors as events.

Insights events (view, click, and conversion) don’t take immediate effect. There’s a delay of from a few minutes up to an hour (depending on whether they’re sent after a search or not and how long after a search they’re sent).

For a better estimation, see how long it takes for Insights events to be taken into account.

By default, InstantSearch uses a random string as the userToken when sending events. Setting a userToken is important for query aggregation and Personalization purposes. If you define unique identifiers for users, it’s best to use those rather than the automatically generated ones. Doing so keeps the userToken sent to Algolia in sync with your system.

For that reason, or if you have to identify a user across different devices, you can send a custom userToken along with the eventName, index, and objectIDs parameters when sending events.

To get the default userToken provided by InstantSearch, call the getUserToken method on the Insights library.

1
2
3
4
5
6
7
8
9
10
// Starting from v1.3.0 of the search-insights.js library
let userToken = '';
window.aa('getUserToken', null, (err, algoliaUserToken) => {
  if (err) {
    console.error(err);
    return;
  }

  userToken = algoliaUserToken;
});

Retrieving the queryID from the search response

When sending a search-related event to Algolia, you need to include the queryID of the most recent search. By default, the search response doesn’t contain a queryID. To retrieve it, you need to set the clickAnalytics parameter to true. You can do this using the ais-configure widget:

1
2
3
<ais-instantsearch [config]="config">
  <ais-configure [searchParameters]="{ clickAnalytics: true }"></ais-configure>
</ais-instantsearch>

If you use the insights function to send events, it will infer the queryID from the InstantSearch context.

Calling the insights function to send events

With the search-insights client connected, you can call the insights function from within the ais-hits component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ais-hits>
  <ng-template let-hits="hits" let-insights="insights">
    <div *ngFor="let hit of hits">
      <a href="/product?queryID={{hit.__queryID}}">
        <ais-highlight attribute="name" [hit]="hit"></ais-highlight>
      </a>
      <button
        (click)="insights('clickedObjectIDsAfterSearch', { eventName: 'Product Clicked', objectIDs: [hit.objectID] })"
      >
        Add to cart
      </button>
    </div>
  </ng-template>
</ais-hits>

Like with queryID, the insights function infers important parameters such as index, positions, and objectIDs from the InstantSearch context, if you don’t provide them. You must include the eventName.

This example uses the clickedObjectIdsAfterSearch type of event, but you could also use convertedObjectIdsAfterSearch.

The insights function doesn’t support sending events that are unrelated to search.

For these events, you should use the API clients, Insights REST API, or InstantSearch library.

Tracking queryID on other pages

Conversion events don’t always happen on a search results page. For example, a user could buy an item from a product detail page, meaning you must pass the queryID to that page.

Did you find this page helpful?