Blogs

Integrating Google Analytics with Astro, Typescript and View Transitions

Google Analytics
Astro JS
Web Development
Tracking

Learn how to set up Google Analytics with Astro JS to track user interactions effectively.

Add Google Analytics with Astro when using view transitions. Here’s a quick guide to set it up and understand key concepts like astro:page-load and is:inline.

Quick Integration Steps

1. Get Your Google Analytics Tracking ID

Ensure you have a Google Analytics account and retrieve your tracking ID (e.g., G-XXXXXXXXXX).

2. Add the Tracking Code

Include the following code in the <head> section of each page or your main layout file:

<script is:inline src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>

<script>
      declare global {
        interface Window {
          dataLayer: any[];
          gtag: (...args: any[]) => void;
        }
      }
      document.addEventListener("astro:page-load", () => {
        window.dataLayer = window.dataLayer || [];
        window.gtag = function gtag(...args: any[]) {
          window.dataLayer.push(arguments);
        };
        window.gtag("js", new Date());
        window.gtag("config", "G-XXXXXXXXXX");
      });
</script>

3. Replace the Placeholder

Substitute G-XXXXXXXXXX with your actual Google Analytics tracking ID.

Key Concepts

  • astro:page-load Event Purpose: Fires after a page is fully loaded and visible. Use it to run scripts on initial load and subsequent navigations.

  • is:inline Directive Function: Keeps the <script> tag as-is in the final HTML, bypassing bundling and optimization. This ensures your Google Analytics script runs correctly on every page load.

Bonus: Add Web Vitals.

The script below integrates Web Vitals with Google Analytics by initializing the gtag function and sending performance metrics to Google Analytics. Helping you track and analyze key performance indicators for your website’s user experience.

npm install web-vitals

<script>
	declare global {
		interface Window {
			MyLib: any;
			dataLayer: any[];
			gtag: (...args: any[]) => void;
		}
	}
	import { onCLS, onINP, onLCP, onTTFB, onFCP } from "web-vitals";
	document.addEventListener("astro:page-load", () => {
		window.dataLayer = window.dataLayer || [];
		window.gtag = function gtag(...args: any[]) {
			window.dataLayer.push(arguments);
		};
		window.gtag("js", new Date());

		window.gtag("config", "G-XXXXX");

		function sendToGoogleAnalytics({name, delta,value, id}: 
    {name: string; delta: number;value: number; id: string;}) {
			window.gtag("event", name, {
				value: delta, 
				metric_id: id, 
				metric_value: value,
				metric_delta: delta,
			});
		}

		onCLS(sendToGoogleAnalytics);
		onINP(sendToGoogleAnalytics);
		onLCP(sendToGoogleAnalytics);
		onTTFB(sendToGoogleAnalytics);
		onFCP(sendToGoogleAnalytics);
	});
</script>

Using the code below means Google Analytics and advertising services will not collect or use any data related to ads or analytics. This helps ensure compliance with privacy regulations, but it also limits the depth of user insights and tracking capabilities available to you. For example it will show each pageview as a new page view even from the same.

<script>
		//...existing code...
        window.gtag("consent", "default", {
          ad_storage: "denied",
          ad_user_data: "denied",
          ad_personalization: "denied",
          analytics_storage: "denied",
        });
		window.gtag("config", "G-XXXXX");
</script>