Guides / Building Search UI / Going further

Send Events with React InstantSearch

We released React InstantSearch Hooks, a new InstantSearch library for React. We recommend using React InstantSearch Hooks in new projects or upgrading from React InstantSearch.

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, 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 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. We are not able to provide support regarding 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';

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’re sent after a search or not, and how long after a search they’re sent. For a better estimation, see: How long does it take 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 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
14
15
import { connectHitInsights } from 'react-instantsearch-dom';

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

// You need to call `window.aa('init', { appId, apiKey })` before.
// Make sure Hit has a `hit` prop.
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, 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. 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?