ReactHustle

How to Dynamically Add Google Analytics 4 to an Astro Website

Jasser Mark Arioste

Jasser Mark Arioste

How to Dynamically Add Google Analytics 4  to an Astro Website

Hello! In this tutorial, you'll learn how to add Google Analytics 4 (GA4) to an Astro website where the Measurement ID is dynamic.

Introduction #

I've seen many tutorials on how to add Google Analytics 4 to an Astro website. Still, none of these tutorials give examples of when the Measurement ID is dynamic like for example, defined in an environment variable.

What is Google Analytics 4? #

Google Analytics 4 (GA4) is a powerful tool that allows website owners to track and analyze user behavior, providing valuable insights into their website's performance. If you've built your website with Astro, a static site generator, you may be wondering how to integrate Google Analytics 4 into your project. In this article, we'll walk you through the step-by-step process of adding GA4 to your Astro website.

Why use Google Analytics4? #

Google Analytics 4 offers several advantages over its predecessor, Universal Analytics. It provides more accurate and comprehensive data, better integration with other Google tools, and a stronger focus on user behavior analysis. By implementing GA4, you can gain a deeper understanding of your website's performance and make data-driven decisions to improve user experience and achieve your goals.

Here's how you can add Google Analytics 4 to your Astro website.

Step 1: Create a Google Analytics 4 Property: #

If you don't already have a Google Analytics account, you'll need to create one. Go to the Google Analytics website (https://analytics.google.com) and sign in with your Google account. Once logged in, follow these steps:

  1. Click on "Admin" in the bottom-left corner.
  2. Click on "+ Create" dropdown and click Property. A wizard will guide you through the steps. 
  3. Configure the Property name, as well as additional settings like industry category, time zone, and currency.
  4. Choose "Web" as your platform.

Step 2: Set Up a Data Stream #

Once you've created a property for your website, you'll need to set up a data stream. A data stream is a connection between your website and your Google Analytics property. Follow these steps:

  1. Enter the name of your data stream and your website's URL.
  2.  Click "Create stream."

Step 3: Get Your GA4 Tracking Code #

After creating the data stream, you'll be presented with your GA4 tracking code snippet. This code is unique to your website and must be added to your Astro project to enable tracking.

Step 4: Add the Tracking Code to Your Astro Project #

Let's set the Measurement ID as an Environment Variable in our project. Create the file .env.local in the root directory of your Astro project.

# .env.local
# be sure to add the PUBLIC_ prefix so that the frontend can access this variable.
PUBLIC_TRACKING_ID="G-ECPLHSSRWY" 

Replace "PUBLIC_TRACKING_ID" with your actual Measurement ID provided by Google Analytics. It's a unique identifier for your property.

Step 4: Creating the Main Layout #

The main layout will contain the script to add gtag script. First, let's create the file /src/layouts/MainLayout.astro:

---
// MainLayout.astro
//Import the Tracking ID
const TRACKING_ID = import.meta.env.PUBLIC_TRACKING_ID!;
const gaSrc = `https://www.googletagmanager.com/gtag/js?id=${TRACKING_ID}`;
---

<html lang="en">
  <head>
    <!-- ...head scripts -->
  </head>

  <body>
    <!-- body layout -->
    <!-- GA Scripts -->
    <script async src={gaSrc}></script>
    <script async>
    const TRACKING_ID = import.meta.env.PUBLIC_TRACKING_ID;
    window.dataLayer = window.dataLayer || [];
    function gtag() {
      window.dataLayer.push(arguments);
    }

    gtag("js", new Date());
    gtag("config", TRACKING_ID);
    </script>
  </body>
</html>
12345678910111213141516171819202122232425262728

Step 5: Use the layout component in your pages #

I don't have to state this but I'll just put it here for good measure. Don't forget to use the layout component in your page. For example in the pages/index.astro

---
import MainLayout from "@layouts/MainLayout.astro"
---
<MainLayout>
  This is the homepage.
</MainLayout>
123456

Step 6: Deploy your application #

After adding the tracking code, save your changes and redeploy your Astro website. This will ensure that the GA4 tracking code is included on all pages of your site.

In my case, I use Vercel to deploy my Astro website so I also had to add the environment variables there:

Here, I had a different tracking ID for development and preview branches from the production branch.

Step 7: Verify the Setup #

To confirm that GA4 is working correctly on your Astro website, visit your site and navigate through different pages. Then, go back to your Google Analytics account and check the "Realtime" section to see if data is being recorded. This may take some time to populate, so be patient.

Conclusion #

Integrating Google Analytics 4 with your Astro website can provide valuable insights into user behavior, helping you make informed decisions to improve your website's performance. By following the steps outlined in this guide, you can easily add GA4 to your Astro project and begin tracking user interactions and website analytics effectively. Remember to regularly check your Google Analytics dashboard to gain insights into your site's performance and make data-driven improvements.

Credits: Image by Alfons from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle