Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to add Google Analytics 4 code to Magento 2?

Vinh Jacker | 08-21-2026 How to Add Google Analytics 4 to Magento 2: Step-by-Step Instructions - Mageplaza

In eCommerce, having accurate data isn’t just a bonus—it’s the backbone of your business decisions. Without clear insights into things like traffic sources, bounce rates, or session times, how can you know what’s working and what isn’t? Data reports help you fine-tune your marketing strategies and understand what keeps customers coming back.

For years, Google Analytics has been the go-to tool for gathering these insights. It’s reliable, easy to use, and trusted by businesses around the world. But with Universal Analytics being retired, many store owners are scrambling to figure out what’s next.

That’s where Google Analytics 4 (GA4) comes in. Designed for the future of analytics, GA4 offers smarter tracking, better insights, and a more modern approach. But let’s be honest—some people haven’t given it the chance it deserves, assuming it’s too complicated to set up.

But trust us, it’s not. In fact, adding GA4 to your Magento 2 store is easier than you think, especially with the help of a Google Analytics 4 extension. This guide will provide clear steps for effortlessly integrating GA4 with your Magento 2 store.

How to add Google Analytics 4 to Magento 2

Google Analytics is an essential tool for businesses aiming to make data-driven decisions and improve conversion rates. With over 56.5% of websites worldwide relying on it, it’s clear how valuable it is for tracking and analyzing online traffic.

If you’re managing a Magento store and want to gain deeper insights into customer behavior, integrating Google Analytics 4 (GA4) is the way forward. This guide will show you exactly how to set up GA4 for Magento 2.

Method 1: Add Google Analytics 4 to Magento 2 manually

Step 1. Set Up a Google Analytics Property

#1. Log in to your Google account and navigate to Google Analytics.

If you don’t already have an account, signing up is quick and free. Simply visit the Google Analytics homepage, click the Get Started Today button, and press Start measuring to create your GA4 account. From there, you can configure your new property and begin tracking valuable insights for your website.

login GA account

#2. Provide an account name that makes it easy to identify your account within the Analytics dashboard. This could be your company name, website name, or any descriptive label that suits your business needs.

#3. Next, customize your Account Data Sharing Settings by checking or unchecking the relevant boxes. These options allow you to control how your tracking data is shared with Google. If you prefer, you can uncheck all the boxes—this won’t affect your ability to integrate Google Analytics with Magento.

Once you’ve configured the settings to your preference, click Next to move to the next step.

enter name

#4. In the Property creation section, enter a name for your Google Analytics property, such as your website or business name, to help you easily identify it. Then, set your reporting time zone and currency to match your business location and transaction preferences.

create property

#5. Click Next to move on to Business details. Then, select your industry and business size to allow GA4 to provide insights tailored to your business.

business detail

#6. Click Next to move to the next step. Here, choose your business objectives to outline how you plan to use Google Analytics, such as tracking customer engagement, boosting sales, or measuring traffic. Remember, you can choose multiple answers in this section.

google analytics

#7. Once you’ve made your selections, click Create to finalize your setup.

terms and conditions

A Google Analytics Terms of Service Agreement popup will appear. Select your country, review the data processing terms, and click I Accept to proceed.

#8. Next, you need to set up a data stream, which tells GA4 where to collect data from. Since you’re integrating with a website, choose Web as your platform. This step ensures Google Analytics 4 can track data from your Magento store effectively.

google analytics

#9. Enter your Website URL and a descriptive Stream Name.

enter website url

#10. Finally, click Create & continue to complete the setup. Congratulations! You’ve successfully created a Google Analytics 4 property and data stream.

Step 2: Get Measurement ID

After setting up a GA property, you’ll be redirected to the Web Stream Details page. Here, you’ll find your Measurement ID (e.g., G-XXXXXXXXXX), which is essential for integration later.

If you already have an existing property, simply login to your GA account, go to the admin panel and click on Data Streams. Select the relevant data stream, and you’ll see the Measurement ID displayed there.

measurement id

In the Google tag section, click on View tag instructions and copy the code snippet inside Installation Instructions > Install manually > Google tag (gtag.js). Head over to the Magento admin to add Google Analytics in Magento.

google analytics measurement code

Step 3: Add GA4 to Magento 2 store

After setting up GTM, the next step is to integrate Google Analytics 4 (GA4) with Magento 2.

Note: The Mageplaza Google Tag Manager extension also supports Google Analytics 4, so both work in the same way.

Login to the admin panel > Stores > Configuration > Sales > Google API. Expand the Google Analytics tab, uncheck Use system value, and set Enable to Yes. Then, enter your Measurement ID in the Account Number field and click Save Config.

Optionally, you can enable Anonymize IP to hide visitor IP addresses and set Enable Content Experiments to Yes if you want to use eCommerce tracking with A/B testing.

configure google analytics

If you’re using a GA4 property, you’ll need to add the global site tag to your website’s <head> section. Inserting the code at the beginning of the head section ensures that events are tracked, even if users stop the page from loading prematurely.

To add Google Analytics in Magento using the global site tag, go to Content > Design > Configuration in the Magento admin. In the Action column on the Design Configuration page, click the Edit link next to the store view you want to configure.

Scroll down to the HTML Head section, expand it, and paste the GA4 site tag into the Scripts and Style Sheets section.

Click Save Configuration, and don’t forget to refresh the Magento cache to apply the changes on the frontend.

Step 4: Verify that Google Analytics is working

Open the Google Analytics dashboard and navigate to the Realtime overview section of your newly created property. Here, you’ll be able to track live visitors to your site and monitor their interactions in real-time.

If you can’t see any live visitors on your Google Analytics dashboard, try these troubleshooting steps for Magento analytics tracking:

  • Disable any ad blockers or analytics blocking features in your browser, as these can prevent the tracking code from firing properly.
  • Verify that the Google Analytics code in the Magento backend is correctly implemented, especially the GA4 or Measurement ID.
  • Flush the Magento store cache to ensure the changes take effect and the updated tracking code is active on the frontend.

Method 2: Add Google Analytics 4 to Magento 2 by using the extension

Step 1: Set up a Google Analytics property

Follow the same steps as in method 1.

Step 2: Get Measurement ID

After setting up a GA property, you’ll be redirected to the Web Stream Details page. Here, you’ll find your Measurement ID, which is essential for integration later.

If you already have an existing property, simply login to your GA account, go to the admin panel and click on Data Streams. Select the relevant data stream, and you’ll see the Measurement ID displayed there.

measurement id

Step 3: Create a GTM container

Since Google Tag Manager (GTM) will be used to integrate Google Analytics 4 with Magento, you’ll need to set up GTM as well. If you already have a GTM account, you can skip to the next step. If not, follow these instructions to set one up:

Go to the Google Tag Manager website and click Create Account button.

Next, fill in the required fields, including Account Name, Country, Container Name, and Target platform.

Create a GTM container

Once completed, click Create to set up your account and container.

Remember: The container name serves as a descriptive title that helps link the container to your website.

Click Create, review the GTM Terms of Service, and click Yes to accept.

Step 4: Locate the Account and Container ID

In addition to the Google Analytics Measurement ID, you’ll also need to gather tracking IDs from Google Tag Manager (GTM). To do this, simply login to the GTM homepage and select the container you plan to use for tracking.

  • Account ID: To find the Account ID, go to the Workspace tab in your container. The Account ID will be visible in the browser address bar, right after /accounts/.
  • Container ID: The Container ID can be easily found in several places, including right after you log into your GTM account. It is displayed at the top of the container page, typically in the format of a string like “GTM-XXXXXX”.

Step 5: Add your GTM codes to Magento 2 store

We use Mageplaza Google Analytics 4 to simplify the integration with GA4 and Google Tag Manager. This module allows merchants to track customer behavior, monitor store performance, and evaluate the success of marketing and promotional efforts.

Log into your Magento 2 store and go to: Stores > Configuration > Mageplaza > Google Tag Manager to configure the GA4 extension.

In this step:

  • Select Yes in the Enable field to activate the extension.
  • Paste the Container ID you obtained earlier into the Google Tag ID field.
  • Click Save Config to apply the changes.

Step 6: Turn on server-side GA4 tracking

Mageplaza Google Tag Manager can also send purchase and refund events directly from Magento to GA4 via the Measurement Protocol, running alongside client-side tracking as an extra path for critical eCommerce events:

Customer places an order → Client-side GA4 event + Server-side GA4 event → GA4

Both events share the same transaction ID, so GA4 deduplicates them automatically. Server-side events can be reviewed in the Event Log grid in Magento Admin.

To configure it, go to:

Stores > Configuration > Mageplaza > Google Tag Manager > Google Analytics 4

Configuration Google Analytics 4

Enable server-side tracking and enter the required GA4 credentials:

server-side tracking and enter the required GA4
  • Measurement ID: In Google Analytics, go to Admin > Data Streams, select your Magento web data stream, and copy the Measurement ID in the format G-XXXXXXXXXX.
  • API Secret: In the same web data stream, go to Measurement Protocol API secrets > Create. Create a new API secret, copy the generated value, and enter it in the Magento configuration.
  • Events to Send Server-side: Select which events (such as Purchase and Refund) should be tracked through server-side tracking.
  • Send Purchase On: Choose the order status or trigger point (e.g., order placement, invoice creation) that determines when the server-side purchase event is sent to GA4.

The remaining fields can be configured by following the instructions provided in the User Guide (UG).

💡 Tip: Don’t add every event to the list. GA4 deduplicates purchase events by transaction_id. It does not do the same for other events.

Once both values are configured, click Send Test Purchase to check whether Magento can successfully connect to GA4 before saving your configuration.

Step 7: Check GTM on your site

Verifying whether Google Tag Manager (GTM) has been successfully added to your store is a crucial step to ensure your setup is functioning as intended. Here are two simple methods to check:

Method 1: Using View Source

  • Open your website’s homepage in a browser.
  • Press CTRL + U (or Command + Option + U on Mac) to view the page source.
  • Press CTRL + F (or Command + F on Mac) to open the search bar and type GTM.
  • If you locate the GTM code snippet (e.g., GTM-XXXXXX) in the source code, congratulations! Google Tag Manager has been successfully added to your site.

Method 2: Using GTM Preview Mode

  1. Log in to your Google Tag Manager account and navigate to the Workspace tab.

  2. Click on the Preview button.

  3. Enter your site URL in the provided field and click Connect.

  4. If the configuration is correct, a confirmation message will appear, indicating that GTM is successfully connected and active on your site.

Checking Server-Side Tracking Status

If you enabled server-side tracking, check it in two more places:

  • In GA4: Reports > Realtime, or Admin > DebugView

  • In Magento: The GA4 Server-side Event Log grid, which lists each event’s Status, Attempts, Last Code, Last Error, and Next Attempt

A purchase that shows in the event log as Sent but never appears in GA4 usually points to a delivery issue on Google’s side worth investigating further. One that shows as Retry, along with a Last Code and Last Error, means the event failed to send and the extension will automatically attempt again at the time shown in Next Attempt—until it succeeds or hits the configured Max Retry Attempts, at which point it’s marked Expired.

Common Mistakes to Avoid When Setting Up GA4 in Magento 2

Integrating Google Analytics 4 (GA4) into your Magento 2 store is a straightforward process, but there are a few common mistakes that can hinder your tracking efforts. Here are some pitfalls to watch out for and how to avoid them:

  • Incorrect Measurement ID: Ensure the correct Measurement ID is used to avoid data tracking errors.
  • Not Refreshing Cache: Many users forget to refresh the Magento cache after integrating GA4, causing the changes to not reflect on the frontend.
  • Trusting browser-side tracking alone: Client-side tracking depends on the shopper’s browser, so purchase or refund events may be missed when tracking requests are blocked or interrupted. Mageplaza Google Tag Manager adds server-side GA4 purchase and refund tracking as an additional tracking path. It works alongside client-side tracking, with automatic deduplication by transaction ID to prevent duplicate transactions.
  • Missing Privacy Compliance: Failing to enable Cookie Restriction Mode can lead to non-compliance with GDPR and CCPA.
  • Skipping Debugging: Always verify the setup using Google Tag Assistant or GTM Preview Mode to ensure the tracking works correctly.

Important Privacy Considerations for Google Analytics

Integrating Google Analytics 4 (GA4) with Magento 2 is a powerful way to track customer behavior and optimize your store. However, it’s equally important to ensure that your setup complies with privacy regulations like the General Data Protection Regulation (GDPR) in the European Union and the California Consumer Privacy Act (CCPA) in the United States. Here’s what you need to know:

#1. Configure Consent for Both Client-Side and Server-Side Tracking When using GA4 with Magento 2, consent should be considered across both client-side and server-side tracking.

A common misconception is that moving tracking from the shopper’s browser to the Magento server automatically bypasses consent. Server-side tracking changes how events are sent, but merchants still need to choose the appropriate consent behavior based on their privacy implementation and applicable requirements.

Mageplaza Google Tag Manager provides three consent modes for server-side tracking:

Consent mode How it works
Strict Server-side tracking follows the customer's consent status and does not send the event when the required analytics consent has not been granted.
Always Send Server-side purchase and refund events are sent according to the configured tracking setup regardless of the browser-side consent state. Merchants should only use this mode when it is appropriate for their privacy and consent implementation.
Cookieless When analytics consent is unavailable, tracking can operate without relying on analytics cookies, allowing limited measurement while respecting the configured consent behavior.

Choose the mode that matches your store’s consent implementation and applicable privacy requirements.

💡 Important: These modes control the technical behavior of server-side tracking. Choosing a mode does not by itself make an analytics implementation compliant. Merchants remain responsible for configuring tracking according to their consent requirements and privacy policies..

You should also use a clear cookie consent mechanism where required, explain what analytics data is collected and why, and give shoppers the appropriate controls over analytics tracking.

#2. Anonymize IP Addresses

To comply with GDPR rules against collecting personally identifiable information (PII), activate the Anonymize IP option in Google Analytics. This ensures that only partial IP addresses are stored, reducing privacy risks.

#3. Include Privacy Disclosures

Your website’s privacy policy should explicitly outline your use of Google Analytics, including:

  • The types of data collected.
  • How the data is used.
  • Whether it is shared with third-party services (like Google).

This transparency is vital for GDPR and CCPA compliance.

#4. Allow Data Access and Deletion Requests

Under GDPR and CCPA, users have the right to:

  • Access their personal data.
  • Request the deletion of their data.

Ensure your Magento store has processes in place to handle such requests promptly.

#5. Configure Data Retention Settings

In Google Analytics 4, you can set limits on how long user and event data are stored. Adjust these settings to align with privacy regulations:

  • Go to Admin > Data Settings > Data Retention in Google Analytics.
  • Set the retention period to the minimum necessary (e.g., 14 months) unless otherwise justified.

#6.Provide an Opt-Out Option

CCPA requires that users be able to opt out of having their data sold or shared. Include an opt-out link on your website and make it prominent. Google offers a GA opt-out browser add-on that you can direct users to as well.

#7. Review Data Transfers

If your data is shared across borders (e.g., stored in the US but collected from EU users), ensure you comply with GDPR cross-border data transfer rules, such as using Standard Contractual Clauses (SCCs) or Privacy Shield (if applicable).

Conclusion

Setting up Google Analytics 4 (GA4) in Magento 2 gives you clearer insights into customer behavior and store performance. Whether you choose a manual setup or use an extension, make sure your tracking is properly configured, tested, and aligned with your privacy requirements.

For more reliable eCommerce tracking, Mageplaza Google Tag Manager goes beyond browser-side tracking by sending purchase and refund events directly from Magento to GA4 via the Measurement Protocol. With client-side and server-side tracking working together, automatic deduplication by transaction ID, Test Connection, and an Admin Event Log, you can track critical transactions more reliably and troubleshoot issues more easily.

Choose the setup that fits your store, test it carefully, and use accurate GA4 data to make better decisions for your Magento business.

Table of content
    Jacker

    Jacker is the Chief Technology Officer (CTO) at Mageplaza, bringing over 10 years of experience in Magento, Shopify, and other eCommerce platforms. With deep technical expertise, he has led numerous successful projects, optimizing and scaling online stores for global brands. Beyond his work in eCommerce development, he is passionate about running and swimming.



    Related Post