API Reference / React InstantSearch Hooks / insights
Signature
import {
  createInsightsMiddleware
} from 'instantsearch.js/es/middlewares';

createInsightsMiddleware({
  insightsClient: null | InsightsClient,
  insightsInitParams?: object,
  onEvent?: (event: InsightsEvent, aa: null | InsightsClient) => void,
});

About this widget

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 turn this off if needed
  3. Send events from your own custom widgets

Requirements

Examples

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { createInsightsMiddleware } from 'instantsearch.js/es/middlewares';
import { useConnector } from 'react-instantsearch-hooks-web';
import { useEffect } from 'react';

const connectMiddleware = (renderFn, unmountFn) => (widgetParams) => ({
  init(initOptions) {
    renderFn(
      {
        ...this.getWidgetRenderState(initOptions),
        instantSearchInstance: initOptions.instantSearchInstance,
      },
      true
    );
  },

  render(renderOptions) {
    const renderState = this.getWidgetRenderState(renderOptions);

    renderFn(
      {
        ...renderState,
        instantSearchInstance: renderOptions.instantSearchInstance,
      },
      false
    );
  },

  getWidgetRenderState(renderOptions) {
    return {
      use: renderOptions.instantSearchInstance.use,
      unuse: renderOptions.instantSearchInstance.unuse,
      widgetParams,
    };
  },

  dispose() {
    unmountFn();
  },
});

function Insights() {
  const { use, unuse } = useConnector(connectMiddleware);

  useEffect(() => {
    const middleware = createInsightsMiddleware({
      insightsClient,
      insightsInitParams,
      onEvent,
    });

    use(middleware);

    return () => unuse(middleware);
  }, []);

  return null;
}

Options

insightsClient
type: null|InsightsClient
Required

The middleware leverages insightsClient to sync the userToken between search and analytics calls. If you want to turn off userToken sync and automatic event sending, you can set this to null.

1
2
3
4
5
6
7
8
9
const middleware = createInsightsMiddleware({
  insightsClient: aa,
});

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

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

When given, the insightsInitParams is passed to the init() method of the insights client.

With search-insights >= v1.7.0 and < 2.0.0, the insights client accepts the useCookie and userToken parameters in its 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.

To learn more about the parameters of init() method, check out the GitHub repository.

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

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

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

Custom events

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 and they’re exposed at the default slot of corresponding React InstantSearch Hooks components.

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
function Hits() {
  const { hits, sendEvent } = useHits();

  return (
    <ol>
      {hits.map((hit) => (
        <li key={hit.objectID}>
          <p>{hit.name}</p>
          <button
            type="button"
            onClick={() => sendEvent('click', hit, 'Item Starred')}
          >
            Star
          </button>

          <button
            type="button"
            onClick={() => sendEvent('conversion', hit, 'Item Ordered')}
          >
            Order
          </button>
        </li>
      ))}
    </ol>
  );
}
Did you find this page helpful?