🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Google Tag Manager: Setup, dataLayer and SPA Views

Astro Google Tag Manager setup: add the GTM head and noscript snippets as a component, push dataLayer events, track view transitions and keep GTM out of dev.

#Astro#Google Tag Manager#GTM#Analytics#dataLayer

To add Google Tag Manager to an Astro site, copy your container ID (it starts with GTM-), put the GTM loader script in the <head> of your base layout with <script is:inline>, and put the <noscript> iframe right after the opening <body> tag. Every tag you then configure in GTM (GA4, ad pixels, heatmaps) runs on every page without another deploy. The Astro Google Tag Manager setup is plain HTML in a component, and it works on static and server-rendered sites alike.

This guide wraps both snippets in reusable components, shows how to push events to the dataLayer from Astro scripts, and handles page views when you use <ClientRouter />.

Key Takeaways

  • GTM needs two snippets: the loader in <head> and a <noscript> iframe at the top of <body>.
  • Render the loader with is:inline and define:vars so Astro writes it to the page untouched.
  • Read the ID from PUBLIC_GTM_ID and render only when import.meta.env.PROD is true.
  • Push custom events with window.dataLayer.push({ event: 'name', ... }) and trigger tags on them in GTM.
  • With <ClientRouter />, push a virtual page view on astro:page-load or use GTM’s History Change trigger.

GTM or plain GA4: which do you need?

Google Tag Manager is a container that loads other tags. You install it once, then add, edit and publish tags from the GTM web interface. That’s useful when:

  • Marketing or analytics people need to add pixels without asking a developer.
  • You run several tags (GA4, Google Ads, LinkedIn, Meta, a heatmap tool) and want consent and triggers in one place.
  • You want versioning, preview mode and rollbacks for tag changes.

If all you need is GA4, GTM adds a layer without much benefit. The Astro Google Analytics guide shows the direct gtag install, which loads less code.

Step 1: create the container and store the ID

In Tag Manager, create an account and a Web container for your domain. The install dialog shows two snippets and your container ID. Store the ID in an env file:

# .env.production
PUBLIC_GTM_ID=GTM-XXXXXXX

The ID is visible in your page source, so it isn’t secret. Keeping it in env means staging and previews don’t fire your production tags. If you want typed variables, declare it with astro:env as shown in the environment variables guide.

Step 2: build the GTM components

GTM’s head snippet is a small loader that creates the dataLayer array and injects gtm.js. Put it in its own component:

---
// src/components/GtmHead.astro
const id = import.meta.env.PUBLIC_GTM_ID;
const enabled = import.meta.env.PROD && Boolean(id);
---
{enabled && (
  <script is:inline define:vars={{ id }}>
    (function (w, d, s, l, i) {
      w[l] = w[l] || [];
      w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
      var f = d.getElementsByTagName(s)[0],
        j = d.createElement(s),
        dl = l != 'dataLayer' ? '&l=' + l : '';
      j.async = true;
      j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
      f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', id);
  </script>
)}

The noscript fallback loads an iframe for browsers with JavaScript disabled:

---
// src/components/GtmBody.astro
const id = import.meta.env.PUBLIC_GTM_ID;
const enabled = import.meta.env.PROD && Boolean(id);
---
{enabled && (
  <noscript>
    <iframe
      src={`https://www.googletagmanager.com/ns.html?id=${id}`}
      height="0"
      width="0"
      style="display:none;visibility:hidden"
    ></iframe>
  </noscript>
)}

Add both to the base layout. Google asks for the head snippet as high in <head> as possible and the body snippet immediately after <body>:

---
// src/layouts/BaseLayout.astro
import GtmHead from '../components/GtmHead.astro';
import GtmBody from '../components/GtmBody.astro';
const { title } = Astro.props;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <GtmHead />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
  </head>
  <body>
    <GtmBody />
    <slot />
  </body>
</html>

is:inline is the important part. Astro normally processes <script> tags as modules and bundles them, which changes when and how they run. define:vars passes the container ID from the frontmatter and implies is:inline, so the loader reaches the browser as written. The script tag guide covers the two modes.

With the PROD guard, astro dev never loads GTM. To test locally, run npm run build && npm run preview.

Step 3: verify with Preview mode

In GTM, click Preview, enter your site’s URL, and Tag Assistant opens your site in a connected tab. You’ll see the container load, the built-in events (gtm.js, gtm.dom, gtm.load) and which tags fired on each. Nothing you configure goes live until you click Submit and publish a version.

If Tag Assistant can’t connect, check the page source for the gtm.js loader. A missing PUBLIC_GTM_ID at build time removes it silently, by design.

Step 4: push events to the dataLayer

The dataLayer is how your site talks to GTM. Push an object with an event key, then create a Custom Event trigger in GTM with the same name. Any tag can fire on it, and any extra keys become available as Data Layer Variables.

---
// src/components/ContactForm.astro
---
<form id="contact" action="/thanks/" method="get">
  <input name="email" type="email" required />
  <select name="topic">
    <option>Sales</option>
    <option>Support</option>
  </select>
  <button type="submit">Send</button>
</form>

<script>
  const form = document.getElementById('contact') as HTMLFormElement | null;
  form?.addEventListener('submit', () => {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'contact_submit',
      form_topic: new FormData(form).get('topic'),
    });
  });
</script>

Declare the global so TypeScript doesn’t complain:

// src/env.d.ts
interface Window {
  dataLayer: Record<string, unknown>[];
}

Because this is a bundled module script, it runs once per page load and works whether or not GTM is present. In development the pushes go into an array nobody reads, which is harmless.

You can also push page-level data from Astro at render time, such as the content category or author, so tags can use it:

---
// src/layouts/PostLayout.astro
const { category, author } = Astro.props;
---
<script is:inline define:vars={{ category, author }}>
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ content_category: category, content_author: author });
</script>

Place this before <GtmHead /> in the head if tags need the values on the very first event.

Step 5: page views with ClientRouter

Without <ClientRouter />, each navigation is a full page load, GTM reloads, and your GA4 tag sends a page view on its normal trigger. Nothing more is needed.

With <ClientRouter />, Astro swaps the page content and updates the URL with the History API. GTM stays loaded and doesn’t see a new page. Choose one approach:

Option A: History Change trigger. In GTM, create a trigger of type History Change and fire your page view tag on it in addition to the initial load. GTM detects pushState itself. This needs no code, but the page title in GTM’s variables can lag behind on some setups.

Option B: push a virtual page view. Add one listener to the layout:

---
// src/components/GtmPageView.astro
---
<script>
  let first = true;
  document.addEventListener('astro:page-load', () => {
    if (first) return void (first = false);
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'virtual_page_view',
      page_location: location.href,
      page_title: document.title,
    });
  });
</script>

astro:page-load fires on the first load and after each navigation. Skipping the first one avoids double counting, since GTM’s normal page view trigger already covers it. In GTM, create a Custom Event trigger for virtual_page_view and send a GA4 page_view event with the pushed page_location and page_title. Option B is more predictable because the title is read after Astro has swapped it.

Every tag in GTM is third-party JavaScript running on your pages, and the container makes it easy to add more. Two habits keep that under control:

  • Consent first. Use GTM’s Consent Mode settings or a consent management platform template so tags wait for consent where the law requires it. Set defaults before the container loads by pushing a consent default command through gtag, or let your CMP template handle it.
  • Audit the container. Review tags quarterly and remove ones nobody uses. A slow tag in GTM slows every page.

@astrojs/partytown can run scripts in a web worker, but GTM is a tricky candidate: it injects other tags that may need the DOM, and forwarding has to be configured for dataLayer.push. Many tags break in subtle ways. Try it only with careful testing, as described in the Partytown guide. For most sites, the async loader is the better trade-off.

If you’re starting a marketing site and want a layout that already separates head, body and page-level props, the technology and SaaS themes are built that way, so a GTM component drops straight in.

Troubleshooting

Tags fire twice on every navigation. You enabled both a History Change trigger and the virtual page view push. Keep one.

Events from your scripts never reach GTM. Check that the event name in dataLayer.push matches the Custom Event trigger exactly, including case. Tag Assistant lists every push, so you can compare.

GTM loads in development. The component checks import.meta.env.PROD. If you see GTM locally, you’re running astro preview on a production build, which is expected.

Content Security Policy blocks GTM. If you use Astro’s CSP support or set headers yourself, allow https://www.googletagmanager.com in script-src, plus the domains of the tags GTM loads. Inline loader scripts also need a hash or nonce. See Astro’s configuration reference for the security options in your version.

FAQ

How do I add Google Tag Manager to Astro?

Create a component that renders the GTM loader with <script is:inline define:vars={{ id }}> and include it near the top of <head> in your base layout. Add a second component with the <noscript> iframe right after <body>.

Do I need both the GTM head script and the noscript iframe?

The head script does the real work. The noscript iframe only runs for visitors with JavaScript disabled, so it’s optional, but Google recommends including it and it costs nothing for everyone else.

How do I track page views in GTM when Astro uses view transitions?

Either add a History Change trigger in GTM, or push a virtual_page_view event to the dataLayer on astro:page-load (skipping the first load) and fire your GA4 page view tag on it. Don’t use both.

Should I use Google Tag Manager or the GA4 gtag snippet on Astro?

Use the gtag snippet if GA4 is your only tag. Use GTM when you manage several tags, need marketing to change them without deploys, or want centralised consent handling.

Can I use Partytown with Google Tag Manager in Astro?

You can, with @astrojs/partytown and dataLayer.push forwarded, but many tags loaded by GTM expect main-thread DOM access and can break. Test every tag in Preview mode before relying on it.