Skip to content

Analytics - GA4

Google Analytics 4 tracks page views, events, and user behaviour.


Get the Measurement ID from the client’s Google Analytics account (format: G-XXXXXXXXXX).

Add to Layout.astro <head>:

<script is:inline async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script is:inline>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>

Replace both instances of G-XXXXXXXXXX with the real Measurement ID.


The _headers CSP must include GA4 sources:

script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com;
connect-src 'self' https://www.google-analytics.com https://region1.google-analytics.com https://www.googletagmanager.com https://stats.g.doubleclick.net;

These are already included in the standard _headers template.


GA4 stores cookies and collects user data. The site must have a Privacy Policy that mentions Google Analytics. The standard privacy-policy.astro template includes a section for this.


  • Get GA4 ID from client (or set up a new property in their Google account)
  • Confirm Privacy Policy is live and mentions analytics
  • Consider adding a cookie consent banner (required for GDPR/EU visitors)

  • is:inline on the <script> tag means Astro does not process or bundle it - it outputs exactly as written
  • The async attribute on the GTM script ensures it does not block page rendering
  • GA4 tracking is not visible during local dev (localhost is filtered in GA4 by default)