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

# Google Tag Manager

> Send click, conversion, and view events to the Algolia Insights API with Google Tag Manager.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

export const Filter = () => <Tooltip tip="A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints." cta="Filtering" href="/doc/guides/managing-results/refine-results/faceting">
    filter
  </Tooltip>;

export const ApplicationID = () => <Tooltip tip="A unique alphanumeric string that identifies an Algolia application." cta="Application ID (dashboard)" href="https://dashboard.algolia.com/account/api-keys">
    application ID
  </Tooltip>;

export const APIKey = () => <Tooltip tip="An alphanumeric string that controls access to the Algolia APIs. It defines what actions are allowed, such as searching an index or adding new records." cta="API key" href="/doc/guides/security/api-keys">
    API key
  </Tooltip>;

To use Google Tag Manager (GTM) for sending [click and conversion events](/doc/guides/sending-events) to the Algolia Insights API,
you need to add data attributes to your website's templates and configure the Algolia Insights template in the GTM dashboard.

## Update your search parameters

To connect events to searches, including those from [category pages](/doc/guides/solutions/ecommerce/browse/tutorials/category-pages),
you must pass [`queryID`](/doc/guides/sending-events/guides/queryid) when sending search-related events to the Insights API, such as with the [`clickedObjectIDsAfterSearch`](/doc/libraries/sdk/v1/methods/clicked-object-ids-after-search) method.

To include the `queryID` in the search response, set [`clickAnalytics`](/doc/api-reference/api-parameters/clickAnalytics) to `true`.

To identify users, [add the `userToken` parameter](/doc/guides/sending-events/concepts/usertoken).

<CodeGroup>
  ```js JavaScript theme={"system"}
  const response = await client.searchSingleIndex({
    indexName: "INDEX_NAME",
    searchParams: {
      query: "YourSearchQuery",
      userToken: "user-1",
      clickAnalytics: true,
    },
  });
  const { hits, queryID } = response;
  console.log(hits, queryID);
  ```

  ```js InstantSearch.js theme={"system"}
  instantsearch.widgets.configure({
    clickAnalytics: true,
    userToken: "user-1",
  });
  ```

  ```jsx React InstantSearch theme={"system"}
  import { Configure } from "react-instantsearch";

  <Configure clickAnalytics={true} userToken={"user-1"} />;
  ```

  ```vue Vue InstantSearch theme={"system"}
  <ais-configure
    :click-analytics.camel="true"
    user-token.camel="user-1"
  />
  ```
</CodeGroup>

## Update your HTML

Add the following data attributes to your template for Algolia search results within your HTML:

* `data-insights-index`. Select a parent DOM element that contains both your filters and hits UI elements to capture events related to both.
* `data-insights-object-id`. The unique object identifier for the Algolia hit.
* `data-insights-position`. The position in the search results, starting with 1 and taking paginated search results into account.
* `data-insights-query-id`. A unique identifier for relating the <SearchQuery /> and event.

For more information, see the [Insights API reference](/doc/rest-api/insights).

<CodeGroup>
  ```js JavaScript theme={"system"}
  const indexName = "INDEX_NAME";

  const { hits, queryID, page, hitsPerPage } = await client.searchSingleIndex({
    indexName,
    searchParams: {
      query: "query",
      userToken: "user-1",
      clickAnalytics: true,
    },
  });

  const container = document.querySelector("ALGOLIA_SELECTOR");

  container.innerHTML = `
    <div data-insights-index="${indexName}">
      <div id="hits">
        ${
          hits.map((hit, arrayIndex) => `
            <div class="hit"
                data-insights-object-id="${hit.objectID}"
                data-insights-position="${arrayIndex + 1 + page * hitsPerPage}"
                data-insights-query-id="${queryID}"
            >
              <!-- ... -->
            </div>
          `).join('')
        }
      </div>
    </div>
  `;
  ```

  ```js InstantSearch.js theme={"system"}
  /*
    <div data-insights-index="<YourIndexName>">
      <div id="filters"><!-- ... --></div>
      <div id="hits"></div>
    </div>
  */

  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: (hit, { html }) => html`
        <div
          data-insights-object-id="${hit.objectID}"
          data-insights-position="${hit.__position}"
          data-insights-query-id="${hit.__queryID}"
        >
          <!-- ... -->
        </div>
      `,
    },
  }),
  ```

  ```jsx React InstantSearch theme={"system"}
  import { Hits } from 'react-instantsearch';

  const indexName = <YourIndexName>;

  function Hit({ hit }) {
    return (
      <div
        data-insights-object-id={hit.objectID}
        data-insights-position={hit.__position}
        data-insights-query-id={hit.__queryID}
      >
        {/* ... */}
      </div>
    );
  }

  // ...

  <div data-insights-index={indexName}>
    {/* ... */}
    <Hits hitComponent={Hit} />
  </div>
  ```

  ```vue Vue InstantSearch theme={"system"}
  <div :data-insights-index="indexName">
    <!-- .. -->
    <ais-hits>
      <ul slot-scope="{ items }">
        <li
          v-for="item in items"
          :key="item.objectID"
          :data-insights-object-id="item.objectID"
          :data-insights-position="item.__position"
          :data-insights-query-id="item.__queryID"
        >
        </li>
      </ul>
    </ais-hits>
  </div>
  ```
</CodeGroup>

To track <Filter /> events, add a `data-insights-filter` attribute to each filter element (format: `${attribute}:${value}`):

<CodeGroup>
  ```js JavaScript theme={"system"}
  <ul>
    <li data-insights-filter="brand:Apple">Apple</li>
    <li data-insights-filter="brand:HP">HP</li>
    <li>...</li>
  </ul>;
  ```

  ```js InstantSearch.js theme={"system"}
  instantsearch.widgets.refinementList({
    container: "#refinement-list",
    attribute: "brand",
    templates: {
      item: ({ value, isRefined, label, count }, { html }) => html`
        <a
          data-insights-filter="${`brand:${value}`}"
          href="${url}"
          style="${isRefined ? "font-weight: bold" : ""}"
        >
          <span>${label} (${count})</span>
        </a>
      `,
    },
  });
  ```

  ```jsx React InstantSearch theme={"system"}
  import { useRefinementList } from "react-instantsearch";

  function CustomRefinementList(props) {
    const { items, refine } = useRefinementList(props, {
      $$widgetType: "gtm.refinementList",
    });
    return (
      <div>
        <ul>
          {items.map((item) => (
            <li key={item.label} data-insights-filter={`${brand}:${item.value}`}>
              <a
                href="#"
                style={{ fontWeight: item.isRefined ? "bold" : "" }}
                onClick={(event) => {
                  event.preventDefault();
                  refine(item.value);
                }}
              >
                {item.label} ({item.count})
              </a>
            </li>
          ))}
        </ul>
      </div>
    );
  }

  // ...
  <CustomRefinementList attribute={"brand"} />;
  ```

  ```vue Vue InstantSearch theme={"system"}
  <ais-refinement-list attribute="brand">
    <template v-slot:item="{ item, refine, createURL }">
      <a
        :data-insights-filter="`brand:${item.value}`"
        :href="createURL(item.value)"
        :style="{ fontWeight: item.isRefined ? 'bold' : '' }"
        @click.prevent="refine(item.value)"
      >
        <ais-highlight attribute="item" :hit="item"/>
        ({{ item.count.toLocaleString() }})
      </a>
    </template>
  </ais-refinement-list>
  ```
</CodeGroup>

## Send the user token to Google Tag Manager

Send the appropriate user token to GTM when the user's browser session changes:

```js JavaScript icon=code theme={"system"}
window.dataLayer.push({
  algoliaUserToken: "user-1",
});
```

If you're using the [`search-insights`](https://github.com/algolia/search-insights.js) library,
use its `onUserTokenChange` method to sync the user token with GTM:

```js JavaScript icon=code theme={"system"}
aa(
  "onUserTokenChange",
  (userToken) => {
    window.dataLayer.push({
      algoliaUserToken: userToken,
    });
  },
  { immediate: true },
);
```

The `onUserTokenChange` method is supported in `search-insights` versions 1.5.0 or later.

## Send view events

GTM doesn't know when users see new search results, as these are rendered client-side on the users' devices.
To inform GTM, you need to manually push view events to the data layer.

<CodeGroup>
  ```js JavaScript theme={"system"}
  const { hits, queryID } = await client.searchSingleIndex({
    indexName: "INDEX_NAME",
    searchParams: {
      /* ... */
    },
  });
  const container = document.querySelector("ALGOLIA_SELECTOR");
  container.innerHTML = `...`;

  dataLayer.push({ event: "Hits Viewed" }); // [!code ++]
  ```

  ```js InstantSearch.js theme={"system"}
  const search = instantsearch({
    insights: {
      onEvent(event) {
        const { widgetType, eventType, payload, hits } = event;

        if (widgetType === "ais.hits" && eventType === "view") {
          dataLayer.push({ event: "Hits Viewed" });
        }
      },
    },
  });
  ```

  ```jsx React InstantSearch theme={"system"}
  <InstantSearch
    insights={{
      onEvent(event) {
        const { widgetType, eventType, payload, hits } = event;

        if (widgetType === "ais.hits" && eventType === "view") {
          dataLayer.push({ event: "Hits Viewed" });
        }
      },
    }}
  />;
  ```

  ```vue Vue InstantSearch theme={"system"}
  <!-- Required: Vue InstantSearch >= 3.7.0 -->
  <template>
    <ais-instant-search
      :index-name="<index-name>"
      :search-client="searchClient"
      :middlewares="middlewares"
    >
      <!-- widgets -->
    </ais-instant-search>
  </template>

  <script>
  import {
    createInsightsMiddleware,
  } from 'instantsearch.js/es/middlewares';

  const insightsMiddleware = createInsightsMiddleware({
    insightsClient: null, // or `window.aa`
    onEvent(event) {
      const { widgetType, eventType, payload, hits } = event;

      if (widgetType === 'ais.hits' && eventType === 'view') {
        dataLayer.push({ event: 'Hits Viewed' });
      }
    }
  });

  export default {
    data() {
      return {
        // ...
        middlewares: [insightsMiddleware]
      }
    },
  }
  </script>
  ```
</CodeGroup>

<Info>
  You can use the Insights option with
  [InstantSearch.js](/doc/api-reference/widgets/instantsearch/js#param-insights),
  [Vue InstantSearch](/doc/api-reference/widgets/instantsearch/vue#param-insights),
  or [React InstantSearch](/doc/api-reference/widgets/instantsearch/react#param-insights).
</Info>

## Add the Algolia Search Insights template

Before sending events to the Insights API, add the [**Algolia Search Insights**](https://tagmanager.google.com/gallery/#/owners/algolia/templates/search-insights-gtm) template to your workspace.

1. Sign in to your GTM workspace and go to **Tag Templates > Search Gallery**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tag-template-step1.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=95d02c80a9cdaedbb1cb3686f1bf35d0" alt="Search for the Algolia Search Insights template in your Workspace" width="1280" height="588" data-path="images/guides/gtm/add-tag-template-step1.png" />

2. Search for the Algolia Search Insights template (by Algolia).

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tag-template-step2.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=da66f7cb8f682c4ce5fbabf2429a01bd" alt="Select the Algolia Search Insights template in your Workspace" width="1280" height="602" data-path="images/guides/gtm/add-tag-template-step2.png" />

3. Click **Add to workspace** and confirm by clicking **Add**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tag-template-step3.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=0db4169d42d13e0c2e55da33fc704ef3" alt="Add the Algolia Search Insights template in your Workspace" width="1280" height="599" data-path="images/guides/gtm/add-tag-template-step3.png" />

4. On the **Tag Templates** page, you should now see the **Algolia Search Insights** template:

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tag-template-step4.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=461e8b5917bfb8b74fd47c3fd4842231" alt="Algolia Search Insights template added in your Workspace" width="1280" height="550" data-path="images/guides/gtm/add-tag-template-step4.png" />

## Add variables

[Variables](https://support.google.com/tagmanager/answer/7683056?hl=en) are named placeholders for values that are populated when code is run on your website or app.

### Built-in variables

First, add the built-in variable **Click Element**.
This variable is associated with the data from your click events.

1. In the **Variables** section of your GTM workspace, click **Configure**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-click-element-step1.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=0ccba3e5748154f0199d948dcc792316" alt="Screenshot of the Google Tag Manager interface showing the 'Built-In Variables' section with a list of variables and a highlighted 'Configure' button." width="1280" height="509" data-path="images/guides/gtm/add-click-element-step1.png" />

2. In the **Configure Built-In Variables** dialog, select **Click Element**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-click-element-step2.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=999e34e326217c794d75b32d3142d2d2" alt="Screenshot of the Google Tag Manager 'Configure Built-In Variables' panel with 'Click Element' selected under 'Clicks'." width="1280" height="563" data-path="images/guides/gtm/add-click-element-step2.png" />

### Algolia Insights User Token

1. In the **Variables** section of your GTM workspace, go to the **User-Defined Variables** section and click **New**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-data-layer-variable-step1.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=354d5f1d6855868069b5ace1414e7d18" alt="Screenshot of Google Tag Manager's Variables section, highlighting the 'New' button for creating user-defined variables." width="1280" height="746" data-path="images/guides/gtm/add-data-layer-variable-step1.png" />

2. Select **Data Layer Variable**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-data-layer-variable-step2.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=622aa4484c17dc65b5c40dcc3c7882eb" alt="Screenshot of a Google Tag Manager interface showing the 'Choose variable type' menu, with the 'Data Layer Variable' option highlighted." width="1280" height="740" data-path="images/guides/gtm/add-data-layer-variable-step2.png" />

3. Enter `Algolia Insights User Token` as the variable name and `algoliaUserToken` as the data layer variable name.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-user-token-variable.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=27d9b1d349b0756f75a1e4a7da50380b" alt="Screenshot of a 'Variable Configuration' dialog showing a 'Data Layer Variable' named 'algoliaUserToken' with 'Version 2' selected." width="1280" height="578" data-path="images/guides/gtm/add-user-token-variable.png" />

### Algolia Get Data Attributes

1. In the **Variables** section of your GTM workspace, go to the **User-Defined Variables** section and click **New**.

2. Select **Custom JavaScript**.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-custom-javascript.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=99092e1f39d8d67a636db0d80f196611" alt="Screenshot of a Google Tag Manager interface showing the 'Choose variable type' menu with 'Custom JavaScript' highlighted under 'Page Variables.'" width="2564" height="1456" data-path="images/guides/gtm/add-custom-javascript.png" />

3. Enter `Algolia Get Data Attributes` as variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     function findClosest(target, selector) {
       while (!target.matches(selector) && !target.matches('body')) {
         target = target.parentElement;
       }
       return target.matches(selector) ? target : undefined;
     }

     return function (attributeName, containerQuerySelector) {
       var clickedElement = {{Click Element}};

       // Search for the selector's children
       var elements = clickedElement
         ? [findClosest(clickedElement, '[' + attributeName +']')]
         : Array.from(document.querySelectorAll((containerQuerySelector || '') + ' [' + attributeName + ']')).filter(Boolean);

       // See if it matches the container itself.
       // For example, `#app[data-insights-index]`
       if (elements.length === 0 && containerQuerySelector) {
         elements = Array.from(document.querySelectorAll(containerQuerySelector + '[' + attributeName + ']')).filter(Boolean);
       }

       var attributes = elements.map(function (element) {
         return element.getAttribute(attributeName);
       });

       return attributes;
     }
   }
   ```

### Algolia Insights index

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights Index` as variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     return {{Algolia Get Data Attributes}}('data-insights-index')[0];
   }
   ```

When searching multiple indices, you must specify which <Index /> to track.
Add an optional query selector with the `data-insights-index` attribute.

For example, if you have the following HTML:

```html HTML icon=code-xml theme={"system"}
<div id="index-1" data-insights-index="YourIndexName">
  <div id="hits">
    <!-- ... -->
  </div>
</div>

<div id="index-2">
  <div id="hits">
    <!-- ... -->
  </div>
</div>
```

Select the `div` element with the id `index-1` for tracking events:

```js JavaScript icon=code theme={"system"}
function() {
  return {{Algolia Get Data Attributes}}('data-insights-index', '#index-1')[0];
}
```

### Algolia Insights ObjectIDs

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights ObjectIDs` as variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     return {{Algolia Get Data Attributes}}('data-insights-object-id');
   }
   ```

When searching multiple indices, you must [specify which index to track](#algolia-insights-index).

### Algolia Insights Positions

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights Positions` as variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     return {{Algolia Get Data Attributes}}('data-insights-position');
   }
   ```

When searching multiple indices, you must [specify which index to track](#algolia-insights-index).

### Algolia Insights QueryID

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights QueryID` as the variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     return {{Algolia Get Data Attributes}}('data-insights-query-id')[0];
   }
   ```

When searching multiple indices, you must [specify which index to track](#algolia-insights-index).

### Algolia Insights Viewed Filters

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights Viewed Filters` as the variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     var attributeName = 'data-insights-filter';
     var elements = Array.from(document.querySelectorAll('[' + attributeName + ']'));
     var attributes = elements.map(function (element) {
       return element.getAttribute(attributeName);
     });
     return attributes;
   }
   ```

### Algolia Insights Clicked Filters

1. [Add a new user-defined variable](#algolia-get-data-attributes).
2. Enter `Algolia Insights Clicked Filters` as variable name and add the following JavaScript code:

   ```js JavaScript icon=code theme={"system"}
   function() {
     return {{Algolia Get Data Attributes}}('data-insights-filter')
   }
   ```

When searching multiple indices, you must [specify which index to track](#algolia-insights-index).

## Add custom triggers

[Triggers](https://support.google.com/tagmanager/answer/7679316?hl=en) listen to selected types of events on your website or app
and tell the tags to fire, when a specified event is detected.

### Add a trigger for view events

To capture the view events you [send from your website](#send-view-events)
you must add a custom trigger.

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-hits-viewed-trigger.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=ebded3fd4fcfe9e6772df3ce942577a1" alt="Screenshot of the Google Tag Manager 'Hits Viewed' trigger configuration with 'Custom Event' selected and 'All Custom Events' chosen." width="1280" height="551" data-path="images/guides/gtm/add-hits-viewed-trigger.png" />

Select the following values for the corresponding fields:

* Trigger name: `Hits Viewed`
* Trigger type: `Custom Event`
* Event name: `Hits Viewed`

### Customize triggers for click events

Click or conversion events come from user actions,
such as clicks on DOM elements.

Consider this template:

```html HTML icon=code-xml theme={"system"}
<div data-insights-index="<your-index-name>">
  <div id="hits">
    <article
      class="hit"
      data-insights-object-id="{{objectID}}"
      data-insights-position="{{__position}}"
      data-insights-query-id="{{__queryID}}"
    >
      <h1>{{name}}</h1>
      <p>{{description}}</p>

      <button class="btn-view-details" type="button">
        View Details
      </button>
    </article>
    <!-- ... -->
  </div>
</div>
```

To configure a click on the **View Details** button as a trigger in GTM, select `Click - All Elements` as the trigger type
and configure the trigger to fire only when the click text matches View Details.

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-custom-trigger1.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=e4f55255ac09f6e5e56d485b8d64c28f" alt="Screenshot of a 'Click - All Elements' trigger configuration with 'Some Clicks' selected and a condition for 'Click Text equals View Details'." width="2558" height="1032" data-path="images/guides/gtm/add-custom-trigger1.png" />

You can also configure the trigger to fire when the click target matches a CSS selector:

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-custom-trigger2.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=8e5ce3d60fe4da0688fa8fbfd32b4a80" alt="Add custom trigger with CSS selector matching in GTM" width="2558" height="1032" data-path="images/guides/gtm/add-custom-trigger2.png" />

### Customize triggers for filters

To track clicked filters, create a trigger that matches the CSS selector of your filter elements.

Consider this template:

```html HTML icon=code-xml theme={"system"}
<div class="ais-RefinementList">
  <ul class="ais-RefinementList-list">
    <li class="ais-RefinementList-item">
      <div>
        <label data-insights-filter="brand:Apple">
          <input type="checkbox" value="Apple" />
          <span class="ais-RefinementList-labelText">Apple</span>
          <span class="ais-RefinementList-count">746</span>
        </label>
      </div>
    </li>
    <li class="ais-RefinementList-item">
      <!-- ... -->
    </li>
    <!-- ... -->
  </ul>
</div>
```

In this example, the CSS selector can be `.ais-RefinementList-labelText`.
You must add the `data-insights-filter` attribute to the element matching the `.ais-RefinementList-labelText` selector,
or to a parent element at a higher level in the DOM.

## Set up tags

Tags are the functions that run when a trigger is fired.
When using GTM with Algolia, each tag corresponds to one [method](/doc/libraries/search-insights) for sending a specific event.

### Set up your initialization tag

First, you **must** set up an initialization tag to [connect with the Algolia Insights API](/doc/libraries/search-insights/init).

1. In your GTM workspace, go to the **Tags** section and select **Algolia Search Insights**.
2. In the **Init Options** section, enter your Algolia <ApplicationID /> and <APIKey /> with [search](/doc/guides/security/api-keys#access-control-list-acl) permissions.
3. In the **Triggering** section, select **Initialization—All Pages** to trigger this tag on all pages.

   <img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tags-init.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=a6d9acb519f3cf742930f62ec8d4bbee" alt="Screenshot of Google Tag Manager tag config for 'Algolia Search Insights' with 'Initialization' method and 'App ID' and 'API Key' fields." width="1278" height="1024" data-path="images/guides/gtm/add-tags-init.png" />

### Set up view tags for objects

This tag sends a [view event](/doc/guides/sending-events/concepts/event-types) to the Algolia Insights API when search results are rendered.
It corresponds to the [`viewedObjectIDs`](/doc/libraries/sdk/v1/methods/viewed-object-ids) method.

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tags-viewed-object-ids.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=1781e7eae8cdb5ed740624939bcf47a8" alt="Screenshot of a Google Tag Manager tag configuration for 'Algolia Search Insights' with event and triggering details." width="1278" height="940" data-path="images/guides/gtm/add-tags-viewed-object-ids.png" />

Attributes:

* Trigger: [`Hits Viewed`](#add-a-trigger-for-view-events)
* Tag type: `Algolia Search Insights`
* Tag method: `Viewed Object IDs`
* Event name: select any name for your events but [name your events consistently](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/).

### Set up view tags for filters

This tag sends a [view event](/doc/guides/sending-events/concepts/event-types) to the Algolia Insights API when a filter is applied to the search query.
It corresponds to the [`viewedFilters`](/doc/libraries/sdk/v1/methods/viewed-filters) method.

Attributes:

* Trigger: [`Hits Viewed`](#add-a-trigger-for-view-events)
* Tag type: `Algolia Search Insights`
* Tag method: `Viewed Filters`
* Filters: [`{{Algolia Insights Viewed Filters}}`](#algolia-insights-viewed-filters)
* Event name: select any name for your events but [name your events consistently](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/).

### Set up click tags for objects related to search

This tag sends a [click event](/doc/guides/sending-events/concepts/event-types) to capture a search query and the clicked items and their positions.
It corresponds to the [`clickedObjectIDsAfterSearch`](/doc/libraries/sdk/v1/methods/clicked-object-ids-after-search) method.

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/add-tags-clicked-object-ids-after-search.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=241d0e4032faa62ee35e1958c049bd71" alt="Screenshot of a Google Tag Manager tag configuration for 'Algolia Search Insights' with 'Clicked Object IDs After Search' method." width="2560" height="2534" data-path="images/guides/gtm/add-tags-clicked-object-ids-after-search.png" />

Attributes:

* Trigger: [`View Details`](#customize-triggers-for-click-events)
* Tag type: `Algolia Search Insights`
* Tag method: `Clicked Object IDs After Search`

### Set up click tags for objects

This tag sends a [click event](/doc/guides/sending-events/concepts/event-types) to the Insights API when users select an item from an Algolia index, regardless of the associated query.
This event can be useful on product detail pages or the shopping cart.
This tag corresponds to the [`clickedObjectIDs`](/doc/libraries/sdk/v1/methods/clicked-object-ids) method.

Attributes:

* Trigger: [`View Details`](#customize-triggers-for-click-events)
* Tag type: `Algolia Search Insights`
* Tag method: `Clicked Object IDs`

### Set up click tags for filters

This tag sends a [click event](/doc/guides/sending-events/concepts/event-types) to the Insights API to capture selected filters.
It accepts the [`{{Algolia Insights Clicked Filters}}`](#algolia-insights-clicked-filters) attribute and corresponds to the [`clickedFilters`](/doc/libraries/sdk/v1/methods/clicked-filters) method.

Attributes:

* Trigger: [`View Details`](#customize-triggers-for-filters)
* Tag type: `Algolia Search Insights`
* Tag method: `Clicked Filters`

### Set up conversion tags

The following tags send a [conversion event](/doc/guides/sending-events/concepts/event-types) to the Insights API:

* **Search-related objects**. Captures a search query and the converted items. It corresponds to the [`convertedObjectIDsAfterSearch`](/doc/libraries/sdk/v1/methods/converted-object-ids-after-search) method. Set up this tag like the related [click tag](#set-up-click-tags-for-objects-related-to-search).
* **Objects**. Captures items, regardless of the associated query. It corresponds to the [`convertedObjectIDs`](/doc/libraries/sdk/v1/methods/converted-object-ids) method. Set up this tag like the related [click tag](#set-up-click-tags-for-objects).
* **Filters**. Captures converted filters. It corresponds to the [`convertedFilters`](/doc/libraries/sdk/v1/methods/converted-filters) method. Set up this tag like the related [click tag](#set-up-click-tags-for-filters).

#### Track add-to-cart and purchase events

If you have an ecommerce website, use [conversion tags](/doc/guides/sending-events/connectors/google-tag-manager#set-up-conversion-tags) to track add-to-cart and purchase conversion events.
This enhances Algolia's AI and unlocks features such as revenue analytics.

Configure the additional **event subtype**, **value**, **currency**, and **object data** (**price**, **discount**, **quantity**) attributes for add-to-cart and purchase events.

To track purchases of multiple items that are associated with different searches, use the **Objects** tag and specify the **query ID** values within the **object data** attribute.
For example, if your object IDs list is `["product-1", "product-2"]`, then your object data list might look like:

```json JSON icon=braces theme={"system"}
[
  { "queryID": "query-1", "price": 10, "quantity": 1, "discount": 0 },
  { "queryID": "query-2", "price": 5, "quantity": 2, "discount": 15.5 }
]
```

## Submit your changes and debug your events

After setting up the variables, tags, and triggers, submit your changes.
To ensure all variables are set correctly, use [Google Tag Assistant](https://tagassistant.google.com/).

<img src="https://mintcdn.com/algolia/AACpGv43fS_1tsyy/images/guides/gtm/tag-assistant-inspect-event.png?fit=max&auto=format&n=AACpGv43fS_1tsyy&q=85&s=0541dff6fa5325fa721fcce5bcb8162a" alt="Ensure all Algolia variables have the expected values" width="1084" height="522" data-path="images/guides/gtm/tag-assistant-inspect-event.png" />

The next step is to [validate your events](/doc/guides/sending-events/guides/validate).
