Files
ipal-kit/docs/analytics.md
T
Radosław SmolińskiandClaude Opus 5.5 f5c53e4523 Consent compliance: docs, agent guide, skills, changelog, shared behaviour spec, browser check, reference e2e
- docs/consent.md: compliance defaults, Global Privacy Control, withdrawal, consent log on by default and the SQL
  migration; no more "UODO requirement" or "GPC not needed". docs/analytics.md: what Consent Mode advanced sends.
- docs/consent-behaviour-spec.md: the behaviour IAPL and IAWL share, with the 13-item test list.
- CHANGELOG 1.17.0: the SQL migration first, a before → after table for an existing site.
- AGENT.md, iapl-setup / iapl-upgrade / iapl-reference / iapl-consent-check, PROGRAMISTA item 78; reference skills copy.
- iapl-consent-check: Global Privacy Control, equal prominence and withdrawal runs; Google asset warnings.
- Reference site uses the new defaults; e2e for GPC, a stale grant, equal prominence, withdrawal; e2e:built runs every
  consent test in both bundlers. YouTubeEmbed warns in development without a poster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:48:19 +01:00

258 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# analytics
Loads the analytics and marketing tags entered in the admin panel, each one
according to the consent from the consent module:
- **Google (GA4 / GTM)** — through Consent Mode v2. The tag always gets a
`consent default` first, with the visitor's stored decision (before a decision:
everything `denied`). Then it depends on `consentMode`:
- `'advanced'` (default): the `googletagmanager.com` script loads **right away,
also before consent**. With `denied`, Google stores no cookies (`_ga`), but it
sends cookieless pings — this is **not** "zero requests before consent" (what they carry: below).
Exception since 1.17.0: a visitor whose browser sends **Global Privacy Control** gets no Google request until
they grant analytics or marketing ([consent.md](./consent.md#global-privacy-control-1170)).
- `'basic'`: **zero requests to Google before consent** — the script waits until
the visitor grants analytics or marketing (see "How Consent Mode works" below).
- **Others (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** —
they have no Consent Mode, so they load **only after consent** for their
category. They react live: click "Accept" → the tag starts without a reload; withdraw → Meta, TikTok and Clarity
are told at once (1.17.0). Clarity also gets its own consent signal (`consentv2`) when it loads.
## Config
No options in `payload.config` — the plugin reads the IDs from the **Site
Integrations** global (Settings → Site integrations):
| Field (`name`) | Format (validated) | Consent category |
|---|---|---|
| GA4 Measurement ID (`ga4MeasurementId`) | `G-` + 4–20 `[A-Z0-9]` | Consent Mode (analytics_storage) |
| GTM Container ID (`gtmContainerId`) | `GTM-` + 4–12 `[A-Z0-9]` | Consent Mode (all signals) |
| Meta Pixel ID (`metaPixelId`) | 5–20 digits | **marketing** |
| Microsoft Clarity Project ID (`clarityProjectId`) | 5–20 characters `[a-z0-9]` | **analytics** |
| LinkedIn Partner ID (`linkedInPartnerId`) | 3–12 digits | **marketing** |
| TikTok Pixel ID (`tiktokPixelId`) | 10–30 characters `[A-Z0-9]` | **marketing** |
GA4 + GTM set at the same time → GTM wins (GA4 is then not loaded separately).
Empty field = the tag does not load. The format is checked on save in the panel,
and `getAnalyticsConfig` also trims spaces and returns `null` for an ID in a
wrong format (e.g. from an import) — such a tag does not load.
All these IDs are public (they are visible in the page source).
`getAnalyticsConfig` reads only them, so secrets (Turnstile, SMTP) cannot leak.
### Pixel in the panel or in GTM?
**One or the other, never both** — otherwise every event is counted twice. The
rule:
- Client without GTM / simple site → enter the Pixel ID in the panel (simplest,
consent handled automatically).
- Client has an agency/marketer who manages tags in GTM → leave the Pixel field
empty; the Pixel is configured in GTM with an `ad_storage` condition (see the
section "Meta Pixel via GTM" below).
### Conversion events (non-Google)
`Analytics` sends only `PageView` (Meta) / `ttq.page()` (TikTok) — **once, when
the tag loads**; Next.js client-side navigation does not generate more
PageViews. You call conversions (e.g. Lead after a form) yourself — the globals
exist only after consent, so always with a guard:
```ts
window.fbq?.('track', 'Lead') // Meta
window.ttq?.track('SubmitForm') // TikTok
window.lintrk?.('track', { conversion_id: 123 }) // LinkedIn
```
The low-level loaders (`loadMetaPixel`, `loadClarity`, `loadLinkedIn`,
`loadTikTok`) are exported from `/client`, but normally you do not need them —
NEVER call them in a way that skips consent.
## Front
In the locale layout, **inside `ConsentProvider`**:
```tsx
import { getAnalyticsConfig } from '@intecion/ipal-kit'
import { ConsentProvider, CookieBanner, Analytics } from '@intecion/ipal-kit/client'
export default async function LocaleLayout({ children, params }) {
const payload = await getPayload({ config })
const analytics = await getAnalyticsConfig(payload) // server
return (
<ConsentProvider texts={texts}>
{children}
<CookieBanner />
<Analytics {...analytics} />
</ConsentProvider>
)
}
```
With `SiteProviders` (`/rsc`) you do not mount it yourself — options go through
`<SiteProviders analytics={{ consentMode, defer, deferTimeoutMs }}>` (`false` = no tags).
`Analytics` renders nothing — it injects scripts. Mount it once, high in the
tree.
| Prop | Type | Default | Description |
|---|---|---|---|
| `ga4MeasurementId`, `gtmContainerId`, `metaPixelId`, `clarityProjectId`, `linkedInPartnerId`, `tiktokPixelId` | `string \| null` | — | from `getAnalyticsConfig` (`AnalyticsConfig`) |
| `consentMode` | `'advanced' \| 'basic'` | `'advanced'` | when the Google tag may load (below) |
| `defer` | `boolean` | `false` | Core Web Vitals mode (below) |
| `deferTimeoutMs` | `number` | `3500` | fallback after `load`, ms |
**It must be inside `ConsentProvider`** (since 1.7.12 it reads the consent state
live — outside the provider it throws a context error).
## Core Web Vitals mode — `defer` (optional)
```tsx
<Analytics {...analytics} defer /> // default 3500 ms
<Analytics {...analytics} defer deferTimeoutMs={5000} />
```
All tags (GA4/GTM and pixels) load from the network only on the **first
interaction** (scroll, click, touch, key) or `deferTimeoutMs` after `load`,
whichever comes first. ~100+ KiB of JS drops out of the FCP/LCP window.
Defer changes **when**, never **whether**:
- the default Consent Mode state is still sent right away (it is only a push to
dataLayer, no network traffic), so GA never starts without it;
- non-Google pixels still need consent for their category;
- with `consentMode: 'basic'` the Google tag waits for both: consent and the
defer moment.
Cost: visitors who leave before interacting and before the timeout are not
counted (slightly fewer sessions in GA). `defer` is off by default.
Report missing options to IAPL (core = engine) — a copy of the component in
the project does not get fixes from updates.
## How Consent Mode works
**`basic` vs `advanced` mode.** `<SiteProviders analytics={{ consentMode: 'basic' }}>` (or
`<Analytics consentMode="basic" />`): the `googletagmanager.com` script does not load until the
visitor consents to analytics or marketing — the "zero tags before consent" requirement. The cost is
no conversion modelling for visitors without consent. The default `advanced` loads the tag right away
with `denied` signals. In both modes the Consent Mode default is set first. The mode is the client's
decision — record it in `AGENTS.md` → "Project decisions".
**What `advanced` sends before consent** (Google's documentation): the Google tag script is downloaded from
`googletagmanager.com`, and while the signals are `denied` it sends cookieless pings to Google — the timestamp,
user agent and referrer the browser adds to any request, whether the page or a previous one carried an ad-click id,
the consent state, and a random number per page load. Every request carries the visitor's IP address (Google says
Ads truncates it while `ad_storage` is denied and Analytics does not log it). No cookie is read or written. Google
uses the pings for conversion and behaviour modelling — which needs volume: GA4 about 1,000 events a day with
analytics denied for 7 days, Google Ads 700 ad clicks in 7 days per country — so on a small site the pings often buy
nothing. Under the EDPB's guidelines on the technical scope of ePrivacy art. 5(3) (2/2023) a script that makes the
browser send information is in scope whether or not a cookie is involved; no authority has ruled on Consent Mode by
name. `'basic'` sends nothing before consent. `ads_data_redaction` is set with the default (since 1.17.0).
The rule itself is `shouldLoadGoogle({ consentMode, ready, state, gpc? })` — a pure function (no React, no DOM;
`gpc`: Global Privacy Control applies, then `advanced` waits like `basic`)
exported from `@intecion/ipal-kit/client` and `@intecion/ipal-kit`. Use it for your own Google-dependent
code (a Maps embed, a YouTube player with Google Ads), so it follows the same consent rule as `<Analytics>`:
```ts
import { shouldLoadGoogle } from '@intecion/ipal-kit/client'
const allowed = shouldLoadGoogle({ consentMode: 'basic', ready: true, state: consent })
```
1. Before the tag loads: `gtag('consent', 'default', { …, wait_for_update: 500 })`
with the visitor's stored decision (or everything `denied` when they have not
decided yet or the consent is from another policy version — `texts.version`).
2. The tag loads (`advanced`: right away; `basic`: after consent for analytics or
marketing) and respects that state from the first hit.
3. Click in the banner → `gtag('consent', 'update', …)` → tags react immediately.
Withdrawing consent (true → false) deletes the category's cookies (`_ga*`, `_fbp`,
`_clck`, `_ttp`, … — see [consent.md](./consent.md)) and its listed storage keys, sends an `update` to
Google, and tells the non-Google tags already on the page (1.17.0): Meta `fbq('consent', 'revoke')`, TikTok
`ttq.revokeConsent()`, Clarity `clarity('consent', false)`. A script cannot be unloaded; LinkedIn Insight has no
consent call and stops with the next page load. A Google tag already loaded in `basic` mode is governed by the
Consent Mode `update` from then on.
Mapping of categories to Google signals:
| Category | Signals |
|---|---|
| analytics | `analytics_storage` |
| marketing | `ad_storage`, `ad_user_data`, `ad_personalization` |
| functional | `functionality_storage`, `personalization_storage` |
| necessary | `security_storage` (always `granted`) |
## Testing
In the console: `window.dataLayer` — it should contain `Arguments(3)` with
`consent` / `default`, and after the decision `consent` / `update`. If you see
`Array` instead of `Arguments`, Google will not recognise the command.
The `_ga` cookie appears only after consent for analytics — that is the core of
Consent Mode.
Google, `advanced` mode: before consent the Network tab **will** show a request
to `googletagmanager.com` (and possibly cookieless `collect` pings with
`gcs=G100`) — this is expected. `basic` mode: before consent there **must not**
be any request to `googletagmanager.com` / `google-analytics.com`.
Non-Google pixels: before consent the Network tab **must not** show requests to
`connect.facebook.net`, `clarity.ms`, `snap.licdn.com`, `analytics.tiktok.com`.
After clicking consent they appear right away. Meta Pixel Helper (Chrome
extension) should show `PageView` only after marketing is accepted.
## Events for GTM — pushDataLayer
To push your own event (e.g. `form_submit` for a Lead tag in GTM) use the
`pushDataLayer` helper (SSR-safe, buffers when GTM is not up yet):
```tsx
import { pushDataLayer } from '@intecion/ipal-kit/client'
pushDataLayer('form_submit', { form_name: 'kontakt' })
```
The most common use — the form's `onSuccess` (see [forms.md](./forms.md)):
```tsx
const f = useContactForm({
submitAction,
onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
})
```
**This only emits the event — GTM still gates consent** (`ad_storage` for
marketing tags such as Meta Pixel). `pushDataLayer` does not bypass consent; it
gives GTM a clean event on which a tag can fire when consent is granted.
**GTM sets no cookies by itself** — it is a container. Without a published
(Submit → Publish, not just save) GA4 tag in the container everything looks
fine: `gtm.load` in dataLayer, Tag Assistant sees the container — but there is no
`_ga`, because nothing creates it. When debugging, temporarily clear the GTM
Container ID and keep GA4 alone, to rule out the container as a variable.
---
## Turn off, override, extend
- **Turn off:** do not mount `<Analytics>` (or `SiteProviders analytics={false}`), or leave the ID
fields in Site integrations empty. The *Analytics* tab in the `site-integrations` global is currently
always added (you can hide or change it with `iapl({ globalOverrides: { 'site-integrations': … } })`).
- **Override:** the `<Analytics>` props are plain IDs — you can pass your own instead of
`getAnalyticsConfig`; `consentMode` (`'advanced'` / `'basic'`) sets when the Google tag may load;
`defer` / `deferTimeoutMs` change when tags load. Access and hooks of the `site-integrations` global:
`iapl({ globalOverrides: { 'site-integrations': { access: { … }, hooks: { … } } } })` (your access
rules win, your hooks run after the plugin's; a function gets the whole global). The mapping of
categories to Google signals currently cannot be changed with an option.
- **Extend:** other scripts → `ConsentScript` ([consent.md](./consent.md)); low-level
`loadMetaPixel` / `loadClarity` / `loadLinkedIn` / `loadTikTok`, `pushDataLayer` from `/client`;
`setDefaultConsent` / `updateConsent` from the root; your own fields in Site integrations via
`iapl({ integrationsFields })` (*More* tab).
## Meta Pixel via GTM
A variant for clients whose tags are managed by a marketer in GTM (the **Meta
Pixel ID** field in the panel then stays **empty** — otherwise double counting).
Full step-by-step guide: [gtm-meta-pixel.md](./gtm-meta-pixel.md).