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_analyticsmodule (drupal/google_analytics): The primary contributed module for GA4. It stores the Measurement ID in Drupal's configuration system and injectsgtag.jsviahook_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.twigin 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.behaviorsrather than rawDOMContentLoadedlisteners. 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
Method 1: Using the Google Analytics Module (Recommended)
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:
- Navigate to Extend in the admin menu
- Click Install new module
- Upload or enter the module URL
- Click Install and then Enable
Step 2: Configure the Module
- Go to Configuration > System > Google Analytics
- Enter your GA4 Measurement ID (format: G-XXXXXXXXXX)
- 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:
- Navigate to Configuration > Development > Performance
- Add GA4 tracking code to your theme's
html.html.twigfile - 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
Privacy and Consent
Configure cookie consent integration:
- Install a cookie consent module (e.g., EU Cookie Compliance)
- In Google Analytics settings, enable Respect Do Not Track
- Configure consent mode parameters:
analytics_storagead_storagewait_for_update
User Role Exclusions
Exclude specific roles from tracking:
- Go to Google Analytics settings > User roles
- Check roles to exclude (typically Administrator, Editor)
- 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
- Navigate to Commerce > Configuration > Google Analytics Ecommerce
- Enable enhanced ecommerce tracking
- Map product fields to GA4 parameters:
- Product ID
- Product Name
- Product Category
- Price
- Currency
Tracked Events
Automatically tracked ecommerce events:
view_item- Product page viewsadd_to_cart- Add to cart actionsbegin_checkout- Checkout initiationpurchase- Completed transactionsrefund- Order refunds
Troubleshooting
Tracking Code Not Firing
Issue: GA4 tag not appearing in page source
Solutions:
- Clear Drupal cache:
drush cr - Verify module is enabled:
drush pml | grep google_analytics - Check permission settings for anonymous users
- Disable caching in development: Configuration > Performance
Duplicate Tracking
Issue: Events tracked multiple times
Solutions:
- Check for multiple GA4 installations (module + theme)
- Review custom theme templates for hardcoded tracking
- Disable GA4 in Google Tag Manager if also using the module
User ID Not Tracking
Issue: Cross-device tracking not working
Solutions:
- Verify User ID tracking is enabled in module settings
- Ensure users are authenticated before tracking
- Check privacy settings don't block user identification
- Verify GA4 property has User-ID reporting enabled
Ecommerce Data Not Appearing
Issue: Purchase events not showing in GA4
Solutions:
- Verify GA4 Ecommerce module is properly configured
- Check currency code matches GA4 property settings
- Test with GA4 DebugView in real-time
- Ensure order confirmation page triggers purchase event
- Verify product data structure matches GA4 requirements
Performance Issues
Issue: Slow page loads after GA4 installation
Solutions:
- Enable asynchronous loading in module settings
- Use Google Tag Manager instead for better performance
- Implement lazy loading for below-fold content
- Configure Drupal's aggregate JavaScript setting
- Use a CDN for analytics script delivery
Verification
After installation, verify tracking is working:
- Real-Time Reports: Check GA4 Real-time reports for active users
- GA4 DebugView: Enable debug mode with browser extension
- Browser Console: Look for
gtagcommands in developer tools - Tag Assistant: Use Google Tag Assistant Chrome extension
Enable Debug Mode
Add to your settings:
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});