Free auditStart free
GuideAstro · Analytics

Astro Google Analytics

Add the GA4 Google tag to an Astro site with is:inline scripts or the Partytown integration, keep the ID in an env variable, and confirm hits fire.

4 min
read
8
sources
Oct 28, 2026
updated
Scaplet Editorial Team
author
In one line

Add the Google tag to a shared layout's <head> in Astro using is:inline scripts, because Astro only bundles and processes script tags with no attributes other than src. To run it off the main thread, install @astrojs/partytown, set type="text/partytown" on the scripts, and forward dataLayer.push. Then confirm requests to googletagmanager.com in the Network tab.

30-second check

Where does your site stand?

Four quick questions, then a straight answer.

1/4Have you checked your own site for this?
Summarize this page withChatGPTClaudePerplexityGoogleAI Mode
01Your call

Pick the loading method first

If this fits

Inline script in the layout

  • Matches Google's own snippet, so Google's docs and Tag Assistant steps apply as written.
  • Fewest moving parts: no integration, no worker, no forwarding config.
  • Choose it when you want the simplest working setup and can accept the tag running on the main thread.
Or

Partytown integration

  • Astro describes Partytown as a way to relocate resource intensive third-party scripts into a web worker, off the main thread.
  • Partytown's docs say the forward config should add dataLayer.push so calls reach window.dataLayer.push.
  • Partytown's docs warn the automatic user_engagement event sent when a user leaves is not reliable from a web worker.

Google says to place its snippet immediately after the opening head tag on every page you want to measure, and notes that it recommends Google Tag Manager for deploying tags. In Astro, "every page" means one shared layout component that all pages use.

02Check it

Method 1: inline gtag.js in your layout

Astro processes a <script> tag with no attributes other than src: it bundles imports, makes it type="module", and may inline it. It does not process a script that has any other attribute, and is:inline opts out on purpose. Google's snippet depends on a global gtag() function, so mark both scripts is:inline and keep Astro's processing away from them.

The snippet mirrors the one in Google's setup guide, with the tag ID swapped for a variable. Astro says only variables prefixed with PUBLIC_ are available in client-side code, so a measurement ID in .env as PUBLIC_GA_ID=G-XXXXXXX works, and a non-prefixed name does not. A measurement ID is not a secret: it appears in the page source either way. define:vars on a script implies is:inline, per the Astro directives reference.

src/layouts/Layout.astro
---
const gaId = import.meta.env.PUBLIC_GA_ID;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    {gaId && (
      <>
        <script is:inline async src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}></script>
        <script is:inline define:vars={{ gaId }}>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', gaId);
        </script>
      </>
    )}
  </head>
  <body>
    <slot />
  </body>
</html>
03How it works

Method 2: Partytown

Head markup with Partytown
<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script type="text/partytown">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXX');
</script>
  1. 01

    Install the integration

    Run npx astro add partytown. Astro's integration page says it installs Partytown and enables it on all your pages. Manual setup adds partytown() to integrations in astro.config.*.

  2. 02

    Forward dataLayer.push

    In astro.config.mjs, pass partytown({ config: { forward: ['dataLayer.push'] } }). Astro's own example for this option is exactly dataLayer.push, and Partytown's Google Tag Manager page says the forward config should add it so calls reach window.dataLayer.push.

  3. 03

    Switch the script type

    Use type="text/partytown" on both scripts: the src script for https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE and the inline block that sets up dataLayer and calls gtag('config', ...). Partytown's page shows this pattern.

  4. 04

    Look for the proxy in the Network tab

    Astro says that with Partytown working you should see "the partytown proxy intercepting this request" in DevTools.

04Worth knowing

Pitfalls specific to Astro

Plain `<script>` is the wrong default

Astro bundles a script with no attributes and makes it type="module", so Google's snippet no longer runs as published. Add is:inline to both tags.

ClientRouter re-runs inline scripts

Astro warns that with <ClientRouter />, inline scripts can re-execute if a page is visited more than once or when a visitor navigates away and back. Put the Google tag in a layout and test with DevTools that you do not see duplicate config calls in the Network tab.

Page views on client-side navigation

Check DebugView after navigating between pages with the router. Google says page_view fires when config is called unless send_page_view is false, so verify what you actually get instead of assuming.

Do not leave `debug_mode` on

Google says to disable debug mode by excluding the parameter: setting it to false does not turn it off.

05How it works

Check it worked

  1. 1

    Network tab

    Open the deployed page in Chrome, open DevTools, go to Network, and refresh. Google says requests to googletagmanager.com mean the tag is firing, and Analytics hits go to google-analytics.com or analytics.google.com.

  2. 2

    Tag Assistant

    Go to tagassistant.google.com, click Add domain, enter the URL, and click Connect. Your tag ID should appear under Google tags found.

  3. 3

    DebugView or Realtime

    Google says the Tag Assistant adds a parameter that enables debug mode for your device, so DebugView shows your events in real time. The Realtime report lets you monitor activity as it happens. Remember DebugView will not show events when consent mode is on and users have not given consent for Analytics cookies.

Once data flows, connect search data too: the Astro SEO guides cover the rest of the setup.

Sources · 8

Every fact, linked and dated.

Official docs first. The date is when we last opened each page.
  • astro.build
  • qwik.dev
  • google.com
  1. 01@astrojs/partytown | Astro Docsdocs.astro.build · checked 2026-11-01
  2. 02Scripts and event handling | Astro Docsdocs.astro.build · checked 2026-11-01
  3. 03Template directives reference | Astro Docsdocs.astro.build · checked 2026-11-01
  4. 04Using environment variables | Astro Docsdocs.astro.build · checked 2026-11-01
  5. 05View transitions | Astro Docsdocs.astro.build · checked 2026-11-01
  6. 06Google Tag Manager | Partytownpartytown.qwik.dev · checked 2026-11-01
  7. 07Set up the Google tag with gtag.js | Google for Developersdevelopers.google.com · checked 2026-11-01
  8. 08Monitor events in DebugView | Analytics Helpsupport.google.com · checked 2026-11-01
Questions

Asked a lot.

3 questions people ask next, answered from the sources on this page.

01Do I need Partytown to use Google Analytics with Astro?

No. The inline Google tag in a layout works. Partytown is optional and moves the script to a web worker; its docs flag that the automatic user_engagement event is not reliable from a worker.

02Why is my gtag function undefined in Astro?

Check that both Google tag scripts have is:inline. Astro bundles scripts with no attributes other than src and makes them modules, so the snippet no longer runs as Google published it.

03Which environment variable prefix does Astro expose to the browser?

PUBLIC_. Astro's environment variables guide says only variables with that prefix are available in client-side code.

Free · 2 minutes

Tools point. Agencies advise. This one ships.

Run the free audit, then approve the fixes. Every change can be undone.

Free, no card60 secondsNobody will call you
  • 46 fixes shipped without a ticket Brightpipe
  • 0→7 ChatGPT citations in six weeks Paylane