Adding Google Analytics 4 to Astro Site

Create Google Analytics Property

Create a Google Analytics Property at https://analytics.google.com/analytics.

Create Google Analytics Property 1

Input a property name and the location.

Create Google Analytics Property 2

Select your business details.

Create Google Analytics Property 3

Select the purpose of using GA4.

Create Google Analytics Property 4

Since we are adding GA4 to an Astro website, choose Web platform.

Create Google Analytics Property 5

Fill out your Astro website info.

Create Google Analytics Property 6

When the property is created, note down the Measurement ID.

Add Measurement ID to Environment Variable

We want to add the GA4 Measurement ID to environment variables.

We create a .env file locally and add the following:

PUBLIC_GA_MEASUREMENT_ID=<your-measurement-id>

Now we can get the Measurement ID by

const GA_MEASUREMENT_ID: string = import.meta.env.PUBLIC_GA_MEASUREMENT_ID;

Install PartyTown

We want to install partytown to load the Google Analytics script in a web worker.

https://docs.astro.build/en/guides/integrations-guide/partytown/

By side-loading the Google Analytics scripts, we preserves the best performance from Astro.

pnpm astro add partytown

Add Google Analytics Script

Add the following script to the pages `“ where you want to include GA4.

---
const GA_MEASUREMENT_ID: string = import.meta.env.PUBLIC_GA_MEASUREMENT_ID;
---

<script
  type="text/partytown"
  src=`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`>
</script>
<script type="text/partytown" define:vars={{ GA_MEASUREMENT_ID }}>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
  dataLayer.push(arguments);
  }
  gtag("js", new Date());
  gtag("config", GA_MEASUREMENT_ID);
</script>

Deploy the Site and Check Google Analyics Realtime User

Remember to add the environment variables to the deployment environment variables.

Go to your site and verify the above script has been added to the <head></head>.

Go to Google Analytics Realtime Reports to see the result.