Recipes

Tracking and Consent

Verification codes and tracking IDs that editors manage.

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 seo global. 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:

tenon.config.ts
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, the seo global is localized. Add localized: false to both groups to keep one value for all languages. Without localization, localized: false stops the server at startup.
  • A site without GTM adds other IDs the same way, like ga4 with pattern: "G-[A-Z0-9]+" or metaPixel with pattern: "[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:

  1. It sets Google's Consent Mode to "denied" first.
  2. 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:

src/tracking.ts
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:

src/layouts/Layout.astro
---
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. The if (!window.grantConsent) guard keeps the consent state.

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.