Algolia DevCon
Oct. 2–3 2024, virtual.
Guides / Sending events / InstantSearch

Capturing real-time user interactions as events gives you actionable insights via click and conversion metrics, and they help you increase your customer engagement and conversions. Events are used to activate Algolia features and products like NeuralSearch, Dynamic Re-Ranking, Query Categorization, Recommend, and Personalization.

Before you begin

To follow this guide, you need to build both search results and category pages with one of these UI libraries:

For other methods of collecting events, see Get started with events.

Manage the Insights library

InstantSearch loads the search-insights library for you from jsDelivr. You don’t need to install it or set it up yourself.

If you’re using a Content Security Policy to protect your site and you want to let InstantSearch load search-insights for you, make sure to add https://cdn.jsdelivr.net in your list of trusted sources for JavaScript.

1
script-src https://cdn.jsdelivr.net/

If you prefer hosting your own version of search-insights, you can add it to your project:

  1. Install the Insights client
  2. Initialize the Insights client (optional)

InstantSearch doesn’t load search-insights when it detects it on the page.

Enable events collection

You can enable the automatic collection of events from your InstantSearch apps in the Algolia dashboard (without coding), or when setting up your InstantSearch app (with coding).

Enabling automatic events collection takes care of the following:

  • Add the search-insights library to your project and make it globally available as window.aa
  • Set an anonymous userToken for sending events to the Insights API and for search requests
  • Include the queryID parameter in the search response
  • Send default click and view events for your InstantSearch widgets

Go to the Events hub in the Algolia dashboard to check the default events arriving from your website or app. For more information, see Validate your events.

No code

  1. Go to the Algolia dashboard and select your Algolia application.
  2. On the left sidebar, select Data sources > Events > Settings.
  3. Click Enable automatic events collection.

Code

Enable the insights option:

1
2
3
4
5
6
7
const search = instantsearch({
    searchClient,
    indexName: "YourIndexName",
+   insights: true,
  });
  // Add your InstantSearch widgets here
  search.start();

Understand which events to track

You may want to send events that are not automatically captured by InstantSearch widgets. To understand which events you should send, think about the different steps a user takes through your website to perform desired actions, such as watching a video, reading an article, or liking a page.

Events for search

Starting with a search on any of your pages, a user might take the following actions:

  1. Select content from the search results to open the content details page.
  2. Consume content, such as watching a video, reading an article, or listening to an audio track.
  3. Interact with content, such as liking, subscribing, or following.

Search and search results pages

User action Method name Automatically collected?
User clicks search result clickedObjectIDsAfterSearch Yes
User clicks categories/filters clickedFilters Yes
User views search results viewedObjectIDs Yes

Browse/category page

User action Method name Automatically collected?
User clicks content clickedObjectIDsAfterSearch Yes
User views content viewedObjectIDs Yes

Content details page

User action Method name Automatically collected?
User views content viewedObjectIDs No

Keep track of query IDs

Conversion events are often triggered on pages that aren’t covered by InstantSearch, such as your content details pages.

To relate the conversion events back to the search request made on your search results or category pages, you need to keep track of the query IDs across your pages.

Track conversion events

Using InstantSearch widgets

You can use the sendEvent function to send conversion events from your InstantSearch app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <h2>${components.Highlight({ attribute: "name", hit })}</h2>
        <p>${hit.description}</p>
        <button
          onClick="${() =>
            sendEvent("conversion", hit, "Article Added To Favorites");
          }"
        >
          Add to favorites
        </button>
      `;
    },
  },
});

Unlike click events, setting custom conversion events doesn’t prevent the custom click event from being sent.

On pages without InstantSearch widgets

An example of a conversion event that may be relevant to your media site:

1
2
3
4
5
6
7
// A user reached the bottom of an article page
window.aa("convertedObjectIDsAfterSearch", {
  eventName: "Article Read",
  index: "YourIndexName",
  queryID: "query-1",
  objectIDs: ["objectID-1"],
});

The window.aa object is the API client for the Insights API and is globally available if you enabled automatic events collection.

The queryID parameter is used by Algolia to relate the event to a prior search.

The objectIDs parameter indicates which items were part of the conversion.

The objectID parameter is included in the search response for each hit.

If the event is not directly related to a search, for example, it’s triggered on the homepage, use the convertedObjectIDs method instead.

1
2
3
4
5
6
// A user watched a video
window.aa("convertedObjectIDs", {
  eventName: "Video Watched",
  index: "YourIndexName",
  objectIDs: ["objectID-1"],
});

Some other examples of conversion events are:

  • Article Bookmarked: a user bookmarked an article.
  • Article Liked: a user liked an article.
  • Article Recommended: a user recommended an article.
  • Playlist Followed: a user followed a playlist.
  • Author Followed: a user followed an author.
  • Brand Followed: a user followed a brand.

Track click events

Override default click events

The hits and infiniteHits widgets expose a sendEvent function. Use it to send click events when users interact with your search results.

1
2
3
4
5
6
7
8
9
10
11
12
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <div onClick="${() => sendEvent("click", hit, "Article Clicked")}">
          <h2>${components.Highlight({ attribute: "name", hit })}</h2>
          <p>${hit.description}</p>
        </div>
      `;
    },
  },
});

You can set more events on specific parts of your template. In the following example, when clicking on the View more info button, two events are sent to the Insights API:

  • A click event with the eventName “Article More Info Clicked”
  • A click event with the eventName “Article Clicked” (via event propagation)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <div onClick="${() => sendEvent("click", hit, "Article Clicked")}">
          <h2>${components.Highlight({ attribute: "name", hit })}</h2>
          <p>${hit.description}</p>
          <button
            onClick="${() =>
              sendEvent("click", hit, "Article More Info Clicked")
            }"
          >
            View more info
          </button>
        </div>
      `;
    },
  },
});

To only send the most specific event per clicked element, you can use Event.stopPropagation in your event handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <div onClick="${() => sendEvent("click", hit, "Article Clicked")}">
          <!-- ... -->
          <button
            onClick="${(event) => {
+             event.stopPropagation();

              sendEvent("click", hit, "Article More Info Clicked");
            }}"
          >
            View more info
          </button>
        </div>
      `;
    },
  },
});

When InstantSearch captures a custom click event that you defined, it doesn’t send the default click event. In the following example, when clicking the View more info button, only the “Article More Info Clicked” event is sent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <h2>${components.Highlight({ attribute: "name", hit })}</h2>
        <p>${hit.description}</p>
        <button
          onClick="${() =>
            sendEvent("click", hit, "Article More Info Clicked")
          }"
        >
          View more info
        </button>
      `;
    },
  },
});

Track additional click events

For Algolia Recommend and Personalization, capture additional click events when users select individual items:

  • On your home page
  • From recommendations

To send click events with the Insights client, add the following code whenever a user clicks on an article—for example, on your homepage.

1
2
3
4
5
window.aa("clickedObjectIDs", {
  index: "YourIndexName",
  eventName: "Article Clicked",
  objectIDs: ["objectID-1"],
});

(Optional) Set up Personalization

For effective personalization, you need to identify users across sessions. It’s best to use an identifier from your authentication system after users signed in. For more information, see User token.

After getting the identifier from your system, set it as the authenticatedUserToken parameter.

1
2
3
// Get a unique, pseudonymous identifier for signed-in users
const authenticatedUserToken = getUserTokenAfterSignIn();
window.aa("setAuthenticatedUserToken", authenticatedUserToken);

If you can’t get persistent user identifiers from your system, you can store the anonymous user token in a cookie after obtaining user consent.

1
2
3
4
5
// If user consented
aa("init", {
  partial: true,
  useCookies: true,
});

If you don’t use persistent user identifiers, a new anonymous user token is generated on every page refresh.

Personalization benefits from the same click and conversion events, plus it can use view events to enrich user profiles.

Your InstantSearch components for the search results and category pages automatically collect view events.

To capture additional view events, such as on your homepage, add this code:

1
2
3
4
5
window.aa("viewedObjectIDs", {
  index: "YourIndexName",
  eventName: "Content Viewed",
  objectIDs: ["objectID-1"],
});

Working examples

Adding events to a React InstantSearch application

Did you find this page helpful?