Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
import { buildSidebarFromToc } from './sidebar';
import { getPlatformHead } from './platform';
import type { HeadEntry, PlatformKey, NavLang } from './platform.ts';
import { getGtmContainerId } from './lib/platform-context.js';
import { remarkEnvVars } from './plugins/remark-env-vars';
import { remarkMdLinks } from './plugins/remark-md-links';
import { remarkHtmlTransforms } from './plugins/remark-html-transforms';
Expand Down Expand Up @@ -667,6 +668,16 @@ export function createDocsSite(options: CreateDocsSiteOptions = {} as CreateDocs
process.env.DOCS_PLATFORM = platform;
}

// Google Tag Manager — first in <head>, as high as possible after the
// mandatory charset/viewport/title tags rendered by DocsLayout. Container ID
// is resolved per build mode (production vs. staging/development); see
// `getGtmContainerId()` for the resolution order.
const gtmContainerId = getGtmContainerId();
const gtmHead: HeadEntry[] = [{
tag: 'script',
content: `(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','${gtmContainerId}');`,
}];

// Platform CDN entries come first so site-specific `head` entries can override.
const platformHead = platform ? getPlatformHead(platform, navLang) : [];

Expand Down Expand Up @@ -755,7 +766,7 @@ export function createDocsSite(options: CreateDocsSiteOptions = {} as CreateDocs
productLinks,
packages,
selectedPackage,
head: [...platformHead, ...codeViewHead, ...head],
head: [...gtmHead, ...platformHead, ...codeViewHead, ...head],
}),
...(base ? [createBasePrependIntegration(base)] : []),
...extraIntegrations,
Expand Down
25 changes: 25 additions & 0 deletions src/lib/platform-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,28 @@ export function getEnvVars(): Record<string, string> {

return _env!;
}

/** Built-in Google Tag Manager container IDs, keyed by build mode. */
const GTM_CONTAINER_ID_DEFAULTS: Record<string, string> = {
production: 'GTM-T65CF7',
staging: 'GTM-NCKNPN',
development: 'GTM-NCKNPN',
};

/**
* Resolves the Google Tag Manager container ID for the current build.
*
* Resolution order:
* 1. `GTM_CONTAINER_ID` env var — explicit override.
* 2. `GTMContainerId` in the resolved `environment.json` (per-mode, per-locale).
* 3. Built-in default for the current build mode — production vs. staging/development.
*/
export function getGtmContainerId(): string {
if (process.env.GTM_CONTAINER_ID) return process.env.GTM_CONTAINER_ID;

const fromEnvJson = getEnvVars().GTMContainerId;
if (fromEnvJson) return fromEnvJson;

const mode = getBuildMode();
return GTM_CONTAINER_ID_DEFAULTS[mode] ?? GTM_CONTAINER_ID_DEFAULTS.development;
}
26 changes: 23 additions & 3 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import { defineMiddleware } from 'astro:middleware';
import { getPlatformContext, getEnvVars } from './lib/platform-context.js';
import { getPlatformContext, getEnvVars, getGtmContainerId } from './lib/platform-context.js';

export const onRequest = defineMiddleware((ctx, next) => {
export const onRequest = defineMiddleware(async (ctx, next) => {
ctx.locals.platformContext = getPlatformContext();
ctx.locals.envVars = getEnvVars();
return next();

const response = await next();

// Only rewrite HTML documents — skip .md/.txt/.xml endpoints and static assets.
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('text/html')) return response;

const html = await response.text();
Comment thread
viktorkombov marked this conversation as resolved.
if (!/<body[^>]*>/i.test(html)) return response;

const gtmNoscript = `<!-- Google Tag Manager (noscript) --><noscript><iframe src="https://www.googletagmanager.com/ns.html?id=${getGtmContainerId()}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript><!-- End Google Tag Manager (noscript) -->`;
const updated = html.replace(/<body([^>]*)>/i, `<body$1>${gtmNoscript}`);

const headers = new Headers(response.headers);
headers.delete('content-length');

return new Response(updated, {
status: response.status,
statusText: response.statusText,
headers,
});
});
Loading