Guides / Building Search UI / Going further

Send Insights Events

If you’re using InstantSearch and want to send Insights events, it’s best to do so directly from your InstantSearch implementation. This guide describes how to send click, conversion, and view events with React InstantSearch.

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—search-related or not—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 at your disposal.

To learn more about why you would want to send events and which events Algolia uses for which features, please read the guide on capturing user behaviors as events. To make sure you’re following InstantSearch best practices, please read the Getting Started guide before sending events.

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 either via the jsDelivr CDN or from your own static file server. If you choose the latter, you have to update the ALGOLIA_INSIGHTS_SRC variable to point to the file URL on your file server.

You can load the library by adding this snippet in the <head> of your HTML file.

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@1.6.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");

  aa('init', {
    appId: 'YourApplicationID',
    apiKey: 'YourSearchOnlyAPIKey',
  });
</script>

jsDelivr is a third-party CDN. We are not able to provide support regarding third party services.

Using insights with Node.js

Since version 1.3.0, you can use search-insights with NodeJS.

With NPM:

$
npm install search-insights

with Yarn:

$
yarn add search-insights

You can now use require to import the package in your code.

1
2
const aa = require('search-insights');
// The rest is the same.

Sending events

Insights events (view, click, and conversion) don’t take immediate effect. The delay can range from a few minutes to an hour, depending on whether they are sent after a search or not, and how long after a search they are sent. For precise timeframes, see our page on when Insights events take effect.

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 your own 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, you can 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 search-related events to Algolia, you need to include the queryID of the most recent search. By default, the search response doesn’t contain a queryID. For Algolia to include it, you need to set the clickAnalytics parameter to true. You can do this using the Configure widget:

1
2
3
4
5
6
7
8
9
10
import { InstantSearch, Configure } from 'react-instantsearch-dom';

const App = () => (
  <InstantSearch
    indexName="INDEX_NAME"
    searchClient={searchClient}
  >
    <Configure clickAnalytics />
  </InstantSearch>
);

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

Connecting the search-insights client

Now, you can connect the search-insights client to any Hits component you want to send click or conversion events from.

1
2
3
4
5
6
7
8
9
10
11
12
13
import { connectHitInsights } from 'react-instantsearch-dom';

const Hit = ({ hit, insights }) => (
  <article>
    <h1>{hit.name}</h1>
    <button> Add to favorite </button>
  </article>
);

const HitWithInsights = connectHitInsights(window.aa)(Hit);

<Hits hitComponent={HitWithInsights} />;

Calling the insights function to send events

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Hit = ({ hit, insights }) => (
  <article>
    <h1>{hit.name}</h1>
    <button
      onClick={() =>
        insights('clickedObjectIDsAfterSearch', {
          eventName: 'Product Clicked'
        })
      }
    >
      See details
    </button>
  </article>
);

Like with queryID, the insights function infers important parameters like 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 types of events, you should use the API clients or Insights REST API directly.

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. That means you need to pass the queryID to the detail page. The keeping track of queryID guide shows how to use query parameters to track the queryID.

Did you find this page helpful?