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

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.

Enable events collection

Set the clickAnalytics parameter to true when making search requests. This includes the queryID parameter in the search response, which is required for linking events and search requests.

1
2
3
4
5
6
7
8
9
10
11
  const algoliasearch = require("algoliasearch");
  const client = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");
  const index = client.initIndex("YourIndexName");

  index
    .search("query test", 
+     { clickAnalytics: true }
    ).then(({ queryID, hits }) => {
      console.log(hits);
      console.log(queryID);
    });

Initialize search-insights.js

Install the search-insights library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
  var ALGOLIA_INSIGHTS_SRC =
  "https://cdn.jsdelivr.net/npm/search-insights@2.16.3/dist/search-insights.min.js";
  !function(e,a,t,n,s,i,c)
  {
    ((e.AlgoliaAnalyticsObject = s),
    (e[s] =
      e[s] ||
      function () {
        (e[s].queue = e[s].queue || []).push(arguments);
      }),
    (e[s].version = (n.match(/@([^\/]+)\/?/) || [])[1]),
    (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>

After installing the search-insights library, initialize the client in your website.

1
2
3
4
5
6
import aa from 'search-insights';

aa("init", {
  appId: "YourApplicationID",
  apiKey: "YourSearchOnlyAPIKey",
});

Understand which events to track

To understand which events you should send, think about the different steps a user takes through your website to reach the final goal: the product purchase.

Events for search

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

  1. Select a product from the search results to open the product details page.
  2. Add a product to the shopping cart.
  3. Buy the product.

Search and search results pages

User action Method name
User clicks search result clickedObjectIDsAfterSearch
User adds product to shopping cart addedToCartObjectIDsAfterSearch
User clicks categories/filters clickedFilters
User views search results viewedObjectIDs

Product listing and category pages

User action Method name
User clicks product clickedObjectIDsAfterSearch
User adds product to shopping cart addedToCartObjectIDsAfterSearch
User views category page viewedObjectIDs

Product details page

User action Method name
User adds product to cart addedToCartObjectIDsAfterSearch
User views product viewedObjectIDs

Checkout page

User action Method name
User buys product purchasedObjectIDsAfterSearch

Keep track of query IDs

Conversion events are often triggered outside of the search results page. In order to correctly attribute which query is responsible for a conversion, it is necessary to keep track of the query ID returned when a search is performed so that it can be included in conversion events.

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 click events

To send click events with the Insights client, add the following code whenever a user clicks on a product.

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

If you want to track clicks on search results pages, add the following code whenever a user clicks on a product.

1
2
3
4
5
6
7
aa("clickedObjectIDsAfterSearch", {
  index: "YourIndexName",
  queryID: "YourQueryID", // From the search response
  eventName: "Product Clicked",
  objectIDs: ["objectID-1"],
  positions: [1],
});
  • The objectID is included in the search response for each search result as part of the hits attribute.
  • The positions array contains the one-based index of the product hit in the search results.

Track add-to-cart events

Add the following code to all components and pages where users can add products to their shopping cart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
aa("addedToCartObjectIDsAfterSearch", {
  eventName: "Product Added To Cart",
  index: "YourIndexName",
  objectIDs: ["objectID-1"],
  objectData: [
    {
      queryID: "queryID-1",
      price: 19.99,
      discount: 3.99,
      quantity: 3,
    },
  ],
  currency: "USD",
});
  • The objectID is included in the search response for each search result as part of the hits attribute.

You should store the query ID with other product details when updating a user’s shopping cart. This makes it easy to record query IDs for each item for any following purchase events.

Track purchase events

To record when a user completes a purchase, add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
aa("purchasedObjectIDsAfterSearch", {
  eventName: "Products Purchased",
  index: "YourIndexName",
  objectIDs: ["objectID-1", "objectID-2"],
  objectData: [
    {
      queryID: "queryID-1",
      price: 19.99,
      discount: 3.99,
      quantity: 3,
    },
    {
      queryID: "queryID-2",
      price: 59.99,
      quantity: 2,
    },
  ],
  currency: "USD",
});

Use objectData to record per-object data, such as the price and quantity of the purchased products.

Users often purchase items that were added to the cart in response to different queries. For example, a user might search for “shoes” and add a pair of shoes to their cart. Then, they search for “lamp” and add a lamp to their cart. Then, they check out and complete the purchase of both items. In this case, there would be a single purchase event. Each item—the shoes and the lamp—will have the query ID of the search they originated from.

(Optional) Handle known users for Personalization

For effective personalization, you need to identify users across sessions. It’s best to use an identifier from your authentication, user profile, or ecommerce service after users signed in.

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

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

When you set the authenticatedUserToken parameter in the Insights client, you also need to update the user token you send with your search requests.

1
2
3
4
5
6
7
8
9
10
11
12
13
function getEffectiveUserToken() {
    const userToken = window.aa("getUserToken");
    const authenticatedUserToken = window.aa("getAuthenticatedUserToken");
    return authenticatedUserToken || userToken;
}

index.search("query", {
    clickAnalytics: true,
    userToken: getEffectiveUserToken(),
}).then(({queryID, hits}) => {
    console.log(hits);
    console.log(queryID);
})

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,
});

(Optional) Send view events for Personalization

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

To capture view events, such as when a user views search results, add this code:

1
2
3
4
5
window.aa("viewedObjectIDs", {
    index: "YourIndexName",
    eventName: "Product Viewed",
    objectIDs: ["objectID-1"],
});
Did you find this page helpful?