Google Analytics

Integrates Google Analytics tracking with Drupal by automatically adding gtag.js JavaScript tracking code to every page.

google_analytics
150,122 sites
143
drupal.org

Install

Drupal 11, 10, 9, 8 v4.0.3
composer require 'drupal/google_analytics:^4.0'

Overview

The Google Analytics module adds comprehensive web statistics tracking to your Drupal website by integrating with Google Analytics (GA4 and Universal Analytics). It automatically adds the required JavaScript tracking code to every page, enabling detailed traffic analysis, user behavior tracking, and marketing effectiveness measurement.

The module supports multiple Google Analytics accounts (GA4 G- properties, Universal Analytics UA-, Google Ads AW-, and DoubleClick DC- tags) with configurable visibility settings based on pages, user roles, and individual user preferences. It provides extensive tracking options including outbound links, mailto/tel links, file downloads, URL fragments, internal site search, and Drupal status messages.

Advanced features include custom dimensions and metrics support with token integration, cross-domain tracking, local JavaScript caching for improved performance, user ID tracking with privacy-compliant hashing, and an event-driven architecture allowing other modules to extend tracking functionality.

Features

  • Multiple Google Analytics account support (GA4 G-, Universal Analytics UA-, Google Ads AW-, DoubleClick DC-) with drag-and-drop ordering
  • Page-based tracking visibility with path patterns and wildcards to include or exclude specific pages
  • Role-based tracking control to track or exclude specific user roles
  • Per-user opt-in/opt-out tracking preferences on their account page
  • Outbound link click tracking to external websites
  • Mailto and telephone (tel:) link click tracking
  • File download tracking with configurable file extensions (50+ default extensions)
  • URL fragment tracking as separate pageviews for single-page applications
  • Colorbox modal dialog content tracking integration
  • Enhanced link attribution support for In-Page Analytics
  • Internal site search tracking with result count reporting
  • Drupal status, warning, and error message tracking as events
  • Custom dimensions and metrics with Drupal token support
  • Custom JavaScript code snippets (before and after gtag config)
  • Cross-domain tracking for multiple top-level domains
  • Privacy-compliant IP anonymization (for Universal Analytics)
  • Local JavaScript caching with daily automatic updates
  • User ID tracking with cryptographic hashing for privacy compliance
  • AdSense ad tracking integration
  • Display advertising features (Remarketing, Demographics, Interest Reporting)
  • Translation set tracking as single units
  • Debug mode with verbose console logging
  • Migration support from Drupal 6 and 7
  • Event-driven architecture for extensibility by other modules

Use Cases

Basic Website Traffic Analysis

Install the module, enter your GA4 property ID (G-xxxxxxxx), and immediately start collecting visitor data. The default configuration tracks all pages except admin paths, with IP anonymization enabled for privacy compliance. View traffic sources, user behavior, and page popularity in Google Analytics.

E-commerce Download Tracking

Enable file download tracking to monitor which documents, PDFs, software, or media files users download. The extensive default file extension list covers most common file types. Customize the extension list for your specific needs. Downloads appear as events in Google Analytics with the file extension as the event action.

Multi-site or Multi-brand Tracking

Add multiple Google Analytics property IDs to track the same site in different GA accounts. Useful for agencies managing client sites, organizations with multiple departments, or tracking in both GA4 and Universal Analytics simultaneously. Drag-and-drop to reorder accounts.

Marketing Campaign Analysis

Track outbound link clicks to see which external resources users visit. Monitor mailto: and tel: clicks to measure contact form alternatives. Enable display advertising features for remarketing campaigns and demographic/interest reporting.

User Segmentation with Custom Dimensions

Create custom dimensions in Google Analytics, then configure them in Drupal with token values like [current-user:role-names] to segment visitors by role, or use node tokens to segment by content attributes. Privacy-compliant token validation prevents accidental PII exposure.

Single-Page Application Tracking

Enable URL fragment tracking for sites using hash-based routing. Each hash change registers as a separate pageview, providing accurate page-level analytics for JavaScript-heavy applications and anchor-based navigation.

Form Usability Analysis

Enable message tracking to capture Drupal status, warning, and error messages as GA events. Identify which forms generate validation errors, which processes show warnings, and overall user experience issues through your analytics dashboard.

Cross-Domain Tracking

For organizations with multiple related domains (example.com, shop.example.com, app.example.com), configure cross-domain tracking to treat visitors as single users across all properties. Enter all domains in the cross-domains list and select 'Multiple top-level domains' mode.

GDPR/Privacy Compliant Tracking

The module installs with privacy-friendly defaults: IP anonymization enabled, authenticated users granted opt-out permission, and PII-containing tokens blocked from custom dimensions. Users can control their tracking preference on their profile page.

Performance Optimization with Local Caching

After confirming tracking works correctly, enable local JavaScript caching to serve gtag.js from your server instead of Google's CDN. The file updates automatically daily via cron, reducing external requests and improving page load times.

Tips

  • Test your tracking setup using Google Analytics Real-Time reports before going live
  • Use debug mode during development to see detailed tracking information in the browser console
  • The default excluded paths (/admin/*, /batch, etc.) prevent tracking of admin activity that could skew analytics
  • When using custom dimensions, always set up the dimension in Google Analytics first, then configure it in Drupal
  • For GDPR compliance, update your privacy policy when enabling display advertising features
  • Local JavaScript caching improves performance but should only be enabled after confirming tracking works
  • User ID tracking uses a one-way hash - the actual Drupal user ID is never sent to Google
  • Multiple GA accounts can be used to track in both GA4 and Universal Analytics during migration
  • The module automatically tracks 403 and 404 error pages regardless of visibility settings for error monitoring

Technical Details

Admin Pages 1
Google Analytics /admin/config/services/google-analytics

Configure all Google Analytics tracking behavior including account IDs, visibility settings, link tracking, custom dimensions/metrics, and advanced JavaScript options.

Permissions 4
Administer Google Analytics

Perform maintenance tasks for Google Analytics including configuring all module settings.

Opt-in or out of tracking

Allow users to decide if tracking code will be added to pages or not. Users can configure this on their account page.

Use PHP for tracking visibility

Enter PHP code in the field for tracking visibility settings. Restricted access - deprecated feature.

Add JavaScript snippets

Enter JavaScript code snippets for advanced Google Analytics functionality. Restricted access for security.

Hooks 6
hook_page_attachments

Main hook that adds the Google Analytics tracking code to every page. Checks visibility, loads accounts, dispatches events, and attaches the JavaScript.

hook_form_user_form_alter

Adds Google Analytics opt-in/opt-out checkbox to user profile forms when the user has the appropriate permission.

hook_cron

Regenerates the locally cached tracking code file daily when caching is enabled.

hook_preprocess_item_list__search_results

Collects and adds the number of search results to the page for site search tracking.

hook_entity_extra_field_info

Defines the Google Analytics settings pseudo-field on user entity forms.

hook_help

Provides help text and documentation links for the module.

Troubleshooting 10
Tracking code not appearing on pages

Verify a valid Web Property ID is configured. Check page visibility settings - by default, admin pages are excluded. Ensure the current user's role is not excluded. Clear Drupal caches after configuration changes.

Status report shows 'Google Analytics module has not been configured'

Navigate to /admin/config/services/google-analytics and enter a valid Google Analytics Web Property ID in the format UA-xxxxx-yy or G-xxxxxxxx.

Debug mode warning in status report

Debug mode loads a larger JavaScript file and should only be used during development. Disable it at /admin/config/services/google-analytics under Advanced settings before going to production.

Custom dimensions not appearing in Google Analytics

Custom dimensions must first be created in the Google Analytics Management Interface before they can be used in Drupal. Ensure the index numbers match between GA and your Drupal configuration.

Downloads not being tracked

Verify the file extension is included in the file extensions list. Extensions are case-insensitive and support regex. Check that file download tracking is enabled.

Colorbox tracking not working

The Colorbox module must be installed and enabled for this feature to work. The checkbox is disabled when Colorbox is not available.

Site search tracking not working

The Search module must be enabled. Additionally, configure your Google Analytics property to use 'search' as the query parameter in the View Settings.

Cross-domain tracking not working

Ensure 'Multiple top-level domains' is selected as the domain mode and all domains are listed in the cross-domains textarea, one per line. All domains must use the same GA property ID.

Users cannot opt out of tracking

Check that users have the 'Opt-in or out of tracking' permission and that user account mode is not set to 'No customization allowed'. Users can then find the option on their account edit page.

Token validation errors for custom dimensions

Certain tokens containing personally identifiable information (usernames, emails, UIDs) are blocked to comply with Google Analytics Terms of Service Section 7. Use alternative tokens that don't expose PII.

Security Notes 7
  • Custom JavaScript snippet fields are protected by a separate permission ('Add JavaScript snippets') to prevent XSS attacks from unprivileged users
  • Tokens containing personally identifiable information (usernames, email addresses, user IDs) are automatically blocked in custom dimensions to comply with Google Analytics Terms of Service
  • User ID tracking uses HMAC-based cryptographic hashing with the site's private key, ensuring the actual user ID is never transmitted to Google
  • The 'Use PHP for tracking visibility' permission is marked as restricted and the feature is deprecated - avoid using PHP code for visibility rules
  • IP anonymization is enabled by default for privacy compliance, though GA4 anonymizes IPs automatically regardless of this setting
  • When local caching is enabled, the JavaScript file is stored in the public files directory - ensure your server is configured securely
  • Review the file extensions list if you have sensitive document types that should not be tracked