🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
Guides / Sending events / Connectors

To use Google Tag Manager (GTM) for sending click and conversion 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, you need to track the queryID. To include the queryID in the search response, add the clickAnalytics parameter to true.

To identify users, add the userToken parameter.

1
2
3
4
5
6
index.search('YourSearchQuery', {
  userToken: 'user-1',
  clickAnalytics: true
}).then(({ hits, queryID }) => {
  console.log(hits, queryID);
})

Update your HTML

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

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
const indexName = <YourIndexName>;

index.search('query', {
  userToken: 'user-1',
  clickAnalytics: true
}).then(({ hits, queryID, page, hitsPerPage }) => {
  const container = document.querySelector('<YourSelector>');

  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>
  `
});

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

1
2
3
4
5
<ul>
  <li data-insights-filter="brand:Apple">Apple</li>
  <li data-insights-filter="brand:HP">HP</li>
  <li>...</li>
</ul>

Send the user token to Google Tag Manager

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

1
2
3
window.dataLayer.push({
  algoliaUserToken: 'user-1',
});

If you’re using the search-insights library, you can use its onUserTokenChange method to sync the user token with GTM:

1
2
3
4
5
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 push view events to the data layer manually.

1
2
3
4
5
6
index.search('query', { /* ... */ }).then(({ hits, queryID }) => {
  const container = document.querySelector('<your-selector>');
  container.innerHTML = `...`

+  dataLayer.push({ event: 'Hits Viewed' });
});

If you’re using InstantSearch.js, Vue InstantSearch, and React InstantSearch you can use the Insights option.

Add the Algolia Search Insights template

Before you can send events to the Insights API, you must add the Algolia Search Insights template to your workspace.

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

    Search for the Algolia Search Insights template in your Workspace

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

    Select the Algolia Search Insights template in your Workspace

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

    Add the Algolia Search Insights template in your Workspace

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

    Algolia Search Insights template added in your Workspace

Add variables

Variables 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.

    Configure variable click element in GTM - step 1

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

    Configure variable click element in GTM - step 2

Algolia Insights User Token

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

    Add Data Layer variable in GTM - step 1

  2. Select Data Layer Variable.

    Add Data Layer variable in GTM - step 2

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

    Add User Token Data Layer variable in GTM

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.

    Add Custom JavaScript variable in GTM

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

    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
    
    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 children of the selector
        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.
  2. Enter Algolia Insights Index as variable name and add the following JavaScript code:

    1
    2
    3
    
    function() {
      return {{Algolia Get Data Attributes}}('data-insights-index')[0];
    }
    

When searching multiple indices, you must specify which index to track. You can add an optional query selector with the data-insights-index attribute.

For example, if you have the following HTML:

1
2
3
4
5
6
7
8
9
10
11
<div id="index-1" data-insights-index="YourIndexName">
  <div id="hits">
    <!-- ... -->
  </div>
</div>

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

You can select the div element with the id index-1 for tracking events:

1
2
3
function() {
  return {{Algolia Get Data Attributes}}('data-insights-index', '#index-1')[0];
}

Algolia Insights ObjectIDs

  1. Add a new user-defined variable.
  2. Enter Algolia Insights ObjectIDs as variable name and add the following JavaScript code:

    1
    2
    3
    
    function() {
      return {{Algolia Get Data Attributes}}('data-insights-object-id');
    }
    

When searching multiple indices, you must specify which index to track.

Algolia Insights Positions

  1. Add a new user-defined variable.
  2. Enter Algolia Insights Positions as variable name and add the following JavaScript code:

    1
    2
    3
    
    function() {
      return {{Algolia Get Data Attributes}}('data-insights-position');
    }
    

When searching multiple indices, you must specify which index to track.

Algolia Insights QueryID

  1. Add a new user-defined variable.
  2. Enter Algolia Insights QueryID as variable name and add the following JavaScript code:

    1
    2
    3
    
    function() {
      return {{Algolia Get Data Attributes}}('data-insights-query-id')[0];
    }
    

When searching multiple indices, you must specify which index to track.

Algolia Insights Viewed Filters

  1. Add a new user-defined variable.
  2. Enter Algolia Insights Viewed Filters as variable name and add the following JavaScript code:

    1
    2
    3
    4
    5
    6
    7
    8
    
    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.
  2. Enter Algolia Insights Clicked Filters as variable name and add the following JavaScript code:

    1
    2
    3
    
    function() {
      return {{Algolia Get Data Attributes}}('data-insights-filter')
    }
    

When searching multiple indices, you must specify which index to track.

Add custom triggers

Triggers listen to selected types of events on your website or app and tell the tags to fire, when a specified event is detected.

Add trigger for view events

To capture the view events you send from your website you must add a custom trigger.

Add Hits Viewed trigger in GTM

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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 trigger type and configure the trigger to fire only when the click text matches View Details.

Add custom trigger with text matching in GTM

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

Add custom trigger with css selector matching in GTM

Customize triggers for filters

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

Consider this template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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 ad 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 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.

  1. In your GTM workspace, go to the Tags section and select Algolia Search Insights.
  2. In the Init Options section, enter your Algolia application ID and API key with search permissions.
  3. In the Triggering section, select Initialization—All Pages to trigger this tag on all pages.

    Initialization tag in GTM

Set up view tags for objects

This tag sends a view event to the Algolia Insights API, when search results are rendered. It corresponds to the viewedObjectIDs method.

Viewed Object IDs tag in GTM

Attributes:

Set up view tags for filters

This tag sends a view event to the Algolia Insights API, when a filter was applied to the search query. It corresponds to the viewedFilters method.

Attributes:

This tag sends a click event to capture a search query and the clicked items and their positions. It corresponds to the clickedObjectIDsAfterSearch method.

Clicked Object IDs After Search tag in GTM

Attributes:

  • Trigger: View Details
  • Tag type: Algolia Search Insights
  • Tag method: Clicked Object IDs After Search

Set up click tags for objects

This tag sends a click event 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 method.

Set up click tags for filters

This tag sends a click event to the Insights API to capture selected filters. It accepts the {{Algolia Insights Clicked Filters}} attribute and corresponds to the clickedFilters method.

This tag sends a conversion event to the Insights API to capture a search query and the clicked items. You can set up this tag like the related click tag. This tag corresponds to the convertedObjectIDsAfterSearch method.

If you have an ecommerce website, you should use this tag to track add to cart and purchase conversions events. Doing so improves how Algolia’s AI works, and unlocks features such as revenue analytics. The event subtype, value, currency and object data (price, discount, quantity) attributes should be configured for add to cart and purchase events.

Set up conversion tags for objects

This tag sends a conversion event to the Insights API to capture items, regardless of the associated query. You can set up this tag like the related click tag. This tag corresponds to the convertedObjectIDs method.

If you have an ecommerce website, you should use this tag to track add to cart and purchase conversions events. Doing so improves how Algolia’s AI works, and unlocks features such as revenue analytics. The event subtype, value, currency and object data (price, discount, quantity) attributes should be configured for add to cart and purchase events.

Set up conversion tags for filters

This tag sends a conversion event to the Insights API to capture converted filters. You can set up this tag like the related click tag. This tag corresponds to the convertedFilters method.

If you have an ecommerce website, you should use this tag to track add to cart and purchase conversions events. Doing so improves how Algolia’s AI works, and unlocks features such as revenue analytics. The event subtype, value, currency and object data (price, discount, quantity) attributes should be configured for add to cart and purchase events.

Submit your changes and debug your events

After setting up the variables, tags, and triggers, submit your changes. To check that you set all variables, use the Google Tag Assistant.

You can check that all the Algolia variables have the expected values

The next step is to validate your events.

Did you find this page helpful?