# 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.

Canonical: https://scaplet.com/seo/astro/google-analytics

Guide Astro Astro · 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 with [ChatGPT](https://chatgpt.com/?hints=search&q=Summarize%20https%3A%2F%2Fscaplet.com%2Fseo%2Fastro%2Fgoogle-analytics%20(%22Astro%20Google%20Analytics%22)%20in%205%20bullet%20points%2C%20then%20tell%20me%20the%20one%20thing%20I%20should%20do%20next.) [Claude](https://claude.ai/new?q=Summarize%20https%3A%2F%2Fscaplet.com%2Fseo%2Fastro%2Fgoogle-analytics%20(%22Astro%20Google%20Analytics%22)%20in%205%20bullet%20points%2C%20then%20tell%20me%20the%20one%20thing%20I%20should%20do%20next.) [Perplexity](https://www.perplexity.ai/search?q=Summarize%20https%3A%2F%2Fscaplet.com%2Fseo%2Fastro%2Fgoogle-analytics%20(%22Astro%20Google%20Analytics%22)%20in%205%20bullet%20points%2C%20then%20tell%20me%20the%20one%20thing%20I%20should%20do%20next.) [![Google](/logos/ai/google-color.svg)AI Mode](https://www.google.com/search?udm=50&q=Summarize%20https%3A%2F%2Fscaplet.com%2Fseo%2Fastro%2Fgoogle-analytics%20(%22Astro%20Google%20Analytics%22)%20in%205%20bullet%20points%2C%20then%20tell%20me%20the%20one%20thing%20I%20should%20do%20next.)

On this page

## 5 parts, 4 minutes.

1. [Pick the loading method first 01](#pick-the-loading-method-first)
2. [Method 1: inline gtag.js in your layout 02](#method-1-inline-gtag-js-in-your-layout)
3. [Method 2: Partytown 03](#method-2-partytown)
4. [Pitfalls specific to Astro 04](#pitfalls-specific-to-astro)
5. [Check it worked 05](#check-it-worked)

_01_Your call

## Pick the loading method first

If this fits

### Inline script in the layout

- Matches Google's own [snippet](/glossary/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](/glossary/google-tag-manager) for deploying tags. In Astro, "every page" means one shared layout component that all pages use.

_02_Check 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>
```

_03_How 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>
```

**Debug mode is on in dev and preview**Astro says Partytown debug mode is on by default in dev or preview mode and outputs detailed logs to the browser console. Set `config: { debug: false }` if you do not want that. Judge real performance on a production build.

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.

_04_Worth 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](/glossary/ga4-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.

_05_How 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](/glossary/consent-mode) is on and users have not given consent for Analytics cookies.

Once data flows, connect search data too: the [Astro SEO guides](/seo/astro) 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 Docs](https://docs.astro.build/en/guides/integrations-guide/partytown/) docs.astro.build · checked 2026-11-01
2. 02 [Scripts and event handling | Astro Docs](https://docs.astro.build/en/guides/client-side-scripts/) docs.astro.build · checked 2026-11-01
3. 03 [Template directives reference | Astro Docs](https://docs.astro.build/en/reference/directives-reference/) docs.astro.build · checked 2026-11-01
4. 04 [Using environment variables | Astro Docs](https://docs.astro.build/en/guides/environment-variables/) docs.astro.build · checked 2026-11-01
5. 05 [View transitions | Astro Docs](https://docs.astro.build/en/guides/view-transitions/) docs.astro.build · checked 2026-11-01
6. 06 [Google Tag Manager | Partytown](https://partytown.qwik.dev/google-tag-manager/) partytown.qwik.dev · checked 2026-11-01
7. 07 [Set up the Google tag with gtag.js | Google for Developers](https://developers.google.com/tag-platform/gtagjs/install) developers.google.com · checked 2026-11-01
8. 08 [Monitor events in DebugView | Analytics Help](https://support.google.com/analytics/answer/7201382) support.google.com · checked 2026-11-01

Questions

## Asked a lot.

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

_01_ Do 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.

_02_ Why 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.

_03_ Which 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.

## Keep learning

[All platform guides](/seo)

[Learn Astro SEO Frameworks](/seo/astro) [Related Google Analytics 4 Measurement](/glossary/google-analytics-4) [Read next Astro 404 page Frameworks](/seo/astro/404) [Do Run a free site audit Free, about two minutes](/site-audit)

Nearby in platform guides
[Astro SEO](/seo/astro)

More in Astro SEO
[Astro 404 page](/seo/astro/404) [Astro Google Analytics](/seo/astro/google-analytics) [Astro redirects](/seo/astro/redirects) [Astro robots.txt](/seo/astro/robots-txt) [Astro XML sitemap](/seo/astro/xml-sitemap)

Terms on this page
[Search snippet](/glossary/snippet) [Google Tag Manager](/glossary/google-tag-manager) [GA4 DebugView](/glossary/ga4-debugview) [Consent mode](/glossary/consent-mode)

Free · 2 minutes

## Tools point. Agencies advise. _This one ships._

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

[Audit my site free](/site-audit)

Free, no card 60 seconds Nobody will call you

- **46** fixes shipped without a ticket Brightpipe
- **0→7** ChatGPT citations in six weeks Paylane
