Tracking and Consent
This recipe adds verification codes and a Google Tag Manager ID to the seo settings, and renders them in your layout. Editors then change an ID in the admin, without a developer. The tracking script loads only after the visitor agrees.
Google Tag Manager (GTM) is the one ID most sites need. Once its container is on the site, Google Analytics, the Meta Pixel and other tags are added in GTM itself. Custom events, like a form submit, still need code: dataLayer.push({ event: "signup" }).
Before you start
- Your site uses the built-in
seoglobal. See Settings. - You have a consent banner, your own or a tool like Usercentrics or Cookiebot.
Add the fields
Extend the seo global with two groups. pattern rejects a typo before it reaches the page:
import { defineCms } from "tenoncms";
import { settings } from "tenoncms/presets";
const { seo } = settings();
export default defineCms({
// ...
settings: {
seo: {
...seo,
fields: {
...seo.fields,
verification: {
type: "group",
separator: true,
label: { en: "Verification", de: "Verifizierung" },
fields: {
google: { type: "text", label: "Google Search Console" },
bing: { type: "text", label: "Bing Webmaster Tools" },
},
},
tracking: {
type: "group",
separator: true,
label: { en: "Tracking", de: "Tracking" },
fields: {
gtm: {
type: "text",
label: "Google Tag Manager",
pattern: "GTM-[A-Z0-9]+",
placeholder: "GTM-XXXXXXX",
},
},
},
},
},
},
});
- Add fields for IDs only, never a field for script code. Anyone who can edit the settings could then run code on every page.
- With
localization, theseoglobal is localized. Addlocalized: falseto both groups to keep one value for all languages. Withoutlocalization,localized: falsestops the server at startup. - A site without GTM adds other IDs the same way, like
ga4withpattern: "G-[A-Z0-9]+"ormetaPixelwithpattern: "[0-9]+". - Verification through DNS needs no field. Use the meta tag when the site owner cannot change DNS.
Render them
In the EU, analytics and marketing scripts MUST NOT load before the visitor agrees. The code below follows that rule:
- It sets Google's Consent Mode to "denied" first.
- It loads GTM only after consent: through
grantConsent()in Astro and TanStack Start, or a consent trigger in Nuxt.
Your banner calls it once the visitor agrees, and again on every page load after that, because the banner stores the choice, not the snippet. A consent tool that sets Consent Mode itself has its own setup. Follow its docs.
Put the inline script in a file of its own:
const denied = {
ad_storage: "denied",
ad_user_data: "denied",
ad_personalization: "denied",
analytics_storage: "denied",
};
/** Inline script: sets the consent defaults and defines `grantConsent()`, which loads GTM. Safe to run twice. */
export function gtmScript(id: string) {
const src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(id)}`;
return `if (!window.grantConsent) {
window.dataLayer = window.dataLayer || [];
window.gtag = function () { dataLayer.push(arguments); };
gtag("consent", "default", ${JSON.stringify(denied)});
window.grantConsent = function (consent) {
gtag("consent", "update", consent);
if (document.getElementById("gtm")) return;
dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
document.head.append(Object.assign(document.createElement("script"), { id: "gtm", async: true, src: ${JSON.stringify(src)} }));
};
}`;
}
Render the tags in the layout:
---
import { gtmScript } from "../tracking";
const { verification, tracking } = await Astro.locals.tenon.getGlobal("seo");
---
<head>
{verification?.google && <meta name="google-site-verification" content={verification.google} />}
{verification?.bing && <meta name="msvalidate.01" content={verification.bing} />}
{tracking?.gtm && <script is:inline set:html={gtmScript(tracking.gtm)} />}
</head>
- A prerendered page keeps the IDs it had at build time. Rebuild after a change, for example with a deploy hook. A page that renders per request always has the current IDs.
- With
<ClientRouter />, inline scripts can run again after a navigation. Theif (!window.grantConsent)guard keeps the consent state.
Use Nuxt Scripts. It loads GTM, Google Analytics, the Meta Pixel and others with consent support, and takes the ID at runtime:
npx nuxt module add scripts
Create one consent trigger for the whole app:
export const scriptsConsent = useScriptTriggerConsent();
Render the tags in app.vue:
<script setup lang="ts">
const { data: seo } = await useTenon().getGlobal("seo");
const verification = seo.value?.verification;
const tracking = seo.value?.tracking;
useHead({
meta: [
{ name: "google-site-verification", content: verification?.google },
{ name: "msvalidate.01", content: verification?.bing },
].filter((tag) => tag.content),
});
const gtm = tracking?.gtm
? useScriptGoogleTagManager({
id: tracking.gtm,
defaultConsent: {
ad_storage: "denied",
ad_user_data: "denied",
ad_personalization: "denied",
analytics_storage: "denied",
},
scriptOptions: { trigger: scriptsConsent },
})
: undefined;
function acceptAll() {
scriptsConsent.accept();
// `consent` is undefined during SSR.
gtm?.consent?.update({
ad_storage: "granted",
ad_user_data: "granted",
ad_personalization: "granted",
analytics_storage: "granted",
});
}
</script>
- Pass
scriptOptions: { trigger: scriptsConsent }to every call of the same script. One call without it loads the script before consent. - Without GTM,
useScriptGoogleAnalytics({ id })anduseScriptMetaPixel({ id, defaultConsent: "denied" })work the same way.
Put the inline script in a file of its own:
const denied = {
ad_storage: "denied",
ad_user_data: "denied",
ad_personalization: "denied",
analytics_storage: "denied",
};
/** Inline script: sets the consent defaults and defines `grantConsent()`, which loads GTM. Safe to run twice. */
export function gtmScript(id: string) {
const src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(id)}`;
return `if (!window.grantConsent) {
window.dataLayer = window.dataLayer || [];
window.gtag = function () { dataLayer.push(arguments); };
gtag("consent", "default", ${JSON.stringify(denied)});
window.grantConsent = function (consent) {
gtag("consent", "update", consent);
if (document.getElementById("gtm")) return;
dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
document.head.append(Object.assign(document.createElement("script"), { id: "gtm", async: true, src: ${JSON.stringify(src)} }));
};
}`;
}
Read the settings in the root route, and return the tags from head:
import { createRootRoute } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
import cms from "../../tenon.config";
import { gtmScript } from "../tracking";
const getSeo = createServerFn().handler(() => cms.getGlobal("seo"));
export const Route = createRootRoute({
loader: () => getSeo(),
head: ({ loaderData }) => {
const verification = loaderData?.verification;
const tracking = loaderData?.tracking;
return {
meta: [
verification?.google && { name: "google-site-verification", content: verification.google },
verification?.bing && { name: "msvalidate.01", content: verification.bing },
].filter((tag) => !!tag),
scripts: tracking?.gtm ? [{ children: gtmScript(tracking.gtm) }] : [],
};
},
});
<HeadContent /> in the root component renders both.
In Astro and TanStack Start, the banner then calls grantConsent() with what the visitor allowed:
grantConsent({
analytics_storage: "granted",
ad_storage: "granted",
ad_user_data: "granted",
ad_personalization: "granted",
});
Count page views
Nuxt, TanStack Start and Astro with <ClientRouter /> change pages without a full load. The script loads once and counts the later pages itself:
- Google Analytics 4 counts history changes by default, as part of "enhanced measurement".
- In GTM, fire page view tags on the built-in History Change trigger.
- The Meta Pixel counts history changes by itself.
Send your own page views only when these are off, or a page counts twice.
Related resources
- Settings: extend or remove the
generalandseoglobals. - Pages and SEO: the head tags that read the settings.
- Rebuild on publish: rebuild a prerendered site after a change.
- Localization: localized globals and
localized: false.