Adding Google Analytics 4 to Astro Site
Create Google Analytics Property
Create a Google Analytics Property at https://analytics.google.com/analytics.
Input a property name and the location.
Select your business details.
Select the purpose of using GA4.
Since we are adding GA4 to an Astro website, choose Web platform.
Fill out your Astro website info.
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.