How to Add Google Analytics to Drupal | OpsBlu Docs

How to Add Google Analytics to Drupal

Integrate Google Analytics 4 with Drupal using the GA module, manual code, or Drupal Commerce integration.

Technical reference for implementing Google Analytics 4 (GA4) on Drupal, covering the google_analytics contributed module, Twig template injection, Drupal Behaviors JavaScript API, Drupal Commerce ecommerce tracking, and role-based exclusion configuration.

How GA4 Works on Drupal

Drupal integrates GA4 through its module and theme layer system:

  • google_analytics module (drupal/google_analytics): The primary contributed module for GA4. It stores the Measurement ID in Drupal's configuration system and injects gtag.js via hook_page_attachments(). The module handles role-based exclusions server-side by checking $account->getRoles() before attaching the script library. It also provides admin UI for configuring custom dimensions, automatic event tracking (file downloads, outbound links, mailto clicks), and privacy settings.
  • Twig template injection: For manual implementations, you edit html.html.twig in your theme to add the gtag snippet before </head>. This bypasses module-level features like role exclusions and consent mode.
  • Drupal Behaviors API: Custom event tracking should use Drupal.behaviors rather than raw DOMContentLoaded listeners. Behaviors re-attach after AJAX content loads (e.g., Views infinite scroll, form AJAX submissions), ensuring tracking persists across dynamic content updates.

Drupal Commerce integration requires an additional module (drupal/ga_ecommerce or similar) that hooks into Commerce order events (commerce_order.place.post_transition) to emit GA4 ecommerce events. Product field mapping (SKU, name, category, price) is configured in the module's admin UI and rendered as inline <script> blocks on relevant pages.

Drupal's render cache and page cache (including BigPipe) can affect script output. The google_analytics module handles cache contexts correctly via #cache metadata, but manual implementations must account for anonymous vs. authenticated page variants.

Installation Methods

The Google Analytics module is the most comprehensive solution for Drupal sites.

Step 1: Install the Module

composer require drupal/google_analytics
drush en google_analytics

Or install via the Drupal admin interface:

  1. Navigate to Extend in the admin menu
  2. Click Install new module
  3. Upload or enter the module URL
  4. Click Install and then Enable

Step 2: Configure the Module

  1. Go to Configuration > System > Google Analytics
  2. Enter your GA4 Measurement ID (format: G-XXXXXXXXXX)
  3. Configure tracking options:
    • Enable page view tracking
    • Set tracking scope (all pages or specific paths)
    • Configure user role exclusions

Step 3: Advanced Settings

Configure additional tracking features:

  • Custom Dimensions: Map Drupal user properties to GA4 dimensions
  • Event Tracking: Enable automatic link tracking, file downloads, and outbound clicks
  • Enhanced Link Attribution: Track multiple links to the same URL
  • User ID Tracking: Track authenticated users across devices

Method 2: Manual Implementation

For sites without module support or requiring custom implementation:

  1. Navigate to Configuration > Development > Performance
  2. Add GA4 tracking code to your theme's html.html.twig file
  3. Insert before the closing </head> tag:
<!-- Google tag (gtag.js) -->
<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');
</script>

Configuration Options

Configure cookie consent integration:

  1. Install a cookie consent module (e.g., EU Cookie Compliance)
  2. In Google Analytics settings, enable Respect Do Not Track
  3. Configure consent mode parameters:
    • analytics_storage
    • ad_storage
    • wait_for_update

User Role Exclusions

Exclude specific roles from tracking:

  1. Go to Google Analytics settings > User roles
  2. Check roles to exclude (typically Administrator, Editor)
  3. Save configuration

Custom Tracking

Add custom tracking parameters in the module's Custom Code section:

gtag('set', 'user_properties', {
  'drupal_role': 'authenticated',
  'content_type': 'article'
});

Event Tracking

Automatic Events

The Google Analytics module automatically tracks:

  • File Downloads: PDF, DOC, ZIP files
  • Outbound Links: External website clicks
  • Email Links: mailto: link clicks

Enable in Configuration > Google Analytics > Event Tracking

Custom Event Implementation

For custom events, use the JavaScript API in your theme or custom module:

// Track form submission
jQuery('#contact-form').on('submit', function() {
  gtag('event', 'form_submit', {
    'form_name': 'contact_form',
    'form_destination': '/thank-you'
  });
});

// Track custom interactions
gtag('event', 'video_play', {
  'video_title': 'Product Demo',
  'video_duration': 120
});

Drupal Behaviors for Event Tracking

Use Drupal's JavaScript API for better integration:

(function ($, Drupal) {
  Drupal.behaviors.customGATracking = {
    attach: function (context, settings) {
      $('.cta-button', context).once('ga-tracking').on('click', function() {
        gtag('event', 'cta_click', {
          'button_text': $(this).text(),
          'button_location': 'sidebar'
        });
      });
    }
  };
})(jQuery, Drupal);

Ecommerce Tracking

Drupal Commerce Integration

For Drupal Commerce sites, install the GA4 Ecommerce module:

composer require drupal/ga_ecommerce
drush en ga_ecommerce

Configure Ecommerce Events

  1. Navigate to Commerce > Configuration > Google Analytics Ecommerce
  2. Enable enhanced ecommerce tracking
  3. Map product fields to GA4 parameters:
    • Product ID
    • Product Name
    • Product Category
    • Price
    • Currency

Tracked Events

Automatically tracked ecommerce events:

  • view_item - Product page views
  • add_to_cart - Add to cart actions
  • begin_checkout - Checkout initiation
  • purchase - Completed transactions
  • refund - Order refunds

Troubleshooting

Tracking Code Not Firing

Issue: GA4 tag not appearing in page source

Solutions:

  1. Clear Drupal cache: drush cr
  2. Verify module is enabled: drush pml | grep google_analytics
  3. Check permission settings for anonymous users
  4. Disable caching in development: Configuration > Performance

Duplicate Tracking

Issue: Events tracked multiple times

Solutions:

  1. Check for multiple GA4 installations (module + theme)
  2. Review custom theme templates for hardcoded tracking
  3. Disable GA4 in Google Tag Manager if also using the module

User ID Not Tracking

Issue: Cross-device tracking not working

Solutions:

  1. Verify User ID tracking is enabled in module settings
  2. Ensure users are authenticated before tracking
  3. Check privacy settings don't block user identification
  4. Verify GA4 property has User-ID reporting enabled

Ecommerce Data Not Appearing

Issue: Purchase events not showing in GA4

Solutions:

  1. Verify GA4 Ecommerce module is properly configured
  2. Check currency code matches GA4 property settings
  3. Test with GA4 DebugView in real-time
  4. Ensure order confirmation page triggers purchase event
  5. Verify product data structure matches GA4 requirements

Performance Issues

Issue: Slow page loads after GA4 installation

Solutions:

  1. Enable asynchronous loading in module settings
  2. Use Google Tag Manager instead for better performance
  3. Implement lazy loading for below-fold content
  4. Configure Drupal's aggregate JavaScript setting
  5. Use a CDN for analytics script delivery

Verification

After installation, verify tracking is working:

  1. Real-Time Reports: Check GA4 Real-time reports for active users
  2. GA4 DebugView: Enable debug mode with browser extension
  3. Browser Console: Look for gtag commands in developer tools
  4. Tag Assistant: Use Google Tag Assistant Chrome extension

Enable Debug Mode

Add to your settings:

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