Add google analytics to Astro with Partytown
Kevin Zuniga Cuellar @kevinzunigacuel
As your website attracts more visitors, you may need to incorporate various third-party scripts into your project to extend its functionality beyond the core features. Two common third-party scripts are Google Analytics and Facebook Pixel, which are web analytics services that help you assess and improve your website’s effectiveness.
In this guide, we will focus on adding Google Analytics to your Astro project using Partytown, a web worker integration.
🧑💻 Getting Started
To begin, create a new Astro project using the CLI:
Next, install the Astro integration for Partytown:
Add the Partytown integration to your astro.config.mjs
file with the following configuration options:
This configuration enables Partytown to forward all events to Google Analytics using window.dataLayer
. For more information about configuration options, refer to the Partytown documentation.
Create a Google Analytics account and obtain the tracking ID. After creating a new property for your domain, you can find the tracking ID in the Property Settings.
Hands-on Time
Now that we have the Partytown integration installed and the Google Analytics tracking ID, we can proceed with setting up our Google Analytics script.
Google Analytics will provide you with an inline script that will resemble the following:
To enable Partytown to run Google Analytics in a web worker, make the following modifications to the script:
- Replace
GA_MEASUREMENT_ID
with your tracking ID. - Add a
type
attribute and set it totext/partytown
for both script tags. This informs Partytown which script tags to handle.
After applying the modifications, your updated script will look like this:
Finally, place this code snippet in the head section of your HTML. If you copy the code above, remember to update GA_MEASUREMENT_ID
with your tracking ID.
Congratulations! You have successfully added Google Analytics to your Astro project. 🎉
Testing
After deploying your project, visit your Google Analytics. You should see some recent activity after visiting your website.