🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / InstantSearch.js / Widgets
Signature
createInsightsMiddleware({
  insightsClient: null | InsightsClient,
  insightsInitParams?: object,
  onEvent?: (event: InsightsEvent, aa: null | InsightsClient) => void,
});
Import
1
import { createInsightsMiddleware } from 'instantsearch.js/es/middlewares';

About this widget

Starting from v4.55.0, you can use the insights option instead of setting up the Insights middleware yourself.

The createInsightsMiddleware creates an insights middleware to help you achieve the following:

  1. Set the userToken for insights purposes (Click Analytics, Personalization, etc.)
  2. Automatically send events from built-in widgets (you can disable it)
  3. Lets you send events from your own custom widgets

Requirements

Examples

1
2
3
4
5
6
7
const insightsMiddleware = createInsightsMiddleware({
  insightsClient,
  insightsInitParams,
  onEvent,
});

search.use(insightsMiddleware);

Options

Parameter Description
insightsClient
type: InsightsClient | null
Optional

The Insights client is used to send events. It synchronizes the user token between search and analytics calls.

To disable userToken synchronization and automatic event sending, set this to null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
  /*
    A snippet to include `search-insights`
    You can find it here
    https://github.com/algolia/search-insights.js
  */
</script>

<script>
  const insightsMiddleware = instantsearch.middlewares.createInsightsMiddleware({
    insightsClient: window.aa,
  });

  search.use(insightsMiddleware);

  const userToken = // Get the user token (synchronously or asynchronously).

  // The `insights` middleware receives a notification
  // and attaches the `userToken` to search calls onwards.
  window.aa('setUserToken', userToken);
</script>
insightsInitParams
since: v4.11.0
type: object
Optional

Insights parameters to forward to the Insights client’s init method.

With search-insights >= v1.7.0 and < 2.0.0, the Insights client accepts useCookie and userToken parameters in the init method. You can pass useCookie: false to prevent the usage of cookies to store an anonymous userToken. You can also pass a custom userToken while creating insights middleware, if you have one.

With search-insights >= 2.0.0, the default value of useCookie is false.

1
2
3
4
5
6
createInsightsMiddleware({
  insightsClient: window.aa,
  insightsInitParams: {
    useCookie: false,
  }
});
onEvent
type: (event: InsightsEvent, aa: null | InsightsClient) => void
default: undefined
Optional

By default, the middleware sends events to Algolia using the provided insightsClient. You can also control events and send them yourself by implementing an onEvent method for the middleware to call instead. The method lets you access data, and filter or modify the payload. You can also use it to send events to third-party trackers.

If you want to use onEvent to send events to third-party trackers, but don’t want to send them to Algolia, you can set insightsClient to null, and you don’t need the search-insights library in your application.

The event parameter has the following properties:

  • insightsMethod?: string: The Insights method (e.g., 'viewedObjectIDs', 'clickedObjectIDsAfterSearch', etc.). You can find more in the Insights API reference.
  • payload: { [key: string]: any }: The event payload.
  • widgetType: string: The widget type given by connectors (e.g., 'ais.refinementList', 'ais.hits', etc.)
  • eventType: string: The event type (e.g., 'view', 'click', 'conversion', or anything else if you customized it).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
createInsightsMiddleware({
  insightsClient: window.aa,
  onEvent: (event, aa) => {
    const { insightsMethod, payload, widgetType, eventType } = event;

    // Send the event to Algolia
    if (insightsMethod) {
      aa(insightsMethod, payload);
    }

    // Send the event to a third-party tracker
    if (widgetType === 'ais.hits' && eventType === 'click') {
      thirdPartyTracker.send('Product Clicked', payload);
    }
  }
});

Custom events

Parameter Description
Connectors

Many of the InstantSearch connectors expose the sendEvent method. If you use these connectors to create custom widgets, you can leverage the method to send custom events.

Here’s a list of connectors that expose sendEvent.

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
36
37
const renderRefinementList = (renderOptions, isFirstRendering) => {
  const { sendEvent } = renderOptions;

  // `sendEvent` from `connectRefinementList` can send `click` events.
  const clickedFacetValue = 'Apple';
  
  // This sends an event like the following:
  /*
    {
      eventType: 'click',
      insightsMethod: 'clickedFilters',
      payload: {
        eventName: 'Filter Applied',
        filters: ['brand:"Apple"'],
        index: '<your-index-name>',
      },
      widgetType: 'ais.refinementList',
    }
  */
  sendEvent('click', clickedFacetValue);

  // Or, you can send a custom payload
  sendEvent({
    eventType: 'click',
    insightsMethod: 'clickedFilters',
    payload: {
      eventName: 'Filter Applied',
      filters: [`brand:${JSON.stringify(clickedFacetValue)}`],
      index: '<your-index-name>',
    },
    widgetType: 'ais.refinementList',
  });
}

const customRefinementList = connectRefinementList(
  renderRefinementList
);
Hits

The hits and infiniteHits widgets provide templates with an exposed sendEvent function.

The sendEvent(eventType, payload, eventName) function triggers an event. When clicking the button, InstantSearch sends it to Algolia, or forwards it to onEvent if provided.

  • eventType: 'click' | 'conversion'
  • payload: Hit
  • eventName: string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
hits({  // or `infiniteHits`
  // ...
  templates: {
    item: (hit, { html, components, sendEvent }) => {
      return html`
        <div>
          <p>${components.Highlight({ attribute: 'title', hit })}</p>
          <button
            type="button"
            onClick=${() => sendEvent('conversion', hit, 'Product Added')}
          >
            Add to cart
          <button>
        </div>
      `;
    }
  },
});
Did you find this page helpful?