Guides / Sending events / Implementing events / Best practices

Track the QueryID for Conversion Events

Often, conversion events occur outside of your search implementation. Consider this scenario:

  1. A user searches for a product.
  2. The user clicks on a result on the product-listing page and is redirected to a product-detail page for this product.
  3. On the product-detail page, the user adds the product to the shopping cart.

You can track this event as a conversion event. Since it’s related to a search, this event needs a queryID. To send events from product-detail pages, you need to make the indexName, queryID, and objectIDs of the previous search available in the new context.

This is different from conversion events that aren’t related to a previous search. For example, if users navigate directly to a product-detail page, you can send a conversion event without a queryID.

Obtaining the queryID from the search response

First, you need to enable generating a queryID with every search. You can do this by setting clickAnalytics as an extra search parameter.

For example, with the JavaScript client:

1
2
3
4
5
6
7
index
  .search('query', {
    clickAnalytics: true
  })
  .then(({ hits }) => {
    console.log(hits);
  });

Or, with InstantSearch:

1
2
3
4
5
search.addWidgets([
  instantsearch.widgets.configure({
    clickAnalytics: true,
  }),
]);

Passing the queryID to your conversion page

When users run a query, you can save the queryID and access it from another page in your app. For web applications, you can use query parameters:

1
2
3
4
5
index.search('query', {
  clickAnalytics: true
}).then(({ queryID }) => {
  console.log(queryID);
});

If you’re using InstantSearch, you can retrieve the queryID using the Hits component:

1
2
3
4
5
6
7
search.addWidgets([
  instantsearch.widgets.hits({
    templates: {
      item: item => `<a href="product.html?queryID=${item.__queryID}"> ... </a>`
    }
  })
]);

To read the queryID from another page, for example, a product-detail page, you need to read the queryID and other parameters from the URL. If you used URL parameters, you can use the URL API available in most browsers.

1
2
3
4
const url = new URL(window.location.href)
const searchParams = url.searchParams

const queryID = searchParams.get('queryID')

Don’t track the queryID in cookies or in the local storage

You could store the queryID in a cookie or in the localStorage and read it in other pages:

1
2
3
4
5
localStorage.setItem("queryID", queryID);

// ...

localStorage.getItem("queryID");

However, in a cookie or localStorage, the queryID is overwritten with every new search query. Passing the queryID via URL parameter is the best way to make sure you send conversion events with correct queryID connected to that conversion.

Sending the conversion event

With the queryID and other search-related parameters available, you can send the conversion event.

Did you find this page helpful?