Analytics: consentMode 'basic' keeps Google tags out until consent

Opt-in; the default stays 'advanced' (tag loads with denied signals).
shouldLoadGoogle holds the rule so it is testable without a DOM.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:05:14 +02:00
co-authored by Claude Opus 5.5
parent 0bfc509102
commit 9a72ebfaff
3 changed files with 66 additions and 6 deletions
+10 -2
View File
@@ -3,8 +3,10 @@
Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze
zgodą z modułu consent:
- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale
dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy.
- **Google (GA4 / GTM)** — przez Consent Mode v2. Domyślnie (`consentMode: 'advanced'`) tag
ładuje się od razu, ale dostaje decyzję odwiedzającego (przed zgodą: wszystko `denied`), zanim
cokolwiek zmierzy — Google dostaje wtedy pingi bez cookies. `consentMode: 'basic'` → **zero
żądań do Google przed zgodą** na analytics lub marketing (patrz niżej).
- **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** —
nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą
kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania.
@@ -104,6 +106,12 @@ w ipal-kit (core = engine).
## Jak działa Consent Mode
**Tryb `basic` vs `advanced`.** `<SiteProviders analytics={{ consentMode: 'basic' }}>` (albo
`<Analytics consentMode="basic" />`): skrypt `googletagmanager.com` nie ładuje się, dopóki
odwiedzający nie zgodzi się na analytics lub marketing — wymóg „zero tagów przed zgodą”. Kosztem
jest brak modelowania konwersji dla osób bez zgody. Domyślne `advanced` ładuje tag od razu z
sygnałami `denied`. Wybór trybu to decyzja klienta — zapisz ją w „Ustaleniach projektu”.
1. Przed załadowaniem tagu: `gtag('consent', 'default', …)` z zapisaną decyzją
odwiedzającego (albo wszystko `denied`, gdy jeszcze nie zdecydował).
2. Tag się ładuje i respektuje ten stan od pierwszego trafienia.
+37 -4
View File
@@ -40,6 +40,17 @@ function injectScript(src: string) {
}
export type AnalyticsProps = {
/**
* Google Consent Mode flavour.
* - `'advanced'` (default): the Google tag (GA4 / GTM) loads before the
* visitor decides, with every signal `denied`; Google gets cookieless
* pings and models conversions.
* - `'basic'`: no request to Google at all until the visitor grants analytics
* or marketing — "zero tags before consent", like the non-Google pixels.
* The Consent Mode default is still set first, so the tag starts with the
* stored choice.
*/
consentMode?: 'advanced' | 'basic'
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
@@ -58,6 +69,24 @@ export type AnalyticsProps = {
deferTimeoutMs?: number
} & AnalyticsConfig
/**
* Whether the Google tag may load now. Pure, so the consent rule is testable
* without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced'
* relies on the Consent Mode default and loads as soon as `ready`.
*/
export function shouldLoadGoogle({
consentMode,
ready,
state,
}: {
consentMode: 'advanced' | 'basic'
ready: boolean
state: { analytics?: boolean; marketing?: boolean }
}): boolean {
if (!ready) {return false}
return consentMode === 'advanced' || Boolean(state.analytics || state.marketing)
}
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
/** True once third-party tags may load (immediately, or per `defer` rules). */
@@ -101,7 +130,8 @@ function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* IDs are set. With `consentMode: 'basic'` the tag itself waits for an
* analytics or marketing grant.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
@@ -115,6 +145,7 @@ function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
export function Analytics(props: AnalyticsProps) {
const {
clarityProjectId,
consentMode = 'advanced',
defer = false,
deferTimeoutMs = 3500,
ga4MeasurementId,
@@ -139,9 +170,11 @@ export function Analytics(props: AnalyticsProps) {
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId, texts.version])
// --- Google: load once `ready`; Consent Mode handles gating ---
// --- Google: load once `ready` (and, in 'basic' mode, once consented);
// Consent Mode handles what the tag may store ---
const googleAllowed = shouldLoadGoogle({ consentMode, ready, state })
useEffect(() => {
if (!ready) {return}
if (!googleAllowed) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
@@ -152,7 +185,7 @@ export function Analytics(props: AnalyticsProps) {
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ready, ga4MeasurementId, gtmContainerId])
}, [googleAllowed, ga4MeasurementId, gtmContainerId])
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, test } from 'vitest'
import { shouldLoadGoogle } from '../src/modules/analytics/Analytics.js'
const none = { analytics: false, marketing: false }
describe("Google tag and consent", () => {
test("'basic': no Google request before an analytics or marketing grant", () => {
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: none })).toBe(false)
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, analytics: true } })).toBe(true)
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, marketing: true } })).toBe(true)
})
test("'advanced' (default) loads with denied signals; `defer` still holds both back", () => {
expect(shouldLoadGoogle({ consentMode: 'advanced', ready: true, state: none })).toBe(true)
expect(shouldLoadGoogle({ consentMode: 'advanced', ready: false, state: none })).toBe(false)
expect(shouldLoadGoogle({ consentMode: 'basic', ready: false, state: { analytics: true } })).toBe(false)
})
})