A zero-component Astro integration for Google Tag Manager (GTM).
Easily inject Google Tag Manager snippets into your Astro site. Supports Astro v5,v6 and v7. Works seamlessly with View Transitions (clientRouter).
Instead of manually adding GTM <script> and <noscript> tags to every page, astro-gtm-lite hooks into Astro's build pipeline and injects the official Google Tag Manager snippets automatically — no layout edits required.
npm install astro-gtm-liteAdd it once in astro.config.mjs and forget about it:
import { defineConfig } from "astro/config";
import gtm from "astro-gtm-lite";
export default defineConfig({
integrations: [
gtm({
id: "GTM-XXXXXX",
}),
],
});The script is injected automatically into every page — no layout edits required.
Note: GTM is disabled during
astro devby default. SetdevMode: trueif you want to test GTM in development.
astro-gtm-lite works seamlessly with and without Astro View Transitions.
On each client-side navigation, a virtualPageview event is pushed to dataLayer with the updated page path and title. The astro:after-swap event is used, which fires immediately after the DOM is swapped — perfect for analytics tracking.
To track these virtual page views in GTM, create a Custom Event trigger with event name virtualPageview, and use Data Layer Variables for virtualPagePath and virtualPageTitle to populate your GA4 / Universal Analytics tags.
| Option | Type | Default | Description |
|---|---|---|---|
id |
string |
required | Your GTM container ID (GTM-XXXXXX) |
enable |
boolean |
true |
Globally toggle GTM injection on/off |
devMode |
boolean |
false |
Inject snippets during astro dev |
dataLayerName |
string |
"dataLayer" |
Rename the global dataLayer variable |
domain |
string |
"https://www.googletagmanager.com" |
Self-hosting or proxy domain |
idis strictly validated and must match the patternGTM-XXXXXX(alphanumeric suffix, case-insensitive).domainmust be a valid URL withhttp:orhttps:protocol.
If you prefer the classic component approach, import it directly:
---
import Gtm from "astro-gtm-lite/component";
---
<head>
<Gtm id="GTM-XXXXXX" />
</head>You can also conditionally disable it:
<Gtm id="GTM-XXXXXX" enable={false} />