top of page

How to leverage Javascript in GTM to enhance your ecommerce tracking

Google Tag Manager (GTM) is a powerful tool for managing tracking codes on your website without the need for manual code changes. For new users, it's essential to grasp how GTM can simplify the tracking of critical e-commerce and product-related data. In this article, we explore five use cases where custom JavaScript functions can be leveraged in GTM to streamline the tracking of product data.

1. Constructing Product Data

The first use case involves constructing an array of product objects. This application becomes particularly valuable when your ecommerce data has not been accurately integrated into your data layer. It may occur that essential product information (such as ID, name, price, etc.) that ideally should be structured within an "object" is mistakenly arranged as individual keys.

An erroneous implementation of your ecommerce data can result in significant tracking issues, hindering various Analytics tools from effectively processing your data. For instance, in the context of Google Analytics 4, it is imperative to transmit product data as an object to properly populate its ecommerce reports.

// Function to construct an array of product objects

function() {

  var items = [{

    'id': {{data layer variable}},
    'name': {{data layer variable}},
    'category': {{data layer variable}},
    'quantity': {{data layer variable}},
    'price': {{data layer variable}},
    'currency': {{data layer variable}}


  return items;


The code above defines an anonymous JavaScript function that initializes a variable named items and assigns it an array containing a single object. Each object represents a product and has properties such as 'id', 'name', 'category', 'quantity', 'price', and 'currency'. The values for each property are expected to be obtained from your data layer, as indicated by {{data layer variable}}.

2. Transforming Basket Data

The second use case revolves around handling product data within a designated product "object." This application proves especially beneficial when the terminology employed in your data layer deviates from the specifications set by your preferred Analytics tool.

The majority of Analytics tools require adherence to a specific naming convention for product data to be identified as ecommerce parameters. If, for instance, the product data being transmitted to Google Analytics 4 does not align with the naming conventions outlined in Google's documentation, it could result in an incomplete population of Google Analytics 4 ecommerce reports.

// Function to process and structure product data from a user's basket

function() {

  var basket_products = {{items}};
  var cleaned_products = [];

  // Helper function to construct product objects

  function rebuildItems(p) {

    var product = {

      'id': p.identifier,
      'name': p.Name,
      'category': p.Category,
      'category_2': p.Category2,
      'price': p.Price,
      'quantity': p.Qty





  return cleaned_products;


The code above defines an anonymous JavaScript function that iterates over the properties within product objects retrieved from your data layer. During this process, it constructs new product objects where each property inside the object is assigned the desired naming.

3. Calculating Total Revenue

The third use case focuses on computing the total value of a basket in cases where this information is not directly available in your data layer.

Businesses integrate ecommerce tracking on their websites primarily to monitor and evaluate their performance. Failing to furnish a value parameter to your Analytics tool hinders the achievement of this essential objective. Without the required data, your Analytics tool cannot populate the necessary information in your ecommerce reports, preventing a comprehensive assessment of your website's performance.

// Function to calculate the total value of products in a shopping cart

function () {

  var products = {{items}};
  var total = 0;
  products.forEach(function(product) {
    total += (product.price*product.quantity);


  return parseFloat(total.toFixed(2));


The code above defines an anonymous JavaScript function that iterates over each product object within the "Products" array obtained from the data layer. Within this iteration, the function computes the total value of the items in the basket by adding up the product of each item's price and quantity. The final result is returned as a formatted floating-point number with two decimal places.

4. Tracking Total Quantity

The fourth use case delves into calculating the total quantity of items in a basket in cases where this information is absent from your data layer.

Businesses often opt to implement ecommerce tracking on their websites not only to monitor performance but also to gain insights into inventory levels and purchasing patterns. In the realm of e-commerce and stock management, having a clear understanding of the total quantity of items in the cart proves invaluable.

// Function to calculate the total quantity of products in a shopping cart

function () {

  var Products = {{items}};
  var total = 0;
  Products.forEach(function(product) {
    total += product.quantity;


  return total;


The code above defines an anonymous JavaScript function that iterates through each product object within the "Products" array obtained from the data layer. In this iteration, the function calculates the total quantity of products in the basket by adding up the quantity of each item.

5 - Creating a custom cookie

The fifth use case can be viewed as a bonus, focusing on creating a tailored cookie to preserve the content of a user’s basket. 

In situations where a user adds items to their basket but departs the website without finalizing the purchase, storing the basket's contents becomes valuable. This allows for strategic interventions, such as triggering a pop-up upon the user's return. The pop-up can serve as a reminder of the items in the basket and offer options to resume the checkout process or continue shopping.

This approach aligns with the common strategy of abandoned cart recovery, aiming to re-engage users and potentially boost conversion rates by addressing incomplete transactions.


  (function() {

var cookieName = "user_basket"; // Name of your cookie
var cookieValue = {{Your data layer Variable}}; // Value of your cookie
var expirationTime = 86400; // One year in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date(); 
var dateTimeNow = date.getTime(); 

date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month)
var date = date.toUTCString(); // Converts milliseconds to UTC time string

document.cookie = cookieName+"="+cookieValue+"; path=/; SameSite=None; Secure"; expires="+date+";



The code above defines an anonymous JavaScript function that scans through the data layer, extracts the content of a user’s basket and saves it in a cookie. This function generates a custom cookie, accessible across your entire website, intended for transmission exclusively with cross-site requests and over secure, encrypted connections (HTTPS). Additionally, the cookie is configured to expire after one year.

In summary, these custom JavaScript functions, when integrated into GTM, enhance e-commerce and product tracking capabilities. They enable dynamic and precise tracking of product data, total revenue, and quantity. For new users, mastering these functions is a valuable asset in ensuring data accuracy and extracting meaningful insights from website analytics. So, embrace the power of GTM to streamline your e-commerce tracking and take your analytics to the next level.

Need help with your GTM? Feel free to reach out !


bottom of page