From 7662fcb6e7161920bb65fee7963e36d2ed14a325 Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:38:44 -0500 Subject: [PATCH] fix(analytics): skip PostHog when the browser sends DNT or GPC posthog-js is_capturing() returns true under cookieless_mode always before it checks respect_dnt, so DNT and GPC visitors were still tracked. Skip posthog.init, the error listeners and pageviews when the browser opts out, and drop events in before_send as a second guard. --- frontend/instrumentation-client.ts | 15 ++++++-- frontend/lib/posthog-privacy.ts | 29 ++++++++++++++++ frontend/test/posthog-source.test.mjs | 21 ++++++++++++ frontend/test/posthog.test.ts | 49 +++++++++++++++++++++++++++ 4 files changed, 111 insertions(+), 3 deletions(-) diff --git a/frontend/instrumentation-client.ts b/frontend/instrumentation-client.ts index e28cd7b..e79e44e 100644 --- a/frontend/instrumentation-client.ts +++ b/frontend/instrumentation-client.ts @@ -1,5 +1,6 @@ import posthog from "posthog-js"; import { + browserRequestsNoTracking, classifyClientErrorName, getPostHogConfig, sanitizeEvent, @@ -12,6 +13,11 @@ const posthogConfig = getPostHogConfig({ NEXT_PUBLIC_POSTHOG_UI_HOST: process.env.NEXT_PUBLIC_POSTHOG_UI_HOST, }); +// Computed once. posthog-js treats cookieless_mode "always" as capturing before +// it checks respect_dnt, so DNT and GPC visitors never get posthog.init at all. +const trackingOptedOut = + typeof window !== "undefined" && browserRequestsNoTracking(window.navigator, window); + function capturePageview(url: string) { posthog.capture("$pageview", { path: sanitizeRoute(url) }); } @@ -31,7 +37,7 @@ function captureClientError(errorKind: "error" | "unhandled_rejection", cause: u }); } -if (typeof window !== "undefined" && posthogConfig) { +if (typeof window !== "undefined" && posthogConfig && !trackingOptedOut) { posthog.init(posthogConfig.token, { api_host: posthogConfig.apiHost, ui_host: posthogConfig.uiHost, @@ -77,7 +83,10 @@ if (typeof window !== "undefined" && posthogConfig) { web_vitals_allowed_metrics: ["CLS", "FCP", "INP", "LCP"], web_vitals_attribution: false, }, - before_send: (event) => sanitizeEvent(event) as typeof event | null, + before_send: (event) => + browserRequestsNoTracking(window.navigator, window) + ? null + : (sanitizeEvent(event) as typeof event | null), }); window.addEventListener("error", (event) => captureClientError("error", event.error)); @@ -89,5 +98,5 @@ if (typeof window !== "undefined" && posthogConfig) { } export function onRouterTransitionStart(url: string) { - if (typeof window !== "undefined" && posthogConfig) capturePageview(url); + if (typeof window !== "undefined" && posthogConfig && !trackingOptedOut) capturePageview(url); } diff --git a/frontend/lib/posthog-privacy.ts b/frontend/lib/posthog-privacy.ts index e31cee7..2a39065 100644 --- a/frontend/lib/posthog-privacy.ts +++ b/frontend/lib/posthog-privacy.ts @@ -89,6 +89,35 @@ export function getPostHogConfig(env: PostHogEnvironment) { return { token, apiHost: POSTHOG_API_HOST, uiHost: POSTHOG_UI_HOST } as const; } +function readSignal(source: unknown, key: string): unknown { + if (source === null || (typeof source !== "object" && typeof source !== "function")) { + return undefined; + } + try { + return (source as Record)[key]; + } catch { + return undefined; + } +} + +function isYesLike(value: unknown, accepted: readonly string[]): boolean { + if (value === true) return true; + return typeof value === "string" && accepted.includes(value.toLowerCase()); +} + +// posthog-js's is_capturing() returns true under cookieless_mode "always" +// before it consults respect_dnt, so the browser's opt-out signals have to be +// checked here instead. A throwing getter counts as no signal. +export function browserRequestsNoTracking(nav: unknown, win?: unknown): boolean { + const dnt = ["1", "yes"] as const; + return ( + isYesLike(readSignal(nav, "doNotTrack"), dnt) || + isYesLike(readSignal(nav, "msDoNotTrack"), dnt) || + isYesLike(readSignal(win, "doNotTrack"), dnt) || + isYesLike(readSignal(nav, "globalPrivacyControl"), ["1", "true", "yes"]) + ); +} + export function sanitizeRoute(input: unknown): string { if (typeof input !== "string" || /^[a-z][a-z\d+.-]*:/i.test(input) || input.startsWith("//")) { return OTHER_PATH; diff --git a/frontend/test/posthog-source.test.mjs b/frontend/test/posthog-source.test.mjs index eed3a42..7a3f977 100644 --- a/frontend/test/posthog-source.test.mjs +++ b/frontend/test/posthog-source.test.mjs @@ -135,3 +135,24 @@ test("newsletter submissions report a fixed result and error class only", async assert.equal(calls.length, 3); for (const [call] of calls) assert.doesNotMatch(call, /email|message|data\./iu); }); + +test("init, listeners and pageviews sit behind the DNT/GPC guard, and before_send re-checks it", async () => { + const instrumentation = await read("instrumentation-client.ts"); + assert.match( + instrumentation, + /const trackingOptedOut =[\s\S]*?browserRequestsNoTracking\(window\.navigator, window\)/u, + ); + assert.match( + instrumentation, + /if \(typeof window !== "undefined" && posthogConfig && !trackingOptedOut\) \{\s*posthog\.init\(/u, + ); + assert.match( + instrumentation, + /onRouterTransitionStart\(url: string\) \{\s*if \(typeof window !== "undefined" && posthogConfig && !trackingOptedOut\)/u, + ); + const beforeSend = + instrumentation.match(/before_send: \(event\) =>[\s\S]*?\n\s*\}\);/u)?.[0] ?? ""; + assert.match(beforeSend, /browserRequestsNoTracking\(window\.navigator, window\)/u); + assert.match(beforeSend, /\? null/u); + assert.match(instrumentation, /respect_dnt: true/u); +}); diff --git a/frontend/test/posthog.test.ts b/frontend/test/posthog.test.ts index 22746f3..e866a03 100644 --- a/frontend/test/posthog.test.ts +++ b/frontend/test/posthog.test.ts @@ -52,6 +52,7 @@ import { type TestContext, test } from "node:test"; import { ALLOWED_CTA_IDS, ALLOWED_ROUTES, + browserRequestsNoTracking, classifyClientErrorName, getPostHogConfig, sanitizeEvent, @@ -864,3 +865,51 @@ test("the public PostHog pipeline stops events rejected by before_send", (t) => const capture = createSdkCapture(t); assert.equal(capture({ event: "private fixture", properties: ENVELOPE }), undefined); }); + +test("browser opt-out signals are detected", () => { + assert.equal(browserRequestsNoTracking({ doNotTrack: "1" }), true); + assert.equal(browserRequestsNoTracking({ doNotTrack: "yes" }), true); + assert.equal(browserRequestsNoTracking({ doNotTrack: "YES" }), true); + assert.equal(browserRequestsNoTracking({ msDoNotTrack: "1" }), true); + assert.equal(browserRequestsNoTracking({}, { doNotTrack: "1" }), true); + assert.equal(browserRequestsNoTracking({}, { doNotTrack: true }), true); + assert.equal(browserRequestsNoTracking({ globalPrivacyControl: true }), true); + assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "1" }), true); + assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "true" }), true); +}); + +test("browsers without an opt-out signal are not flagged", () => { + for (const value of ["0", "unspecified", "no", "", null, undefined, 0, false]) { + assert.equal(browserRequestsNoTracking({ doNotTrack: value }), false, String(value)); + assert.equal(browserRequestsNoTracking({}, { doNotTrack: value }), false, String(value)); + } + assert.equal(browserRequestsNoTracking({ globalPrivacyControl: false }), false); + assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "false" }), false); + assert.equal(browserRequestsNoTracking({}), false); + assert.equal(browserRequestsNoTracking(undefined), false); + assert.equal(browserRequestsNoTracking(null, null), false); + assert.equal(browserRequestsNoTracking("navigator", 42), false); +}); + +test("a throwing signal getter counts as no signal unless another says yes", () => { + const throwing = { + get doNotTrack(): string { + throw new Error("blocked"); + }, + }; + assert.equal(browserRequestsNoTracking(throwing), false); + assert.equal(browserRequestsNoTracking(throwing, throwing), false); + assert.equal(browserRequestsNoTracking(throwing, { doNotTrack: "1" }), true); + const gpc = Object.defineProperties( + {}, + { + doNotTrack: { + get() { + throw new Error("blocked"); + }, + }, + globalPrivacyControl: { value: true }, + }, + ); + assert.equal(browserRequestsNoTracking(gpc), true); +});