Using Google analytics on Astro ― TalentedUnicorn
Back to blog

Using Google analytics on Astro

If you've been keeping up with the extensive number of tools to build your website with; you may have come across Astro — the all-in-one web framework designed for speed.

Like a number of similar frameworks1; Astro embraces the server-first approach by rendering HTML on the server making websites faster to load. This makes Astro perfect for content-focused websites.

I recently needed to add a Google Analytics tracking tag to a fun Astro project and this is how I did it.

All about the layout

I needed to add the script tags to the layout so they get rendered on pages using the layout. But rather than pasting the analytics scripts right into the layout template I created a component that gets rendered in production only.

import Analytics from "components/analytics.astro"
const isProd = import.meta.env.MODE === 'production';

  ... {isProd &&
  <Analytics />

Analytics component

The component itself needed to be reusable so I extracted the tag ID to an environment variable named GTAG

const tagId = import.meta.env.GTAG;

	<!-- Google tag (gtag.js) -->
	<script async src=`https://www.googletagmanager.com/gtag/js?id=${tagId}`></script>
	<script define:vars={{ tagId: tagId }}>
		window.dataLayer = window.dataLayer || [];
		function gtag() {
		gtag('js', new Date());

		gtag('config', tagId);

You may have noticed the define:vars directive on the second script tag — this allows us to use server-side variables inside <script> and <style> tags as well as treating the script with the is:inline directive for the script to be rendered inline on the HTML.

You could alternatively pass the variables manually through data attributes data-* and then reading the values with this.dataset.[variable-name]

Cover photo: a red and white rocket ship flying through the sky — Andy Hermawan

  1. Frameworks like GatsbyJs or NextJs

Other posts

Changing author information on a git commit

March 13, 2020

Read more