Google Analytics 4 Setup for Magento | Blue Frog Docs

Google Analytics 4 Setup for Magento

Complete guide to implementing Google Analytics 4 on Magento 2 and Adobe Commerce, including native integration, extensions, and manual implementation methods.

Google Analytics 4 Setup for Magento

Implement Google Analytics 4 (GA4) on your Magento 2 or Adobe Commerce store to track user behavior, eCommerce transactions, and conversion data. This guide covers multiple implementation methods, from native Adobe Commerce features to custom integrations.


Implementation Methods

Adobe Commerce includes built-in Google Analytics support.

Enable Google Analytics

  1. Navigate to Admin Panel:

    Stores > Configuration > Sales > Google API > Google Analytics
    
  2. Configure Settings:

    • Enable: Yes
    • Account Type: Google Analytics 4
    • Measurement ID: Enter your GA4 Measurement ID (format: G-XXXXXXXXXX)
    • Enable Content Experiments: Yes/No (for A/B testing)
    • Anonymize IP: Yes (recommended for GDPR compliance)
  3. Save Configuration:

    php bin/magento cache:flush
    

Limitations

  • Basic pageview tracking only
  • Limited eCommerce event customization
  • May require additional configuration for enhanced eCommerce

Method 2: Magento Marketplace Extensions

Several high-quality extensions provide advanced GA4 integration.

1. Google Tag Manager & GA4 by Mageplaza

  • Features: Full GA4 + GTM integration, enhanced eCommerce, server-side tracking
  • Installation:
    composer require mageplaza/module-google-tag-manager
    php bin/magento setup:upgrade
    php bin/magento setup:di:compile
    php bin/magento setup:static-content:deploy
    php bin/magento cache:flush
    

2. Google Analytics 4 by Amasty

  • Features: Advanced event tracking, custom dimensions, user properties
  • Installation: Via Magento Marketplace or Composer

3. Google Analytics 4 Pro by MageWorx

  • Features: Enhanced eCommerce, server-side tracking, consent mode
  • Installation: Via Magento Marketplace

Extension Configuration

After installation, configure via:

Stores > Configuration > [Vendor] > Google Analytics

Method 3: Manual Implementation via Layout XML

For complete control, implement GA4 manually using Magento's layout system.

Step 1: Create Custom Module

Directory Structure:

app/code/YourCompany/Analytics/
├── etc/
│   ├── module.xml
│   └── frontend/
│       └── di.xml
├── Block/
│   └── Ga4.php
├── view/frontend/
│   ├── layout/
│   │   └── default.xml
│   └── templates/
│       └── ga4.phtml
└── registration.php

Step 2: Module Registration

File: app/code/YourCompany/Analytics/registration.php

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'YourCompany_Analytics',
    __DIR__
);

Step 3: Module Configuration

File: app/code/YourCompany/Analytics/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="YourCompany_Analytics" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Theme"/>
        </sequence>
    </module>
</config>

Step 4: Create Block Class

File: app/code/YourCompany/Analytics/Block/Ga4.php

<?php
namespace YourCompany\Analytics\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Ga4 extends Template
{
    protected $scopeConfig;

    public function __construct(
        Context $context,
        ScopeConfigInterface $scopeConfig,
        array $data = []
    ) {
        $this->scopeConfig = $scopeConfig;
        parent::__construct($context, $data);
    }

    public function getMeasurementId()
    {
        return $this->scopeConfig->getValue(
            'google/analytics/measurement_id',
            ScopeInterface::SCOPE_STORE
        );
    }

    public function isEnabled()
    {
        return $this->scopeConfig->isSetFlag(
            'google/analytics/active',
            ScopeInterface::SCOPE_STORE
        );
    }

    public function shouldAnonymizeIp()
    {
        return $this->scopeConfig->isSetFlag(
            'google/analytics/anonymize_ip',
            ScopeInterface::SCOPE_STORE
        );
    }
}

Step 5: Create Layout XML

File: app/code/YourCompany/Analytics/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <block class="YourCompany\Analytics\Block\Ga4"
               name="google.analytics.ga4"
               template="YourCompany_Analytics::ga4.phtml"
               before="-"/>
    </head>
</page>

Step 6: Create Template

File: app/code/YourCompany/Analytics/view/frontend/templates/ga4.phtml

<?php
/** @var \YourCompany\Analytics\Block\Ga4 $block */
if (!$block->isEnabled() || !$block->getMeasurementId()):
    return;
endif;

$measurementId = $block->escapeHtml($block->getMeasurementId());
$anonymizeIp = $block->shouldAnonymizeIp() ? 'true' : 'false';
?>

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?= $measurementId ?>"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', '<?= $measurementId ?>', {
        'anonymize_ip': <?= $anonymizeIp ?>,
        'send_page_view': true,
        'cookie_flags': 'SameSite=None;Secure'
    });

    // Enhanced eCommerce - Pageview tracking
    require(['jquery', 'Magento_Customer/js/customer-data'], function($, customerData) {
        var cart = customerData.get('cart');

        // Track cart data on page load
        cart.subscribe(function(cartData) {
            if (cartData.items && cartData.items.length > 0) {
                gtag('event', 'view_cart', {
                    currency: cartData.subtotal_currency_code || 'USD',
                    value: parseFloat(cartData.subtotal) || 0,
                    items: cartData.items.map(function(item) {
                        return {
                            item_id: item.product_sku,
                            item_name: item.product_name,
                            price: parseFloat(item.product_price_value),
                            quantity: parseInt(item.qty)
                        };
                    })
                });
            }
        });
    });
</script>

Step 7: Enable Module

php bin/magento module:enable YourCompany_Analytics
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush

Method 4: Admin Panel HTML Head Injection

For quick testing or simple implementations without module development.

Steps:

  1. Navigate to:

    Content > Design > Configuration
    
  2. Select Store View and click Edit

  3. Expand HTML Head Section

  4. Add GA4 Code to Scripts and Style Sheets:

    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'G-XXXXXXXXXX', {
        'anonymize_ip': true,
        'cookie_flags': 'SameSite=None;Secure'
      });
    </script>
    
  5. Save Configuration

  6. Flush Cache:

    php bin/magento cache:flush
    

Limitations:

  • No dynamic data integration
  • Manual updates required
  • Limited access to Magento data layer

Configuration Options

Basic GA4 Configuration

gtag('config', 'G-XXXXXXXXXX', {
    // Privacy & Compliance
    'anonymize_ip': true,
    'allow_google_signals': false,
    'allow_ad_personalization_signals': false,

    // Cookie Configuration
    'cookie_domain': 'auto',
    'cookie_expires': 63072000, // 2 years in seconds
    'cookie_prefix': 'ga',
    'cookie_update': true,
    'cookie_flags': 'SameSite=None;Secure',

    // Page View
    'send_page_view': true,
    'page_title': document.title,
    'page_location': window.location.href,

    // Custom Dimensions (requires GA4 setup)
    'user_id': customerData.id || null, // Only for logged-in users
    'customer_group': customerData.group_id || 'guest',
    'store_view': 'default'
});

User Properties (Logged-in Customers)

require(['Magento_Customer/js/customer-data'], function(customerData) {
    var customer = customerData.get('customer');

    if (customer().firstname) {
        gtag('set', 'user_properties', {
            'customer_group': customer().group_id,
            'customer_lifetime_value': customer().lifetime_value || 0,
            'is_subscribed': customer().is_subscribed ? 'yes' : 'no'
        });
    }
});

Full Page Cache Considerations

Magento's Full Page Cache (FPC) and Varnish can impact analytics tracking.

Private Content Sections

Use Magento's customer sections for dynamic data:

File: etc/frontend/sections.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer/etc/sections.xsd">
    <action name="catalog/product/view">
        <section name="analytics"/>
    </action>
    <action name="checkout/cart/add">
        <section name="analytics"/>
    </action>
</config>

ESI Tags with Varnish

For Varnish users, mark analytics blocks as ESI:

<block class="YourCompany\Analytics\Block\Ga4"
       name="google.analytics.ga4"
       template="YourCompany_Analytics::ga4.phtml">
    <arguments>
        <argument name="ttl" xsi:type="number">0</argument>
    </arguments>
</block>

Testing & Validation

1. Google Tag Assistant

2. GA4 DebugView

Enable debug mode:

gtag('config', 'G-XXXXXXXXXX', {
    'debug_mode': true
});

View real-time events in GA4:

Admin > Configure > DebugView

3. Network Tab Verification

Open Chrome DevTools > Network tab:

  • Filter by google-analytics.com or collect
  • Verify requests contain correct tid (Tracking ID) and event parameters

4. Magento Logging

Add custom logging for debugging:

$this->logger->info('GA4 Event Fired', [
    'event_name' => 'purchase',
    'transaction_id' => $orderId,
    'value' => $orderTotal
]);

Performance Optimization

1. Async Script Loading

Always load GA4 asynchronously:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>

2. DNS Prefetch

Add to layout XML <head>:

<link rel="dns-prefetch" href="//www.google-analytics.com"/>
<link rel="dns-prefetch" href="//www.googletagmanager.com"/>

3. RequireJS Integration

Load analytics as RequireJS module for better dependency management:

File: view/frontend/requirejs-config.js

var config = {
    paths: {
        'gtag': 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX'
    },
    shim: {
        'gtag': {
            exports: 'gtag'
        }
    }
};

Enable Magento's cookie restriction:

Stores > Configuration > General > Web > Default Cookie Settings
  • Cookie Lifetime: 3600 (seconds)
  • Cookie Path: /
  • Cookie Domain: (leave empty for auto)
  • Use HTTP Only: No
  • Cookie Restriction Mode: Yes

Implement consent-based tracking:

require(['jquery', 'mage/cookies'], function($) {
    // Check if user accepted cookies
    if ($.mage.cookies.get('user_allowed_save_cookie')) {
        // Initialize GA4
        gtag('config', 'G-XXXXXXXXXX');
    } else {
        // Wait for consent
        window.addEventListener('user-allowed-save-cookie', function() {
            gtag('config', 'G-XXXXXXXXXX');
        });
    }
});
// Set default consent state
gtag('consent', 'default', {
    'analytics_storage': 'denied',
    'ad_storage': 'denied',
    'wait_for_update': 500
});

// Update consent when user accepts
function grantConsent() {
    gtag('consent', 'update', {
        'analytics_storage': 'granted',
        'ad_storage': 'granted'
    });
}

Troubleshooting

Tags Not Firing

Issue: GA4 tags don't appear in Tag Assistant

Solutions:

  1. Check Measurement ID format (G-XXXXXXXXXX)
  2. Verify cache is cleared: php bin/magento cache:flush
  3. Disable Full Page Cache temporarily for testing
  4. Check browser console for JavaScript errors

Duplicate Tracking

Issue: Multiple pageviews recorded

Solutions:

  1. Ensure only one GA4 implementation method is active
  2. Check for duplicate script tags in HTML source
  3. Verify extensions aren't conflicting

No Data in GA4

Issue: No data appears in GA4 reports

Solutions:

  1. Wait 24-48 hours for data processing
  2. Use DebugView for real-time validation
  3. Verify Measurement ID in GA4 Admin > Data Streams
  4. Check data filters and IP exclusions in GA4

Next Steps


Additional Resources

// SYS.FOOTER