Install Google Analytics 4 on Shopware | OpsBlu Docs

Install Google Analytics 4 on Shopware

How to install GA4 on Shopware 6 using plugins, theme templates, or Google Tag Manager.

There are three main methods to install GA4 on your Shopware store, each with different capabilities and complexity levels.

Method Comparison

Method Difficulty Customization Updates Recommended For
Plugin (Shopware Store) Easy Medium Automatic Quick setup, non-technical users
Manual Theme Implementation Medium High Manual Developers, custom requirements
Google Tag Manager Medium Very High Flexible Most stores (recommended)

Method 1: Plugin Installation (Easiest)

Shopware Store offers several GA4 plugins with varying features.

  1. Google Analytics 4 Integration (Official/Popular Options)
  2. Enhanced Ecommerce for GA4
  3. Advanced Analytics Suite

Installation Steps

  1. Find Plugin in Shopware Store

    • Log into Shopware Administration
    • Go to ExtensionsMy extensionsExtension Store
    • Search for "Google Analytics 4" or "GA4"
    • Review features, pricing, and ratings
  2. Install Plugin

    • Click on your chosen plugin
    • Click Add extension or Buy now (if paid)
    • Click Install
    • Wait for installation to complete
  3. Configure Plugin

    • Go to ExtensionsMy extensionsInstalled
    • Find the GA4 plugin and click Configure
    • Enter your GA4 Measurement ID (format: G-XXXXXXXXXX)
    • Configure additional settings:
      • Enable ecommerce tracking
      • Set currency settings
      • Configure user ID tracking (if desired)
      • Enable enhanced ecommerce events
  4. Assign to Sales Channel

    • Some plugins require assignment to specific sales channels
    • Go to Sales Channels → Select your channel
    • Check plugin is enabled for this channel
  5. Clear Cache

    bin/console cache:clear
    

    Or in Administration: SettingsSystemCaches & indexesClear cache

What Gets Tracked (Typical Plugin)

Standard Events:

  • Page views
  • Product views
  • Product list views
  • Add to cart
  • Remove from cart
  • Begin checkout
  • Purchase events
  • Search events

Enhanced Features (Plugin-Dependent):

  • User ID tracking
  • Enhanced ecommerce
  • Custom dimensions
  • Promotions tracking
  • Checkout step tracking

Plugin Limitations

  • Cannot customize tracking code or add custom event parameters without editing plugin source
  • Dependent on plugin updates
  • May have licensing costs
  • Different plugins offer different features
  • Potential performance impact

Method 2: Manual Theme Implementation

Add GA4 directly to your Shopware theme for complete control.

Prerequisites

  • Access to theme files (FTP/SFTP or local development)
  • Basic understanding of Twig templating
  • Familiarity with Shopware 6 theme structure

Setup Steps

1. Locate Base Template

Find your theme's base template:

/custom/plugins/YourTheme/src/Resources/views/storefront/base.html.twig

Or if extending default theme:

/custom/plugins/YourTheme/src/Resources/views/storefront/layout/meta.html.twig

2. Add GA4 gtag.js Script

Create or extend the layout_head_javascript_tracking block:

{% sw_extends '@Storefront/storefront/base.html.twig' %}

{% block layout_head_javascript_tracking %}
    {{ parent() }}

    <!-- Google Analytics 4 -->
    <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', {
            'send_page_view': true,
            'currency': '{{ context.currency.isoCode }}',
            {% if context.customer %}
            'user_id': '{{ context.customer.id }}',
            {% endif %}
            'user_properties': {
                'customer_group': '{{ context.customer.group.translated.name ?? "Guest" }}'
            }
        });
    </script>
{% endblock %}

Replace G-XXXXXXXXXX with your GA4 Measurement ID.

Respect GDPR by checking cookie consent:

{% block layout_head_javascript_tracking %}
    {{ parent() }}

    <script>
        // Initialize gtag function
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}

        // Check cookie consent
        const cookiePreference = getCookie('cookie-preference');

        if (cookiePreference === 'all' || cookiePreference === '1') {
            // Load GA4 if consent given
            (function() {
                var script = document.createElement('script');
                script.async = true;
                script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
                document.head.appendChild(script);
            })();

            gtag('js', new Date());
            gtag('config', 'G-XXXXXXXXXX', {
                'send_page_view': true,
                'currency': '{{ context.currency.isoCode }}'
            });
        } else {
            // Set default consent to denied
            gtag('consent', 'default', {
                'analytics_storage': 'denied',
                'ad_storage': 'denied'
            });
        }

        // Helper function to get cookie
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        // Listen for consent changes
        document.addEventListener('cookie-preference-updated', function(event) {
            if (event.detail.all || event.detail.analytics) {
                gtag('consent', 'update', {
                    'analytics_storage': 'granted'
                });
            }
        });
    </script>
{% endblock %}

4. Clear Cache and Compile Theme

# Clear cache
bin/console cache:clear

# Compile theme
bin/console theme:compile

# Or in one command
bin/console cache:clear && bin/console theme:compile

5. Test Installation

  • Visit your storefront
  • Open browser DevTools → Network tab
  • Look for requests to google-analytics.com or analytics.google.com
  • Check GA4 Realtime report for active users

Advanced Configuration

Multi-Language Support

gtag('config', 'G-XXXXXXXXXX', {
    'send_page_view': true,
    'language': '{{ context.salesChannel.language.locale.code }}',
    'currency': '{{ context.currency.isoCode }}',
    'country': '{{ context.salesChannel.country.iso }}'
});

Multi-Domain Tracking

For multiple sales channels with different domains:

{% if context.salesChannel.id == 'sales-channel-id-1' %}
    {% set gaId = 'G-XXXXXXXXX1' %}
{% elseif context.salesChannel.id == 'sales-channel-id-2' %}
    {% set gaId = 'G-XXXXXXXXX2' %}
{% else %}
    {% set gaId = 'G-XXXXXXXXXDEFAULT' %}
{% endif %}

gtag('config', '{{ gaId }}', {
    'linker': {
        'domains': ['domain1.com', 'domain2.com']
    }
});

GTM provides the most flexibility and is recommended for most stores.

Why Use GTM?

  • Easier to manage: Update tracking without editing theme files
  • Better organization: All tags in one place
  • Advanced features: Custom events, triggers, variables
  • Better performance: Single container load
  • Non-technical updates: Marketers can manage without developers
  • Version control: Built-in versioning and rollback

Setup Overview

  1. Install GTM on Shopware

    See Install Google Tag Manager for complete GTM installation guide.

  2. Create GA4 Configuration Tag

    Once GTM is installed:

    a. In GTM, go to TagsNew

    b. Click Tag ConfigurationGoogle Analytics: GA4 Configuration

    c. Enter your Measurement ID (G-XXXXXXXXXX)

    d. Configuration Settings:

    Fields to Set:
    - currency: {{Currency Code}}
    - user_id: {{Customer ID}} (if logged in)
    

    e. Triggering: Select All Pages

    f. Save and name it "GA4 - Configuration"

  3. Create GTM Variables

    Create variables for Shopware data:

    • Data Layer Variable: customerGroup
    • Data Layer Variable: currencyCode
    • Data Layer Variable: customerId
    • JavaScript Variable: salesChannelId
  4. Configure User Properties

    Add user properties to understand your audience:

    User Properties:
    - customer_group: {{Customer Group}}
    - language: {{Language}}
    - currency: {{Currency}}
    
  5. Publish Container

    • Click Submit in GTM
    • Add version name: "GA4 Initial Setup"
    • Add description
    • Click Publish

GTM + Shopware Integration

Shopware provides event data that GTM can access:

Verification & Testing

1. Check GA4 Realtime Reports

  • Open GA4 → ReportsRealtime
  • Navigate your store
  • Verify events appear within 30 seconds
  • Check user location, device type

2. Use GA4 DebugView

Enable debug mode for detailed event inspection:

For GTM:

  • Use GTM Preview mode
  • Events automatically appear in DebugView

For Manual Implementation:

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

In GA4:

  • Go to AdminDebugView
  • View events in real-time with full parameters
  • Verify parameter values are correct

3. Test Ecommerce Events

Test the complete purchase funnel:

  1. View homepage → check page_view
  2. View category → check view_item_list
  3. View product → check view_item
  4. Add to cart → check add_to_cart
  5. Begin checkout → check begin_checkout
  6. Purchase → check purchase event
  7. Verify transaction details → revenue, tax, shipping

4. Common Issues to Check

  • Duplicate events: Multiple GA4 implementations
  • Missing events: JavaScript errors or incorrect configuration
  • Wrong currency: Currency parameter not set correctly
  • Missing user ID: Customer ID not passed when logged in
  • Bot traffic: Filter out in GA4 data settings

Troubleshooting

Events Not Firing

See Events Not Firing Troubleshooting for detailed debugging.

Quick checks:

  • Verify Measurement ID is correct (format: G-XXXXXXXXXX)
  • Check browser console for JavaScript errors
  • Clear Shopware cache
  • Disable ad blockers for testing
  • Check cookie consent is granted
  • Verify theme compilation completed

Duplicate Events

Cause: Multiple GA4 implementations active simultaneously.

Diagnosis:

# Check theme files for GA4 code
grep -r "gtag" custom/plugins/YourTheme/
grep -r "G-" custom/plugins/YourTheme/

# Check for plugins
bin/console plugin:list | grep -i "analytic\|ga4\|google"

Fix:

  1. Choose ONE implementation method
  2. Remove or disable others
  3. Clear cache
  4. Test in Realtime reports

Cache Issues

Problem: Changes not appearing on storefront.

Solution:

# Clear all caches
bin/console cache:clear

# Warm up cache
bin/console cache:warmup

# Recompile theme
bin/console theme:compile

# Or clear HTTP cache
bin/console http:cache:clear

Plugin Conflicts

Problem: GA4 plugin conflicts with theme or other plugins.

Diagnosis:

  • Check Shopware error logs: var/log/
  • Check browser console for JavaScript errors
  • Disable plugins one by one to identify conflict

Solution:

  • Update all plugins to latest versions
  • Contact plugin developer for support
  • Switch to manual implementation if needed

Performance Considerations

Script Loading Strategy

Async Loading (Recommended):

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

Deferred Loading:

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

Delayed Loading (Advanced):

// Load GA4 after user interaction
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        // Load GA4 after 3 seconds
        var script = document.createElement('script');
        script.async = true;
        script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
        document.head.appendChild(script);
    }, 3000);
});

Monitor Performance Impact

  • Use Lighthouse to measure impact
  • Check LCP before and after
  • Monitor Time to Interactive (TTI)
  • Test on mobile devices

Next Steps

For general GA4 concepts, see Google Analytics 4 Guide.