Skip to Content
How-to guidesAnalytics and consentConnect Google Tag Manager and GA4

Connect Google Tag Manager and GA4

Audience: Integrator.

Use this procedure for BrowserIntegration → GTM → GA4.

Prerequisites

  • Complete browser integration setup and consent configuration.
  • Use a published test storefront, a GTM web container, and a test GA4 measurement ID.
  • Use an account with access to configure and publish the GTM container.
  • Keep other integrations for the same GA4 property disabled. Use one Google installation per storefront document.
  • Use direct GA4 instead if you do not use GTM.

The application supplies events and consent state. The CMS script loads GTM and forwards events. CodeBanner local JavaScript runs in isolation.

1. Configure the CMS record

Create a browser integration. Select it in the target Website-Domains record. Set containerId at the start of the script below. In Required consents, select the record with key ANALYTICS_STORAGE. Include this record in the active consent configuration. Add any other Google purposes that your tags need to that configuration. Unselected or unknown purposes remain denied.

{ "name": "Storefront ecommerce" }

CMS script for GTM

Paste this source into JavaScript. It loads the container only after the visitor saves analytics consent. It forwards bus events and sends later consent changes. The script owns window.hitoGtmConsent; the GTM template below reads its current value. Keep the loader element after cleanup. This prevents duplicate container loading when the visitor grants consent again.

const containerId = 'GTM-EXAMPLE'; if (customerPrivacy.getState().consent.ANALYTICS_STORAGE !== true) { throw new Error('Analytics consent is required.'); } function googleConsent(consent) { const purposes = { analytics_storage: 'ANALYTICS_STORAGE', ad_storage: 'AD_STORAGE', ad_user_data: 'AD_USER_DATA', ad_personalization: 'AD_PERSONALIZATION', functionality_storage: 'FUNCTIONALITY_STORAGE', personalization_storage: 'PERSONALIZATION_STORAGE', security_storage: 'SECURITY_STORAGE', }; return Object.fromEntries( Object.entries(purposes).map(([purpose, key]) => [ purpose, consent[key] === true ? 'granted' : 'denied', ]) ); } window.dataLayer ??= []; function updateConsent(state) { window.hitoGtmConsent = googleConsent(state.consent); window.dataLayer.push({ event: 'hito_consent_changed' }); } updateConsent(customerPrivacy.getState()); customerPrivacy.subscribe(updateConsent); runtime.onDispose(() => updateConsent({ consent: {} })); const scriptId = 'hito-gtm-' + containerId; if (!document.getElementById(scriptId)) { window.dataLayer.push({ 'gtm.start': Date.now(), 'event': 'gtm.js' }); const script = document.createElement('script'); script.id = scriptId; script.async = true; script.src = 'https://www.googletagmanager.com/gtm.js?id=' + encodeURIComponent(containerId); document.head.appendChild(script); } analytics.subscribe('all_events', (event) => { window.dataLayer.push({ event: event.name, event_id: event.id, context: event.context, data: event.data, }); });

Create a custom Tag Template in the GTM container with the code below. Add a dropdown field named operation with default and update options. Permit read access to the global variable hitoGtmConsent. Permit write access to the seven listed consent purposes. This is GTM template code, not CMS source.

const setDefaultConsentState = require('setDefaultConsentState'); const updateConsentState = require('updateConsentState'); const copyFromWindow = require('copyFromWindow'); const denied = { analytics_storage: 'denied', ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', functionality_storage: 'denied', personalization_storage: 'denied', security_storage: 'denied', }; if (data.operation === 'default') { setDefaultConsentState(denied); } updateConsentState(copyFromWindow('hitoGtmConsent') || denied); data.gtmOnSuccess();

Create two tags from this template. Run operation = default on Consent Initialization - All Pages. Run operation = update on the custom event hito_consent_changed. The initialization tag sets denied defaults. It applies the saved choice before other tags. The update tag reads the latest choice, including withdrawal. Require analytics_storage for analytics tags and the applicable advertising purposes for advertising tags.

Use GTM consent APIs for these updates. See Google’s consent mode setup  and custom template API reference .

Enable and save the CMS record on the test domain after the container setup below. Use one GTM installation. Reload the storefront after changing the container ID. Keep other integrations for the same GA4 property disabled.

The mapping reference shows the data-layer message produced by this script. Do not add a second subscription that sends the same event.

2. Configure the Google tag and GTM variables

In the GTM web container, create a Google tag for the test GA4 measurement ID, for example G-EXAMPLE. Use Initialization - All Pages. Add the configuration parameter send_page_view with the boolean value false. Disable page-view collection in the GA4 web stream’s enhanced measurement settings, including history changes. The event-bus page-view tag below sends the initial view and later route views. See Google’s Google tag setup  and manual page views .

Enable the built-in Event variable. Create these Data Layer Variable entries. Read the complete data object with Version 1. Use Version 2 for the nested context fields. See Google’s variable types .

GTM variable nameData layer variable nameVersion
DLV - Shop datadata1
DLV - Shop event idevent_id1
DLV - Shop page locationcontext.document.location.href2
DLV - Shop page titlecontext.document.title2
DLV - Shop page referrercontext.document.referrer2

Create a Lookup Table variable named Lookup - Shop GA4 event. Set its input to {{Event}}. Leave the default value unset.

Use the event-name mapping table for the lookup entries.

Create a Custom JavaScript variable named JS - Shop items:

function () { var name = {{Event}}; var data = {{DLV - Shop data}}; var lines = []; if (!data) return []; if (name === "product_viewed") { lines = [{ merchandise: data.productVariant, quantity: 1 }]; } else if ( name === "product_added_to_cart" || name === "product_removed_from_cart" ) { lines = [data.cartLine]; } else if (name === "cart_viewed") { lines = data.lines; } return lines.map(function (line) { var variant = line.merchandise; return { item_id: variant.sku || variant.id, item_name: variant.product.title, item_variant: variant.title || "", price: Number(variant.price.amount), quantity: line.quantity }; }); }

Create a Custom JavaScript variable named JS - Shop currency:

function () { var data = {{DLV - Shop data}}; if (!data) return; if ({{Event}} === "product_viewed") { return data.productVariant.price.currencyCode; } if (data.cartLine) return data.cartLine.merchandise.price.currencyCode; if (data.total) return data.total.currencyCode; if (data.lines && data.lines.length > 0) { return data.lines[0].merchandise.price.currencyCode; } }

Create a Custom JavaScript variable named JS - Shop value:

function () { var items = {{JS - Shop items}}; var value = 0; for (var i = 0; i < items.length; i++) { value += items[i].price * items[i].quantity; } return Math.round(value * 100) / 100; }

Use the value and quantity rules when you adapt these variables.

3. Create the event tags

Create a Custom Event trigger named Shop ecommerce. Enable regular expression matching and enter:

^(product_viewed|product_added_to_cart|product_removed_from_cart|cart_viewed)$

Use Some Custom Events. Add the condition {{JS - Shop currency}} does not equal undefined. This excludes an empty cart with no currency in its snapshot. The event-name expression limits the trigger to the four listed names. See Google’s custom event triggers .

Create a Google Analytics: GA4 Event tag named GA4 - Shop ecommerce. Use the same measurement ID as the Google tag. Set Event Name to {{Lookup - Shop GA4 event}}. Attach Shop ecommerce. Add these event parameters directly. Do not enable automatic ecommerce data from an ecommerce data-layer key. The CMS script sends its payload under data.

Event parameterGTM value
event_id{{DLV - Shop event id}}
page_location{{DLV - Shop page location}}
page_title{{DLV - Shop page title}}
page_referrer{{DLV - Shop page referrer}}
currency{{JS - Shop currency}}
value{{JS - Shop value}}
items{{JS - Shop items}}

Create another Custom Event trigger for the exact name page_viewed. Create a second GA4 Event tag with Event Name page_view. Use the same measurement ID and the first four parameters from the table. Attach only that trigger. Do not attach click, history, or All Pages triggers to either event tag. See Google’s GA4 event tag setup .

Keep items as an array. Do not convert it to a JSON string. Remove duplicate tags and installations, including when you pass event_id.

4. Verify and publish

  1. Open GTM Preview and connect Tag Assistant to the published test storefront. The CMS event check uses simulated events and validates syntax. It does not execute source or call GTM or GA4.
  2. Start with analytics consent denied. Confirm that the CMS script does not load GTM. Grant analytics consent and confirm that it loads once. Inspect the container’s consent state. The analytics grant must not grant advertising consent.
  3. View a product. Add two units, remove one unit, and open the cart. Examine data-layer messages, mapped names, numeric values, and item arrays in Tag Assistant. Repeat with a product that has no SKU. Make sure the event uses its variant ID. A failed cart action must not produce an action event.
  4. Navigate between pages without a full reload. Confirm one page_view per application page view. A cart refresh must not send another add_to_cart.
  5. Use Tag Assistant debug mode. Examine the events in GA4 DebugView. If needed, add the debug_mode event parameter with boolean value true to both GA4 event tags for the test. Remove this parameter before production. See Google’s DebugView setup .
  6. Withdraw analytics consent. Confirm that the CMS script stops forwarding bus events and that Google consent changes. Examine tags that installed their own listeners. Removing a loader element does not unload a vendor SDK. Test consent validation on tags with independent listeners. Reload when full removal is necessary.
  7. Publish the tested GTM container version. Select the integration in the production Website-Domains record. Set the container ID in the script. Enable and save the record. Confirm that only one integration sends to the production property. Record the saved CMS configuration and GTM container version with the release.

The mapping limits define unsupported checkout and collection events.

Last updated on