Adding google analytics to Astro can be done with the partytown integration.
Step 1: Add Partytown to your Astro site
npx astro add partytown
Step 2: Add datalayer push as a forwarding event in your astro.config.mjs file
export default defineConfig ({
integrations: [partytown({
config: {
forward: ["dataLayer.push"]
},
})],
})
Step 3: Add GA tag on every page of your Astro Note: If you are using a common layout, you can just add that there directly.
Paste the tag obtained from google analytics as soon as the head tag ends. Add type=”text/partytown” inside the script tags obtained from Google analytics.
type="text/partytown"
Screenshot of script tag placed inside the HTML after the head tag
After the above-mentioned changes, it might look something like this.
Don’t forget to add the tag to every page you have created with Astro, or add it to the common layout.
Have a great day! See you at the next one.