Skip to content

Google Tag Manager (GTM) and Stape

Google Tag Manager loads a web container that manages tags outside the application code. With Stape, the web container sends events to a server-side GTM (sGTM) container, and the container script can load from a first-party domain through the Custom Loader power-up.

The gtmProvider() factory loads the container and writes to the data layer. It does not use gtag.js. Configure GA4 and other tags in the GTM web container, and send them to Stape with the server container URL.

type GtmConfig = (
| { containerId: string } // loads https://www.googletagmanager.com/gtm.js?id=<containerId>
| { scriptSrc: string } // full container script URL, used unchanged
| { stapeLoader: { origin: string; loaderId: string; query: string } } // a Stape Custom Loader
) & {
enabled?: boolean;
consentMode?: "basic" | "advanced";
waitForUpdate?: number;
nonce?: string;
dataLayerName?: string;
hostnames?: string[];
excludePaths?: string[];
consentUpdateEvent?: string;
trackPageViews?: boolean;
userProperties?: Record<string, string>;
};

| Option | Required | Default | Description | |--------|----------|---------|-------------| | containerId | One of | - | Web container ID (GTM-XXXXXX). An empty string makes the provider a no-op. | | scriptSrc | One of | - | Full container script URL, used unchanged, for example https://<stape domain>/gtm.js?id=GTM-XXXXXX. | | stapeLoader | One of | - | The values of a Stape Custom Loader snippet. See Usage with Stape. | | enabled | No | true | Set false to keep the provider registered but make every method a no-op. | | consentMode | No | basic | See Consent. | | waitForUpdate | No | - | Adds wait_for_update to the consent default command. | | nonce | No | - | CSP nonce for the scripts that the provider adds. | | dataLayerName | No | dataLayer | Global data layer name. With containerId, the provider adds a custom name to the script URL as l=<name>. A scriptSrc URL or a Stape loader must already load the container on this data layer. | | hostnames | No | - | The hostnames where the provider runs, for example ["app.releaf.co.uk"]. On other hosts, the markup scripts and every method do nothing. Use it when one build serves more than one host. | | excludePaths | No | - | Paths where the provider does not run, for example ["/set-new-password"]. A path also excludes the pages below it, so /set-new-password excludes /set-new-password/abc. A trailing slash doesn’t matter. On these pages, the markup scripts and every method do nothing, so the container never sees their URLs. Use it for pages whose URL carries a token. | | consentUpdateEvent | No | - | The name of an event that the provider pushes after each consent update, for example releaf_consent_update. Tags that do not follow Google’s consent mode can trigger on it. | | trackPageViews | No | true | Set false when the container records page views itself. | | userProperties | No | {} | The identify() traits to push, as { traitName: "data_layer_name" }. Other traits are not pushed. |

| Mode | Markup | Events | |------|--------|--------| | basic | The consent default. | The service calls the provider only when analytics is granted (requiredConsent: ["analytics"]). init() then loads the container. | | advanced | The consent default, then the container. | The service calls the provider before and after consent. The container’s tags apply consent themselves. |

In advanced mode, the data layer gets every event before consent. Configure a consent check on every tag in the container: Google tags follow consent mode, and other tags can trigger on the consentUpdateEvent. The provider sends user_data only when adUserData is granted.

The consent default sets security_storage to granted, and personalization_storage to the value of functionality.

The provider pushes the consent update once when the saved choice loads (init()), then on each change. It does not push the same state twice.

| Method | Data layer entry | |--------|------------------| | init() | gtag("consent", "update", …) and the consentUpdateEvent, then { "gtm.start": …, event: "gtm.js" } and the container script, if it is not already on the page. | | trackEvent() | { event, ...params, event_id }. See Events. | | page() | { event: "page_view", page_title, page_location, page_path, page_referrer, event_id }, unless trackPageViews is false. A page view with the same meta.eventId as the last one is pushed once. An app can send the page view again when consent is granted, and in advanced mode the container already has it. | | identify() | { user_id, ...userProperties }, only with analytics consent. Without it, the provider keeps the call and pushes it when updateConsent() grants analytics. If analytics is withdrawn, it pushes these keys as undefined, and pushes them again if analytics is granted again. GTM keeps these keys in its data model for the rest of the page, so only the traits in userProperties are pushed. | | updateConsent() | gtag("consent", "update", …), then { event: <consentUpdateEvent>, consent_analytics, consent_advertising, consent_ad_user_data, consent_ad_personalization, consent_functionality }. | | reset() | A function that calls this.reset(), which clears every key in the GTM data model, for example user_id after a logout. |

The provider pushes consent commands as Arguments objects, as the official gtag() snippet does. GTM ignores consent commands that arrive as plain arrays or objects.

The provider does not define a global gtag. Both this provider and ga4Provider() use dataLayer by default, so with the defaults the GTM container also receives the GA4 provider’s commands. Set a different dataLayerName on one of them to keep them apart.

If the Google tag in the container sends its automatic page view, set trackPageViews to false, or GA4 counts each page view twice.

  • event_id. Each event push has an event_id: meta.eventId from trackEvent(), or a random ID. Server-side tags use it to deduplicate the browser and server copies of an event.
  • No values after the event. GTM keeps every pushed key until a later push changes it. Straight after each event, the provider pushes the event’s keys as undefined. GTM handles one push at a time, so the event’s tags read its values, and nothing after it does. Before an event with ecommerce, the provider also pushes { ecommerce: null }.
  • user_data. If params.user_data is an object with keys, and adUserData is granted, the provider pushes it. Otherwise it leaves it out. Use hashGtmUserData() to make it.
const userData = await hashGtmUserData({ email, phone });
// { sha256_email_address, sha256_phone_number, sha256_phone_number_digits }
  • The email is trimmed and lowercased before it is hashed.
  • The phone number must be in E.164 format, for example +447700900123. Google matches the hash of +447700900123, and Meta matches the hash of 447700900123, so the result has both. A number without a country code gets no phone keys.
  • Each hash is SHA-256, as lowercase hex.
  • Call it before trackEvent() and pass the result in the event data, so the plain email and phone never reach the analytics service.
  • It never rejects. Where Web Crypto is missing or fails, it returns an empty object.
  1. In Stape, enable Custom Loader for the sGTM container, with the same data layer name that the provider uses. Use the “Stape user ID” option.
  2. Copy three values from the generated snippet into stapeLoader: o is origin, i is loaderId and c is query. On Safari 16.4 and later, the provider loads the container from the Cookie Keeper path, as the snippet does.
  3. In the web GTM container, set the server container URL on the Google tag to the Stape tagging domain.
  4. Register the provider and map events under the gtm provider key:
const events = createEventRegistry().register(
createEventDefinition(accountCreated, {
providers: {
gtm: (data) => ({
event: "AC",
params: { user_data: data.userData },
}),
},
}),
);
export const analytics = createAnalyticsService({
app: "releaf",
events,
providers: [
gtmProvider({
stapeLoader: {
origin: "https://<stape domain>",
loaderId: "<i>",
query: "<c>",
},
consentMode: "advanced",
hostnames: ["app.releaf.co.uk"],
excludePaths: ["/set-new-password", "/impersonate-user"],
consentUpdateEvent: "releaf_consent_update",
trackPageViews: false,
}),
],
consent: { default: { analytics: "denied", advertising: "denied" } },
});
await analytics.trackEvent({
event: "account_created",
data: { userData: await hashGtmUserData({ email, phone }) },
meta: { eventId: `AC:${userId}` },
});

Render analytics.markup() in the document head, as for the GA4 provider, so that the consent default runs before the container loads.

Do not register ga4Provider() for a GA4 property that also has a GA4 tag in the GTM container. GA4 then receives each event twice.