How to Integrate Google Analytics with Astro Using Partytown: The Best Way for Optimal Performance
Streamline Third-Party Script Integration (Google Analytics, etc.) for Faster Websites with Astro and Partytown
Day by Day I love Astro and its performance results, since you're reading this blog it's likely you're already using it. I will show you in this blog the best way to integrate Google Analytics (and maybe other third-party scripts like Facebook Pixel...) with the help of Partytown.
If you're unfamiliar with Partytown, It's a lazy-loaded library that helps relocate resource-intensive scripts into a web worker, and off of the main thread. Its primary goal is to help you use third-party scripts without slowing down your site.
Normally, this is the code you need to add to the head of your document
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-ID');
</script>
First, let's install Partytown:
#npm
npx astro add partytown
#pnpm
pnpm astro add partytown
#yarn
yarn astro add partytown
Create Astro component google-analytics.astro
with the following content:
---
const GA_MEASUREMENT_ID = import.meta.env.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 || []
window.gtag = function gtag() {
dataLayer.push(arguments)
}
gtag('js', new Date())
gtag('config', GA_MEASUREMENT_ID)
</script>
I use an environment variable so if The project is open source it won't expose the measurement ID. Remember to create a .env
file and include the variable as shown below:
PS: You can be added to platforms like Vercel or Netlify...
GA_MEASUREMENT_ID=YOUR-ID
Last but not least, You need to include that component in a layout or a page. There are two conditions to render the script:
Only render it in a production environment
Render it if
GA_MEASUREMENT_ID
is truthy (it exists). This ensures that if you didn't add it to production, you won't see an error in the console.
---
import GoogleAnalytics from '../components/google-analytics.astro'
const GA_MEASUREMENT_ID = import.meta.env.GA_MEASUREMENT_ID
const isProd = import.meta.env.PROD
---
<!doctype html>
<html lang="en">
<head>
<!-- Metadata tags -->
{isProd && GA_MEASUREMENT_ID && <GoogleAnalytics />}
</head>
<body>
</body>
</html>
I have put the final code in this repository. I hope you find this article helpful. Thank you for reading.