> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# createAlgoliaInsightsPlugin

> A function to create a new Algolia Insights plugin for Autocomplete that lets you send click and conversion events to the Insights API.

export const UserToken = () => <Tooltip tip="A user token is a pseudonymous ID that represents an individual user across Algolia searches and events. It links queries, clicks, and conversions to a user profile, enabling user-level analytics, personalization, and recommendations." cta="User token" href=" /doc/guides/sending-events/concepts/usertoken">
    user token
  </Tooltip>;

<Tip>
  Autocomplete is also available as an experimental widget in InstantSearch,
  making it easier to integrate into your search experience.
  For more information,
  see the API reference for [InstantSearch.js](/doc/api-reference/widgets/autocomplete/js) or
  [React InstantSearch](/doc/api-reference/widgets/autocomplete/react).
</Tip>

The Algolia Insights plugin automatically sends [click and conversion events](/doc/guides/sending-events/getting-started) to the [Algolia Insights API](/doc/rest-api/insights)
whenever a user interacts with the autocomplete.

<Note>
  Starting from version 1.9.2 of Autocomplete,
  you no longer need to use this plugin directly.
  Instead, use the [`insights` option](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-insights)
  of the [`autocomplete`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete) function.
</Note>

For more information,
see [Send click and conversion events](/doc/ui-libraries/autocomplete/guides/sending-algolia-insights-events).

## Use the `insights` option

<Note>
  This option is available starting from v1.9.2.
</Note>

Instead of using this plugin,
you can set up events using the [`insights`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-insights)
option of the [`autocomplete`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete) function.

```js JavaScript icon=code theme={"system"}
import { autocomplete } from "@algolia/autocomplete-js";

autocomplete({
  container: "#autocomplete",
  insights: true,
});

// or with options

autocomplete({
  container: "#autocomplete",
  insights: {
    // ...
  },
});
```

<Note>
  If you don't pass an `insightsClient`,
  it will be automatically detected from the `window` object,
  or downloaded from the [jsDelivr CDN](https://www.jsdelivr.com/).
</Note>

<Tip>
  If you are using the [`insights` option](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-insights)
  you don't need to follow the rest of this guide.
</Tip>

## Installation

First, you need to install the plugin.

<CodeGroup>
  ```sh npm theme={"system"}
  npm install @algolia/autocomplete-plugin-algolia-insights
  ```

  ```sh yarn theme={"system"}
  yarn add @algolia/autocomplete-plugin-algolia-insights
  ```
</CodeGroup>

Then import it in your project:

```js JavaScript icon=code theme={"system"}
import { createAlgoliaInsightsPlugin } from "@algolia/autocomplete-plugin-algolia-insights";
```

If you don't use a package manager, you can use the HTML `script` element:

```html HTML icon=code-xml theme={"system"}
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-algolia-insights@1.19.9/dist/umd/index.production.js"
  integrity="sha256-SM0SWyRxCsM39Jl+yICKdevSInaMP2aQe9NM2xJyi/w="
  crossorigin="anonymous"
></script>
<script>
  const { createAlgoliaInsightsPlugin } =
    window["@algolia/autocomplete-plugin-algolia-insights"];
</script>
```

<Note>
  If you don't pass an `insightsClient`,
  it will be automatically detected from the `window` object,
  or downloaded from the [jsDelivr CDN](https://www.jsdelivr.com/).
</Note>

## Examples

This example uses the plugin within [`autocomplete-js`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete), along with the [`algoliasearch`](https://www.npmjs.com/package/algoliasearch) API client and [Search Insights](https://www.npmjs.com/package/search-insights) library.

```js JavaScript icon=code theme={"system"}
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { autocomplete } from "@algolia/autocomplete-js";
import { createAlgoliaInsightsPlugin } from "@algolia/autocomplete-plugin-algolia-insights";
import insightsClient from "search-insights";

const appId = "latency";
const apiKey = "6be0576ff61c053d5f9a3225e2a90f76";
const searchClient = algoliasearch(appId, apiKey);
insightsClient("init", { appId, apiKey });

const algoliaInsightsPlugin = createAlgoliaInsightsPlugin({ insightsClient });

autocomplete({
  container: "#autocomplete",
  plugins: [algoliaInsightsPlugin],
});
```

To identify users consistently, such as authenticated users, use your own <UserToken /> with `setUserToken`.
The `search-insights` library can create anonymous user tokens and store them in cookie.
To use cookie-based anonymous tokens,
initialize the library with [`useCookie`](/doc/libraries/search-insights/init#param-use-cookie) set to `true`:

```js JavaScript icon="code" theme={"system"}
insightsClient("init", { appId, apiKey });
insightsClient("setUserToken", yourUserToken);

// or

insightsClient("init", { appId, apiKey, useCookie: true });
```

In older versions of the `search-insights` library (earlier than version 2.0),
cookie-based anonymous tokens are on by default.

The plugin exposes hooks to let you inject custom logic in the lifecycle:
[`onItemsChange`](#param-on-items-change),
[`onSelect`](#param-on-select),
and [`onActive`](#param-on-active).
You can use them to either customize the events sent to Algolia, or plug additional behavior.

For example, if you have several search experiences on your site,
you can customize the event name to identify where the events came from:

```js JavaScript icon=code theme={"system"}
const algoliaInsightsPlugin = createAlgoliaInsightsPlugin({
  insightsClient,
  onItemsChange({ insights, insightsEvents }) {
    const events = insightsEvents.map((insightsEvent) => ({
      ...insightsEvent,
      eventName: "Product Viewed from Autocomplete",
    }));
    insights.viewedObjectIDs(...events);
  },
  onSelect({ insights, insightsEvents }) {
    const events = insightsEvents.map((insightsEvent) => ({
      ...insightsEvent,
      eventName: "Product Selected from Autocomplete",
    }));
    insights.clickedObjectIDsAfterSearch(...events);
  },
});
```

If you're using another analytics provider along with Algolia Insights,
you can use these hooks to send events as well.
For example, you can send Segment events:

```js JavaScript icon=code theme={"system"}
const algoliaInsightsPlugin = createAlgoliaInsightsPlugin({
  insightsClient,
  onActive({ insights, insightsEvents }) {
    insightsEvents.forEach((insightsEvent) => {
      // Assuming you've initialized the Segment script
      // and identified the current user already
      analytics.track("Product Browsed from Autocomplete", insightsEvent);
    });
  },
});
```

<Note>
  If you send events to other analytics providers,
  it might make sense to [create a dedicated plugin](/doc/ui-libraries/autocomplete/core-concepts/plugins#build-your-own-plugin).
</Note>

## Parameters

<ParamField body="insightsClient" type="InsightsClient">
  [The Search Insights client](/doc/ui-libraries/autocomplete/guides/sending-algolia-insights-events).
  If not provided, the plugin will use the global `window.aa` object,
  or fetch it from the [jsDelivr CDN](https://www.jsdelivr.com/).
</ParamField>

<ParamField body="insightsInitParams" type="object" post={["since: v1.14.0"]}>
  Insights parameters to forward to the Insights client's [`init`](/doc/libraries/search-insights/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 user token.
  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`.
</ParamField>

<ParamField body="onItemsChange" type="(params: OnItemsChangeParams) => void">
  Hook to send an Insights event whenever the items change.

  By default, it sends a `viewedObjectIDs` event.

  In as-you-type experiences, items change as users type.
  This hook is debounced every 400 ms to reflect actual items that users notice and avoid generating too many events for items matching "in progress" queries.

  ```ts TypeScript icon=code theme={"system"}
  type OnItemsChangeParams = {
    insights: InsightsApi;
    insightsEvents: ViewedObjectIDsParams[];
    state: AutocompleteState<any>;
  };
  ```
</ParamField>

<ParamField body="onSelect" type="(params: OnSelectParams) => void">
  Hook to send an Insights event whenever an item is selected.

  By default, it sends a `clickedObjectIDsAfterSearch` event.

  ```ts TypeScript icon=code theme={"system"}
  type OnSelectParams = {
    insights: InsightsApi;
    insightsEvents: ClickedObjectIDsAfterSearchParams[];
    item: AlgoliaInsightsHit;
    state: AutocompleteState<any>;
    event: any;
  };
  ```
</ParamField>

<ParamField body="onActive" type="(params: OnActiveParams) => void">
  Hook to send an Insights event whenever an item is active.

  By default, it doesn't send any events.

  ```ts TypeScript icon=code theme={"system"}
  type OnActiveParams = {
    insights: InsightsApi;
    insightsEvents: ClickedObjectIDsAfterSearchParams[];
    item: AlgoliaInsightsHit;
    state: AutocompleteState<any>;
    event: any;
  };
  ```
</ParamField>
