Introduction
With the help of GTM, it is possible to keep track of shopper activities on your website and hand this activity data over to GA4. GA4 here does the job of event-tracking and summarising this data.
In this document, we have highlighted the steps you need to take to track all Klevu-led activities (events) using GTM and GA4. You will need to follow three steps:
- Configure Google Tag Manager by importing our ready-to-use container configuration.
- Refer to the list of a variety of events Klevu can send to GA4 and add the ones you like to monitor.
- Finally, add a small snippet of Javascript on your front end for Klevu to start sending events.
Eligibility
You have integrated Klevu solutions using the latest JS Library (aka JSv2).
You have Google Tag Manager integrated on your storefront. Click here learn to setup.
You have enhanced ecommerce tracking done through the dataLayer (using a structured JavaScript object to pass ecommerce-related data).
This guide is NOT for you if:
You have used API or SDK to integrate Klevu solutions on your storefront.
You have integrated Klevu solutions using JSv1 (our legacy JS Library).
What You’ll Need
- Access to modify your store’s frontend code.
- Admin access to your Google Tag Manager account.
- Admin access to your Google Analytics 4 account.
1. Google Tag Manager Configuration
This guide assumes that you're already set up with a GTM account and have created a container. A container is a collection of tags, triggers, variables, and other related configurations. You will need a container to import the necessary variables and tags to track Klevu events.
If you have not set up a container or would like to set up a new one, please follow the guide here to do so.
1A. Import the Klevu Container Template
To streamline the process for you, we have prepared a container that contains all the required variables, triggers, and tags. These are required to read events from dataLayer, capture them in GTM along with their Klevu parameters, and pass them to GA4 for reporting.
You can download the container below:
In Google Tag Manager, go to Admin → Import Container,
Select the above-downloaded template in the import file.
Choose an existing workspace, or create a new one.
Choose an import option:
- If you are importing into a container with existing tags, triggers, or variables - choose "Merge"
- If the container is new - choose Overwrite.
Verify that changes will not affect the existing setup and import the container template. You can verify by clicking on “View Detailed Changes” on the Preview and Confirm your import section.
1B. Edit GA4 Tracking ID Variable
Login to your Google Analytics 4 account and copy the GA4 Measurement ID. (Finding your GA4 Measurement ID)
Go back to Google Tag Manager → Workspace → Variables
Select Klevu GA4 Tracking ID
Paste the GA4 Measurement ID in this variable’s value, or update all tags with your own GA4 tracking ID variable.
1C. Regular Ecommerce GTM Events
In the above imported container, we have added some regular GA4 tags, which you may already have in your GTM Worskpace. If you already have these same tags implemented, you should consolidate them to use only one. This will ensure that you do not track multiple duplicate events in your GA4.
GA4 ecommerce clear tag
The ecommerce clear command is necessary in the dataLayer to prevent duplicate or unintended data from being sent to Google Analytics or other analytics tools. It helps ensure the accuracy of your Enhanced Ecommerce tracking by explicitly clearing the ecommerce object in the dataLayer after an event has been processed.
GA4 config tag
If you already have existing GA4 tracking in your Google Tag Manager, you can delete imported GA4 - config tag, but make sure to not use the default pageview from the config file. You should set your config tag to not send the page views by adding the configuration parameter send_page_view to false, and put the highest tag firing priority to it, because you want this tag to fire first always.
GA4 EE events
If you already have enhanced ecommerce tracking implementation done through the GTM, you need to remove this tag, but you will need to update all your existing GA4 enhanced ecommerce tags (view_item, add_to_cart, view_cart, remove_from_cart, begin_checkout, add_shipping_info, add_payment_info or purchase) to the following parameters:
- Event Parameter = items
- Event Value = {{EE item_list - MERGE - CT}}
If you already have existing enhanced ecommerce tags, it is recommended to remove GA4 EE events tag. This is to ensure that duplicate enhanced ecommerce events are not captured in GA4.
1D. Klevu GA4 Attribution Events
It's really helpful to know which parts of your site are catching customers' attention attributed to Klevu. That's where setting up 'list parameters' ["item_list_id" and "item_list_name"] comes in. They help track which product listings or page sections are sparking interest with Klevu as a source.
We know this setup can seem a bit tricky. So, we've already added this to the template that you imported earlier. Basically, when someone clicks on a product, this template remembers which list or section they clicked from and then keeps track of what they do next, like viewing more details or adding to the cart.
To get started with our template, you'll just need to tweak a few things in your current e-commerce setup. It's a key step for making sure everything's tracked correctly and gives you clearer insights into what's working on your site.
1D-i. GA4 select_item Event
Klevu uses the “klevu_click” event for tracking clicks in all of Klevu’s product listings [search, quick_search, recommendations and category)
If you have additional events with item_list_id and item_list_name parameters added to those events, then,
Navigate to Workspace → Triggers
Update the Event Name parameter to = ^(klevu_click|add_to_cart|klevu_add_to_cart|productClick)$
Once you have followed all the steps, please make sure to Publish your workspace changes. Please note that Google takes up to 36 hours for changes to take effect before you can see data in GA4. However, you can refer to section 4 in this document to verify your integration once all steps are completed.
1D-ii. GA4 view_item_list Event
This event is designed to track user interactions with Klevu search and product discovery features, sending detailed data about search behavior, category, and recommendations to GA4 for analysis. It helps businesses understand how users interact with product lists and optimize search and navigation for better conversions.
1D-iii. GA4 search Event
This GA4 search event tag tracks user interactions with Klevu-powered search functionality. It captures details about user search behavior, such as the search term, filter usage, and results count, allowing businesses to analyze how effectively the search experience contributes to user engagement and conversions.
1D-iv. GA4 klevu_filter Event
The klevu_filter event tracks user interactions with filters in Klevu-powered search or navigation interfaces. It provides detailed insights into which filter attributes (e.g., brand, color, size) and filter options users select during their product discovery journey.
1D-v. GA4 Klevu Attribution Local Storage Setter
The GA4 Klevu Attribution Local Storage Setter tag is designed to store specific data (related to product interactions) in the browser's local storage. This tag helps preserve attribution details such as user interactions with product lists, clicks, or other events for future use in analytics or further tracking.
2. Create Custom Dimensions in GA4
Klevu sends many crucial parameters (listed in the table below) with its GA4 events. If you'd like to report on them in GA4, please create custom dimensions in GA4.
Login to Google Analytics 4 account as an admin.
Navigate to GA4 → Admin → Select the correct account & property → Custom Dimensions
Click on Create Custom Dimension
Enter a Name, Scope, Description, and event Parameter. Refer to the table below for a list of possible custom dimensions.
2A. Custom Dimension Reference
Please note that the Event Parameter needs to be input exactly as provided below.
Dimension Name | Scope | Event Parameter | Value examples | Description |
Klevu Search Type | Event | klevu_search_type |
| Type of search - Which content types were searched/included in the search |
Klevu Component | Event | klevu_component |
| Klevu component identifier |
Klevu Recommendation Logic | Event | klevu_component_method |
| Klevu's method/logic used for recommendations or merchandising |
Klevu Search Term | Event | klevu_search_term |
| search term used |
Number of Klevu Search Results | Event | klevu_search_results_num |
| number of products returned by the search, send 0 if no results |
Klevu Filter Attribute | Event | klevu_filter_attribute |
| Filter attribute name/label |
Klevu Fitler Value | Event | klevu_filter_option |
| Selected option name/label, for price ranges create a string "from-to" |
Klevu Category Name | Event | klevu_category_name |
| Category Name, in the form of breadcrumb |
Klevu Results Page Number | Event | klevu_page_num |
| Pagination number [if paginated content] |
Klevu Recommendation Title | Event | klevu_recommendation_name |
| Smart recommendation box name/label |
Klevu Page Type | Event | klevu_page_type |
| Page type where recommendations box is rendered |
Klevu API Key | Event | klevu_store_id |
| The ID of Klevu store |
Klevu Was Filter Used | Event | klevu_filter_used |
| Was the search filter applied? |
Item Klevu Category | Item | item_klevu_category | ||
Item Klevu Component | Item | item_klevu_component |
Once you have added the Custom Dimensions in GA4, your list should look like the following:
3. Changes to Store Theme Code
You will need to add a snippet of code to your store’s theme to ensure that Klevu pshes events to the dataLayer that will be read by GTM. Please see the steps by platform below:
3A. For Magento
Log in to your Magento Backend Admin.
Navigate to Content → Design → Configuration → {store} Edit → Other Settings → HTML Head → Scripts and Style Sheets
Add the below code to the Scripts & Style Sheets section, and click on Save Configuration. You will notice an extra function here. This function parses the category name in case it is nested. E.g. a product that belongs to Mens → Tops → Shirts will be indexed at Klevu as Mens;;;;Tops;;;;Shirts, and hence for accurate category mapping, the extra function will correctly parse the product ID. from the correct category.
<script>
var klevu_connectors = {gtm:{enabled:true}};
window._klvReady = window._klvReady || [];
window._klvReady.push(function(){
// add extra fields for category
klevu({analytics:{product:{fields:["klevu_category"]}}});
//change the way we collect the item id
klevu.support.hook(["analytics.gtmDataExtract"],function(){
// add the processor
klevu.analytics.dataExtract.gtm.addProcessor("product","item_id",function(item){
let sku = klevu.getObjectPath(item,"sku","");
sku = sku.split(";;;;");
if(sku.length > 1){
sku = sku[1];
} else {
sku = sku[0];
}
return sku;
});
// tell data extractor to include the attribute
klevu({analytics:{gtm:{product:{fields:["item_id"]}}}});
});
});
</script>
3B. For Shopify
Log in to your Shopify Admin Backend,
From the left panel, navigate to Online Store → Click on … from the active theme → Edit Code,
Find your theme.liquid file, and right before the closing </head> tag add the following:
{% render 'klevu-customizations' %}
Navigate to snippets and click on + Add a new snippet and name it klevu-customizations.liquid
Add the following code in the klevu-customizations.liquid file as shown below. This code enables the dataLayer events to be pushed.
<script>
var klevu_connectors = {
gtm:{
enabled:true
}
};
</script>
This script is critical for ensuring consistency between Klevu's data extraction and your existing Enhanced Ecommerce setup in Google Tag Manager (GTM). If your Enhanced Ecommerce implementation already sends product identifiers (item_id) to GA4, and you have adjusted events like view_item_list to accommodate grouped, configurable, or bundled products, this code ensures that Klevu aligns with the same item_id values. By default, Klevu handles simple products correctly, but for these more complex product types, the script ensures the group-level identifier is sent to GA4. In the case of the Shopify, it’s itemGroupId
<script>
window._klvReady= window._klvReady|| [];
window._klvReady.push(function(){
klevu.support.hook(["analytics.gtmDataExtract"],function(){
klevu.analytics.dataExtract.gtm.addProcessor("product","item_id",
function(item){return item.itemGroupId;}); // add the processor
klevu({analytics:{gtm:{product:{fields:["item_id"]}}}}); // tell data extractor to include the attribute , need to do it even if the attribute is already included
});
});
</script>
If you have enabled klevu add to cart buttons on your product lists, add the following code to track those events too
<script>
function klevu_addtocart( id, url, qty, recsKey,scope){
//normal code added by platform here based on https://docs.klevu.com/template-js/add-to-cart-function , exit function if the add to cart is fail
//create and store the add to cart event
let product = klevu.analytics.dataExtract.search.itemByIdFromScope(id, scope);
if (product.length > 0) {
let collectorPayload;
// recs specific event manipulation
if(recsKey){
collectorPayload = klevu.getObjectPath(scope.kScope.parentScope,"viewPayload",false);
if(collectorPayload){
klevu.setObjectPath(collectorPayload,"type","add_to_cart");
klevu.setObjectPath(collectorPayload,"data.items",product);
}
} else {
// other search scopes event manipulation
collectorPayload = {
type:"add_to_cart",
component:"search",
scope:scope.kObject.getWebhookSettings().scope,
object:scope.kObject.getWebhookSettings().object,
apiKey:klevu.getSetting(scope.kData.settings, "settings.search.apiKey", klevu.getGlobalSetting("search.apiKey", klevu.getGlobalSetting("global.apiKey"))),
user:{},
data:{
meta:klevu.analytics.dataExtract.search.metaFromScope(scope.kScope),
filters:klevu.analytics.dataExtract.search.filtersFromScope(scope.kScope),
items:product
}
};
}
//add event to collector
if(!klevu.isUndefined(klevu.support.hook)){
klevu.support.hook(["analytics.collector"],function(){
klevu.analytics.collector.addEvent(collectorPayload);komal
});
}
}
if ('undefined' !== typeof klevu_customAddToCart) {
klevu_customAddToCart(id, url, 1);
} else {
var urlProtocol = ( "https:" === document.location.protocol ? "https://" : "http://" );
var url = urlProtocol + window.location.hostname + '/cart/add?id=' + id + '&quantity=1';
window.location.assign(url);
}
}
</script>
3C. For BigCommerce
Log in to your BigCommerce Backedn Admin Panel
From the left panel, navigate to Storefront → Script Manager → Create a Script
Enter a Script Name e.g. Push Klevu Events to GTM/GA4
Choose Placement as Header
Choose Location as All Pages
Choose Category as Analytics
Choose Script Type as Script
Copy paste the below code in Script Contents input box
<script>
var klevu_connectors = {
gtm:{
enabled:true
}
};
</script>
3D. For All Other Platforms
For any other platforms not listed above, add the following code inside the <head> section of your store’s theme files. It is recommended that you place the snippet as high as possible within the <head> section.
<script>
var klevu_connectors = {
gtm:{
enabled:true
}
};
</script>
4. Test your GA4 Set Up
Once you have followed the above guide and made the necessary, you can use the GTM Assistant to check if you are correctly receiving events and data from your storefront to GTM.
Log in to your Google Tag Manager Account → Select the Workspace where you have imported the Klevu Container.
Click on Preview from the top right in the menu bar.
This will open a new tab & prompt you to enter your website’s URL. Enter the URL and click on Connect.
On clicking Connect, your site will open in a new window/tab, and if the connection is successful, you will see a dialog box on your site (as shown below). If you do not see this dialog box, then your connection was unsuccessful. Learn more on fixing this.
Once the connection is successful, on your website use a Klevu-powered search, and click on a product. Once done, navigate back to the Tag Assistant tab. You should now see Klevu-related events in the side panel and their relevant tags fired when you select an activity (as shown below).
If you see these events being tracked and tags being fired, it means that the integration is now successful.