To add Google Analytics 4 to an Astro site, create a GA4 property, copy your measurement ID (it starts with G-), and paste the gtag snippet into the <head> of your base layout using <script is:inline> so Astro outputs it untouched. Every page that uses the layout is then tracked. No Astro Google Analytics integration is needed, and the setup works on fully static sites.
This guide turns that snippet into a reusable component, keeps it out of local development, makes page views work with view transitions, sends custom events, and adds Consent Mode for visitors in regions that require it.
Key Takeaways
- Use
is:inline(ordefine:vars, which implies it) so Astro doesn’t bundle Google’s script.- Store the measurement ID in a
PUBLIC_GA_IDvariable and render the tag only whenimport.meta.env.PRODis true.- With
<ClientRouter />, rely on GA4’s history-based page views or sendpage_viewonastro:page-load, not both.- Send custom events with
gtag('event', name, params)from any client script.- Set Consent Mode defaults before
gtag('config')if you need consent before tracking.
Step 1: get your GA4 measurement ID
In Google Analytics, go to Admin > Data streams, add a Web stream for your domain, and copy the Measurement ID. While you’re on that screen, open Enhanced measurement. It’s on by default and tracks scrolls, outbound clicks, site search, file downloads and video engagement without extra code. Keep it in mind for Step 4.
Store the ID in an environment variable so preview and production can differ:
# .env.production
PUBLIC_GA_ID=G-XXXXXXXXXX
Variables prefixed with PUBLIC_ are available in client code and templates. The ID isn’t secret, since it appears in your page source anyway, but keeping it in env means staging builds don’t send data to your production property. The environment variables guide covers .env file precedence.
Step 2: create a GoogleAnalytics component
---
// src/components/GoogleAnalytics.astro
const id = import.meta.env.PUBLIC_GA_ID;
const enabled = import.meta.env.PROD && Boolean(id);
---
{enabled && (
<>
<script is:inline async src={`https://www.googletagmanager.com/gtag/js?id=${id}`}></script>
<script is:inline define:vars={{ id }}>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
window.gtag = gtag;
gtag('js', new Date());
gtag('config', id);
</script>
</>
)}
Then add it to your base layout’s head:
---
// src/layouts/BaseLayout.astro
import GoogleAnalytics from '../components/GoogleAnalytics.astro';
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<GoogleAnalytics />
</head>
<body>
<slot />
</body>
</html>
Three details in that component matter:
is:inlinetells Astro to leave the script alone. Without it, Astro processes the<script>as a module, bundles it and changes when it runs, which breaks Google’s loader. The script tag guide explains Astro’s two script modes.define:varspasses the ID from the frontmatter into the inline script. It impliesis:inline, so the script is still written to the page as is.window.gtag = gtagmakes the function global. Astro wraps adefine:varsscript in its own function scope so the variables don’t leak, which also keepsgtaglocal unless you attach it towindow. Your other scripts need it there to send events.
Because the tag is wrapped in import.meta.env.PROD, astro dev never loads it, so your own testing doesn’t inflate the numbers. To check the tag locally, run npm run build && npm run preview, which uses the production build.
Step 3: verify it’s working
Open your deployed site, then in GA4 go to Reports > Realtime. Your visit should appear within a few seconds. For more detail, use Admin > DebugView with the Google Analytics Debugger browser extension, or add debug_mode: true to the config call temporarily:
gtag('config', id, { debug_mode: true });
In the browser’s network tab, requests to google-analytics.com/g/collect confirm that hits are being sent. If you see none, check that the build had PUBLIC_GA_ID set. A missing variable silently removes the tag, which is the intended behaviour in development but a common surprise in CI.
Step 4: page views with view transitions
A normal Astro site does a full page load on every navigation, and GA4 records a page view each time. Nothing more is needed.
If you use <ClientRouter />, navigation updates the URL with the History API without reloading, so the gtag snippet doesn’t run again. You have two options. Pick one, not both, or you’ll count every navigation twice.
Option A: let GA4 detect history changes. In Enhanced measurement > Page views > Show advanced settings, keep Page changes based on browser history events turned on. GA4 then records a page view whenever the URL changes through pushState. This is the zero-code option.
Option B: send page views yourself. Turn off the history-based setting, disable the automatic first page view, and send one on every astro:page-load:
---
// src/components/GoogleAnalytics.astro (manual page views)
const id = import.meta.env.PUBLIC_GA_ID;
---
{import.meta.env.PROD && id && (
<>
<script is:inline async src={`https://www.googletagmanager.com/gtag/js?id=${id}`}></script>
<script is:inline define:vars={{ id }}>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
window.gtag = gtag;
gtag('js', new Date());
gtag('config', id, { send_page_view: false });
document.addEventListener('astro:page-load', () => {
gtag('event', 'page_view', {
page_location: location.href,
page_title: document.title,
});
});
</script>
</>
)}
astro:page-load fires on the first load and after each client-side navigation, so every page is counted exactly once. Option B gives you control over the page title that’s sent, since document.title has already been updated when the event fires.
The head scripts run once, and the listener they register stays active for the whole visit, so you don’t need data-astro-rerun or transition:persist on them.
Step 5: send custom events
Enhanced measurement covers generic behaviour. For things specific to your site, like a newsletter signup or a theme preview click, send events from a client script:
---
// src/components/NewsletterForm.astro
---
<form id="newsletter" action="/api/subscribe" method="post">
<input type="email" name="email" required />
<button type="submit">Subscribe</button>
</form>
<script>
document.getElementById('newsletter')?.addEventListener('submit', () => {
window.gtag?.('event', 'sign_up', { method: 'newsletter' });
});
</script>
The optional call window.gtag?.() means the code doesn’t throw in development, where the tag isn’t loaded. Add a type declaration so TypeScript knows about it:
// src/env.d.ts
interface Window {
gtag?: (...args: unknown[]) => void;
dataLayer: unknown[];
}
GA4 has recommended event names such as sign_up, generate_lead and select_content. Using them where they fit gives you prebuilt reports. Mark the important ones as key events in Admin > Events.
Consent Mode and cookie banners
In the EEA, UK and some other regions, you generally need consent before setting analytics cookies. Google’s Consent Mode lets the tag load with storage denied, then update once the visitor accepts. Set the defaults before config:
// inside the inline script, before gtag('config', id)
gtag('consent', 'default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied',
});
When your banner’s accept button is clicked, update it:
// src/scripts/consent.ts
export function acceptAnalytics() {
window.gtag?.('consent', 'update', { analytics_storage: 'granted' });
localStorage.setItem('consent', 'granted');
}
On later visits, read the stored choice in the inline script and call the update before config. A consent management platform does the same thing with a UI and per-region rules. This is a technical pattern, not legal advice, so check what your jurisdiction requires.
If you’d rather avoid cookies and banners, a privacy-focused tool like Plausible, Fathom or Cloudflare Web Analytics may suit you better. The privacy-friendly analytics tip compares them.
Performance: should you use Partytown?
The gtag script is loaded with async, so it doesn’t block rendering, but it still runs on the main thread. @astrojs/partytown can move it to a web worker:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import partytown from '@astrojs/partytown';
export default defineConfig({
integrations: [partytown({ config: { forward: ['dataLayer.push', 'gtag'] } })],
});
Then change both scripts to type="text/partytown". Test carefully: events sent from your own main-thread code must go through the forwarded functions, and debugging becomes harder. For most sites, the plain async snippet is fine. The Partytown guide covers when it’s worth the trade-off.
If you manage several tags, such as GA4 plus ad pixels, consider Google Tag Manager on Astro instead, so marketing can change tags without a deploy. And if you’re starting a new site, every Astro theme ships a base layout where this component drops into the head.
FAQ
How do I add Google Analytics to an Astro site?
Paste the GA4 gtag snippet into your base layout’s <head> and add is:inline to both script tags. Better, wrap it in a component that reads the ID from PUBLIC_GA_ID and renders only in production builds.
Why isn’t Google Analytics tracking pages after navigation in Astro?
You’re probably using <ClientRouter />, which navigates without a full reload. Enable GA4’s history-based page views in Enhanced measurement, or send a page_view event on the astro:page-load event with automatic page views turned off.
Do I need an integration for Google Analytics in Astro?
No. GA4 is two script tags. An is:inline script in your layout is all Astro needs, and @astrojs/partytown is optional if you want to move the script off the main thread.
Can I use Google Analytics on a static Astro site?
Yes. GA4 runs entirely in the visitor’s browser and sends data to Google, so it works on static builds hosted on Cloudflare Pages, Netlify, Vercel or GitHub Pages with no server code.
Does Google Analytics slow down an Astro site?
It adds a third-party script that loads asynchronously, so it doesn’t block the first render, but it does use main-thread time. Loading it only in production and considering Partytown or a lighter analytics tool keeps the cost down.