Integrating Google Analytics with Astro JS Full Site View Transitions: A Step-by-Step Guide

by Ramon Malcolm on January 10, 2024 07:00:00 UTC
1 min read

In this article, we’ll guide you through the process of integrating Google Analytics with Astro JS to ensure that events are properly sent on navigation. Follow these steps to enhance tracking capabilities and gain valuable insights into user interactions on your Astro-powered website.

Step 1: Get Your Google Analytics Tracking ID

Before proceeding, make sure you have a Google Analytics account and obtain the tracking ID for your website.

Step 2: Copy the Following Code

Copy the following code and paste it into the <head> section of each page or your main layout:

<script 
  async 
  src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
></script>
<script is:inline>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
</script>
<script is:inline>
  document.addEventListener(
    "astro:page-load",
    () => {
      gtag("js", new Date());
      gtag("config", "G-XXXXXXXXXX");
    },
    { once: false }
  );
</script>

Step 3: Replace G-XXXXXXXXXX with Your Tracking ID

Replace “G-XXXXXXXXXX” in the code with your actual Google Analytics tracking ID.

By following these steps, you’ll successfully integrate Google Analytics with Astro JS and ensure that events are sent on navigation. Happy tracking! 🚀

Article was last modified on April 11, 2024 10:58:51 UTC