Send events with React InstantSearch Hooks
On this page
If you’re using InstantSearch and want to send Insights events, it’s best to do so directly from your React InstantSearch Hooks implementation.
The InstantSearch Insights library allows developers to send click
, conversion
, and view
events. For search-related events, it correlates the event with the queryID
s generated when you’ve set the clickAnalytics
parameter to true
.
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 also uses all valid events 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 set of well-formatted user data.
Requirements
search-insights
v1.6.2 or later.- React InstantSearch Hooks v6 or later.
Installing the search-insights
library
To send events in 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.4.0/dist/search-insights.min.js";
!function(e,a,t,n,s,v,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>
jsDelivr is a third-party CDN. Algolia can’t provide support for such 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';
Creating the insights
middleware
1
2
3
4
5
import { createInsightsMiddleware } from 'instantsearch.js/es/middlewares';
const insightsMiddleware = createInsightsMiddleware({
insightsClient: aa,
});
Connecting InstantSearch with the insights
middleware
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { createInsightsMiddleware } from 'instantsearch.js/es/middlewares';
import { useInstantSearch } from 'react-instantsearch-hooks-web';
import { useLayoutEffect } from 'react';
function InsightsMiddleware() {
const { use } = useInstantSearch();
useLayoutEffect(() => {
const middleware = createInsightsMiddleware({
insightsClient: aa,
});
return use(middleware);
}, [use]);
return null;
}
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function App() {
return (
<InstantSearch indexName="instant_search" searchClient={searchClient}>
{/* ... */}
<InsightsMiddleware />
</InstantSearch>
);
}
Retrieving the queryID
from the search response
When sending a search-related event to Algolia, you need to include the queryID
of the most recent search. By default, the search response doesn’t contain a queryID
. To retrieve it, you need to set the clickAnalytics
parameter to true
.
The insights
middleware handles this for you.
Setting the userToken
By default, search-insights
library sets an anonymous token and stores it in a cookie. It’s best to set the userToken
yourself using an internal user identifier. This lets you reliably identify users.
If you use search-insights >= 2.0.0
, it doesn’t set an anonymous token automatically and no longer uses cookies by default. If you want to enable it, refer to the insightsInitParams
.
1
aa('setUserToken', yourUserToken);
If you don’t already have access to that information, you can set it up later from your code. As soon as you’ve set it, the insights
middleware ensures that every subsequent search includes a userToken
.
Sending default events
When using any of the following connectors, the insights
middleware automatically sends default for some user behaviors like selecting a facet or viewing a result.
Sending events from refinement widgets
If you customize a widget using connectors, the insights
middleware also sends events. You can turn off this behavior or change the default payload.
Sending events from results widgets
When using any of the following connectors, the insights
middleware automatically sends default view
events when hits are rendered.
If you customize a widget using connectors, the insights
middleware also sends events. You can turn off this behavior or change the default payload.
Sending events
Usually, you want to send events when the user interacts with search results. This means you want to send the events from either the <Hits>
or the <InfiniteHits>
widget.
This example sets up the <Hits>
widget:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { InstantSearch, Hits, Highlight } from 'react-instantsearch-hooks-web';
function Hit({ hit, sendEvent }) {
return (
<article>
<h3>
<Highlight hit={hit} attribute="name" />{' '}
</h3>
<button
type="button"
onClick={() => {
sendEvent('click', hit, 'Product Added');
}}
>
Add to cart
</button>
<button
type="button"
onClick={() => {
sendEvent('conversion', hit, 'Product Ordered');
}}
>
Order
</button>
</article>
);
}
function App(props) {
return (
<InstantSearch {...props}>
<Hits hitComponent={Hit} />
</InstantSearch>
);
}
Once you’ve registered your index with the application ID and the API key, you can start sending events. For examples of the different kinds of events and what user behaviors translate into them, refer to the guide on capturing user behaviors as events.
Insights events (view, click, and conversion) don’t take immediate effect. There’s a delay of from a few minutes up 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 it takes for Insights events to be taken into account.
Different event types need different data. For example, a conversion
event doesn’t need the positions
attribute, but the click
event does. This is because positions
determines the average click position. The integration with InstantSearch handles all this for you. InstantSearch injects:
To see a full implementation, check the Insights for React InstantSearch Hooks example.
- All the necessary data based on the event to send
- The context of the current query.
If you intend to send these events with the Personalization feature, deciding which events to send and when to send them is vital. Read the guide on capturing user actions as events if you need help deciding what to send.
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, meaning you must pass the queryID
to that page.
Advanced insights
middle customizations
The insights
middleware lets you turn off default events, change the default event payloads, send events from your own custom widgets, and send events to third-party trackers. Check the insights
middleware documentation to learn how to do this.