Google Analytics for Drupal: Complete Setup and Best Practices

Google Analytics for Drupal: Complete Setup and Best Practices

Google Analytics is one of the most important tools in any SEO or marketing toolkit. But with the shift to GA4, new privacy considerations, and evolving user behavior, simply adding a tracking script to your site isn’t enough anymore. Getting real value from Google Analytics means setting it up properly, aligning it with your business goals, and knowing how to track the actions that matter most.

In this guide, we’ll show you how to install Google Analytics on your Drupal site, configure it to track leads and campaigns, and apply best practices for analyzing your data. We’ll also cover how to use GA4 to follow newsletter signups, ecommerce transactions, UTM-tagged campaigns, and more.

Whether you’re starting from scratch or reviewing an existing setup, this guide will help you turn data into decisions.


Installing Google Analytics (GA4) on a Drupal Site

Before you can analyze traffic, track conversions, or evaluate the performance of your marketing campaigns, you need to install Google Analytics on your site. GA4 uses a new event-based model, replacing the old Universal Analytics setup. This makes the initial configuration slightly different, especially for Drupal.

Here’s how to properly set up Google Analytics 4 on a Drupal website.


Step 1: Create a GA4 Property in Google Analytics

To start tracking data, you need to create a GA4 property. This is your main analytics container that will receive all user interaction data from your website.

  1. Go to analytics.google.com and sign in with a Google account.
     
  2. In the lower left menu, click Admin.
     
  3. Under the Account column, select an existing account or click Create Account if this is your first time setting up Analytics.
     
  4. Under the Property column, click Create Property.
     
  5. Give your property a name (for example, “Monarq Site – GA4”), set your reporting time zone and currency, then click Next.
     
  6. On the next screen, choose Web as your data stream type. Enter your website domain (without https://) and give the stream a name (such as “Main Website”).
     
  7. Click Create Stream. You’ll now be given a Measurement ID that looks like G-XXXXXXXXXX.

Keep this Measurement ID handy, you’ll need it to connect your Drupal site to GA4.


Step 2: Add the Measurement ID to Drupal

There are multiple ways to add Google Analytics tracking code to Drupal. The recommended method for GA4 is using the Google Tag module.


Option A: Use the Google Tag Module (Recommended for GA4)

The Google Tag module is designed to support the newer gtag.js tracking format used by GA4. It’s lightweight, stable, and directly injects the tracking script into your site’s <head>.

Install the Module:

If your project uses Composer (as most modern Drupal setups do), run the following in your terminal:

composer require drupal/google_tag

Then enable the module with Drush:

drush en google_tag -y

Alternatively, enable it through the Drupal admin interface under Extend.

Configure the Module:

  1. In the Drupal admin menu, go to Configuration > Google Tag Settings.
     
  2. Paste your GA4 Measurement ID (e.g., G-XXXXXXXXXX) into the appropriate field.
     
  3. Check the boxes to enable tracking for the desired user roles. You may want to exclude administrators or authenticated users to avoid inflating traffic numbers during site maintenance or internal testing.
     
  4. Save the configuration.

Once this is complete, GA4 will begin receiving data from your site.


Option B: Use Google Tag Manager 

If you want more advanced control, such as setting up ecommerce events, custom conversions, or running other third-party scripts, you may prefer using Google Tag Manager (GTM).

Steps to use GTM:

  1. Create an account and container at tagmanager.google.com.
     
  2. Once the container is created, you’ll receive a Container ID like GTM-XXXXXXX.
     
  3. Install the Google Tag Manager module in Drupal:
composer require drupal/google_tag_manager
drush en google_tag_manager -y

Go to Configuration > Google Tag Manager and paste in your Container ID.

  1. Configure visibility options to load the tag only for anonymous users, if needed.
     

Once GTM is installed, you can add your GA4 Measurement ID as a tag within GTM, along with other tracking tools like Facebook Pixel, LinkedIn Insight, or Hotjar, without editing Drupal’s codebase.

 

Option C: Manually Add the GA4 gtag.js in Your Theme's

If you prefer full control and minimal dependencies, you can manually insert the GA4 gtag.js tracking snippet into your Drupal theme’s template.

  1. Edit the following file in your custom theme:
/themes/custom/YOUR_THEME/templates/html.html.twig
  1. Insert the following code just 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>
  1. Replace G-XXXXXXXXXX with your actual GA4 Measurement ID.
     
  2. Clear Drupal's cache to apply changes:
drush cr

If you don’t see the tag firing, ensure your theme is active and Twig debugging is set up correctly.

Alternatively, you can use hook_preprocess_html() in a custom module to inject the code programmatically.


GA4 Best Practices 

Setting up Google Analytics is just the start. To get accurate, actionable insights from GA4, you need to configure it thoughtfully. Below are key best practices to make sure your data is clean, useful, and aligned with your goals.


1. Enable Enhanced Measurement

GA4 includes Enhanced Measurement options that automatically track common user actions. This saves time and avoids the need for custom scripts.

What it can track:

  • Scroll depth (when someone reaches 90 percent of a page)
     
  • Clicks on external links
     
  • File downloads (PDFs, DOCs, and more)
     
  • Internal search terms
     
  • Video views from embedded YouTube videos


How to turn it on:

  1. Go to the GA4 Admin panel
     
  2. Under Data Streams, select your web stream
     
  3. Look for Enhanced Measurement and make sure it is enabled
     
  4. Click the gear icon to fine-tune which events to include


Tip for Drupal:

If your internal search uses /search/node?keys=, GA4 will pick it up by default. If not, make sure your query parameter is readable.


2. Exclude Internal Traffic

Internal traffic from your team, developers, or staging environments can skew your data. By default, GA4 will treat all users equally unless you tell it otherwise.

Option A: IP-based filter

  1. In GA4, go to Admin > Data Settings > Data Filters
     
  2. Click Create Filter, select “Internal Traffic”
     
  3. Use your office or VPN IP range to define the rule
     
  4. Apply the filter to Test mode first, then move to Active

Method 2: Developer-defined parameter

If your IPs change often, push a custom parameter like user_type = internal using Google Tag Manager. Then create a data filter in GA4 based on that value.

For Drupal setups:

You can add a condition in the google_tag module config to exclude authenticated or admin users from tracking. This is a simpler alternative if most of your team is logged in.


3. Use Clean URLs and Optimized Metadata

GA4 reports are easier to read when your URLs and page titles are structured clearly. Long or messy URLs can clutter reports and make it harder to evaluate page performance.

Tips for Drupal users:

  • Use the Pathauto module in Drupal to create clean, keyword-rich URLs like /services/seo-audit instead of /node/54
     
  • Use the Metatag module to set custom page titles and meta descriptions that accurately reflect your content
     
  • Avoid using session IDs or dynamic parameters in URLs unless necessary

GA4 reports use both page title and page path to group data. Clean URLs and clear titles make it easier to analyze what’s working.


4. Always Use UTM Parameters for Campaigns

UTM parameters help GA4 identify where your visitors come from and what content brought them in. Without them, traffic from emails, ads, and social platforms may be misclassified as "direct" or "unassigned."

Use these UTM fields:

  • utm_source (example: newsletter, facebook)
  • utm_medium (example: email, cpc, social)
  • utm_campaign (example: fall_launch, webinar_q3)
  • utm_content (optional: for variations or CTA testing)

Example:

https://example.com/landing?utm_source=newsletter&utm_medium=email&utm_campaign=fall_launch

If you’re linking to internal landing pages from marketing emails or social ads, always tag the links with UTMs. Then review the results in GA4 under Reports > Acquisition > Traffic Acquisition or by building a custom exploration.

Tools to generate UTM links:
Campaign URL Builder (Google)


5. Define Events and Mark Conversions

GA4 uses an event-based model, which means all user interactions (page views, clicks, submissions) are events. Some events happen automatically, others need to be set up manually. The most important ones should be marked as conversions so they can be measured against your business goals.

Step-by-step:

  1. Automatically Tracked Events: GA4 already tracks page_view, scroll, click, and file_download if Enhanced Measurement is on.
     
  2. Create Custom Events: You can define your own events such as form_submission, cta_click, or newsletter_signup. This can be done through Google Tag Manager or the GA4 interface.
     
  3. Mark Events as Conversions:
    • Go to Admin > Conversions
       
    • Click New Conversion Event
       
    • Enter the name of the event you want to track (must match exactly)

For Drupal users:

Use the Google Tag Manager module to push custom events for form submissions, cart actions, or CTA button clicks. You can also use JavaScript or trigger events directly in your templates.

Example:

Add a dataLayer.push() when someone submits a form:

window.dataLayer = window.dataLayer || [];
dataLayer.push({
 event: "newsletter_signup"
});

This data can then be picked up by GTM and sent to GA4 as a named event. You can label it as a conversion once it starts tracking.


Tracking Ecommerce on Drupal with GA4

If you're running an online store on Drupal, understanding what users do before, during, and after a purchase is essential. GA4 supports robust ecommerce tracking, allowing you to measure product views, cart behavior, checkout steps, transactions, and revenue.

To make this work in Drupal, especially if you're using Drupal Commerce, you’ll need to structure ecommerce data in a way GA4 can understand and push it into the dataLayer.


Why Use the dataLayer?

The dataLayer acts as a communication bridge between your Drupal site and Google Tag Manager (GTM). When a user views a product or completes a purchase, your site sends data to the dataLayer, which GTM can then capture and forward to GA4.

Example: Tracking a Product View

When a product page loads, you can push a view_item event like this:

<script>
 window.dataLayer = window.dataLayer || [];
 dataLayer.push({
   event: 'view_item',
   ecommerce: {
     items: [{
       item_id: '123',
       item_name: 'Sample Product',
       currency: 'CAD',
       price: 99.00
     }]
   }
 });
</script>

This structure follows GA4’s ecommerce schema, allowing you to track individual item views, revenue, and more. Other events you can trigger include:

  • add_to_cart
     
  • remove_from_cart
     
  • begin_checkout
     
  • purchase


Setting Up Google Tag Manager to Track Ecommerce Events

Once your site pushes events to the dataLayer, GTM steps in to listen and send the data to GA4.

Steps:

  1. Open your GTM workspace
     
  2. Create a new Trigger of type “Custom Event”
    • Event name: purchase (or view_item, etc.)
       
  3. Create a new Tag of type “GA4 Event”
    • Set the event name to match (e.g., purchase)
       
    • Map the ecommerce object using the Event Parameters section
       
    • Use your GA4 configuration tag

Repeat this setup for each ecommerce event you want to track.


Recommended Drupal Modules

To simplify ecommerce tracking, use contributed modules that expose ecommerce data in a GTM-friendly format.


1. Commerce Google Tag Manager

This module integrates Drupal Commerce with GTM by automatically pushing structured ecommerce events like product impressions, cart actions, and purchases into the dataLayer.

Features:

  • Exposes GA4-compatible ecommerce data
     
  • Works with product variations, SKUs, and prices
     
  • Customizable with tokens and rules

Installation:

composer require drupal/commerce_google_tag_manager
drush en commerce_google_tag_manager -y

Then go to:

Configuration > Google Tag Manager (Commerce section)

Enable the events you want and review the structure of the pushed data.


2. GTM Datalayer

If you’re not using Commerce, or have a custom shop setup, this module allows you to push custom events and values into the dataLayer.

Use case examples:

  • Tracking donations in a nonprofit store
     
  • Tracking virtual products or subscription purchases
     
  • Triggering events for quote requests or soft conversions

Advanced Ecommerce Tracking Tips

  • Track coupon codes: Include coupon: 'SPRING25' in your purchase event to measure promo performance.
     
  • Use dynamic values: Instead of hardcoding values, inject item data dynamically using Twig in Drupal templates.
     
  • Send refund events: For full ecommerce tracking, consider sending refund events if your platform supports it.
     
  • Connect to Google Ads: Link GA4 with your Google Ads account to track ecommerce conversions from campaigns.

Tracking Leads from Newsletters

Email newsletters are a powerful tool to bring users back to your site, promote content, and drive conversions. But without proper tracking, it’s impossible to know whether your campaigns are truly effective. Fortunately, GA4 gives you everything you need to measure newsletter performance if you set things up correctly.


1. Use UTM Parameters in All Email Links

The first and most important step is to tag your links with UTM parameters. These tags tell GA4 where your traffic is coming from and why.

For example, your email link might look like this:

https://www.example.com/download?utm_source=newsletter&utm_medium=email&utm_campaign=august_launch

UTM parameters used:

  • utm_source=newsletter (the channel, e.g., Mailchimp, Hubspot, etc.)
     
  • utm_medium=email (the format)
     
  • utm_campaign=august_launch (the campaign name)


2. Use a Dedicated “Thank You” Page

When someone signs up, downloads a resource, or completes another action via your newsletter, they should land on a dedicated confirmation page, such as:

https://www.example.com/thank-you

Why is this helpful?

  • It's a reliable conversion point
     
  • It isolates the event from partial form fills or reloads
     
  • It provides a clear URL that you can track in GA4

Bonus: You can also use this page to suggest additional content or encourage social sharing.


3. Create an Event in GA4 to Track the Thank You Page

To track conversions from newsletter visits, create an event in GA4 that fires when someone lands on /thank-you.

Steps:

  1. Go to Admin > Events
     
  2. Click Create Event
     
  3. Click Create and configure it like this:
    • Event Name: newsletter_lead
       
    • Matching Conditions:
       
      • page_location contains /thank-you
         
  4. Save the event

This custom event will now trigger every time a user reaches the Thank You page.


4. Mark That Event as a Conversion

Once your event is created, tell GA4 it’s important by marking it as a conversion.

Steps:

  • Go to Admin > Conversions
     
  • Click New conversion event
     
  • Enter newsletter_lead

From now on, GA4 will treat every visit to that thank you page as a conversion, giving you easy access to performance metrics in your reports.


5. Monitor Campaign Performance

Once your tracking is in place, you can monitor newsletter performance in several places:

  • Reports > Acquisition > Traffic acquisition
    • Filter by source and medium to isolate newsletter traffic
       
  • Reports > Engagement > Conversions
    • View how many newsletter_lead conversions were triggered over time
  • Explore tab
     
    • Create a custom funnel from email click to thank-you page

If you’re using Google Looker Studio, you can also build a custom dashboard with newsletter UTM tracking, open rates, click-throughs, and conversion counts all in one view.


Bonus Tip: Segment Audiences for Retargeting

If you want to remarket to people who opened your email but didn’t convert, set up an audience in GA4:

  1. Audience: Users with session source = newsletter but no conversion event
     
  2. Connect GA4 to Google Ads
     
  3. Retarget those users with a follow-up offer

Custom Reporting with GA4 + Looker Studio

While Google Analytics 4 provides several built-in reports, most teams quickly hit limitations when they need to present data in a way that aligns with their goals, KPIs, or cross-functional reporting. That’s where Looker Studio (formerly Google Data Studio) becomes essential.

By connecting GA4 to Looker Studio, you can turn raw tracking data into clear, visual dashboards that make it easier to communicate performance across marketing, content, SEO, and leadership teams. These dashboards update in real time (or near real time), making them ideal for weekly check-ins, stakeholder reporting, or campaign retrospectives.


Connecting GA4 to Looker Studio

  1. Open Looker Studio
     
  2. Click Blank Report or use a template
     
  3. Under Connect to Data, choose Google Analytics
     
  4. Select your GA4 property and web data stream

Once connected, you can drag and drop dimensions, metrics, filters, and visualizations to build fully customized reports.


Key Charts to Include in Your Dashboard

Depending on your goals, here are some high-impact visualizations worth including:

1. Organic vs. Paid Traffic Split

  • Show how much traffic is coming from search engines versus paid campaigns.
     
  • Use filters for Default Channel Grouping or UTM medium.


2. Top Landing Pages by Conversion Rate

  • Highlight which pages are bringing in the most engaged traffic.
     
  • Useful for content teams optimizing high-intent pages.


3. Bounce Rate and Engagement Time by Device

  • Understand how mobile, tablet, and desktop users behave.
     
  • Use this to catch UX or speed issues affecting specific devices.


4. Campaign Performance Breakdown

  • Visualize traffic and conversions by UTM parameters:
    • Source (utm_source)
       
    • Medium (utm_medium)
       
    • Campaign (utm_campaign)
       
  • Useful for newsletters, ads, and partnership links.


5. Lead or Purchase Funnel

  • Set up a visual funnel to show user progression from visit to conversion.
     
  • Combine event data like view_item, add_to_cart, and purchase.


6. Search Terms or Site Search Data

  • Show what users are looking for within your Drupal site.
     
  • Track if they’re finding what they need, or where content gaps exist.

Final Tips and QA Tools

  • Use DebugView in GA4 to test events in real-time
     
  • Install Google Tag Assistant to verify that your GA4 or GTM tags are loading correctly
     
  • Check mobile and page speed performance with Lighthouse.

Conclusion: Set Up GA4 to Measure What Matters

Google Analytics only works when it reflects your goals. Whether you're tracking sales, lead forms, or article engagement, a well-configured GA4 setup gives you the visibility needed to make smart decisions.

At Monarq, we help organizations set up Google Analytics in a way that’s useful, scalable, and aligned with how your site is actually used. From technical implementation to event planning and dashboard creation, we can help you get more out of your data.

Let’s talk about how to get your GA4 tracking working the way it should.