Verified the IAWL summary's "Doc/code" notes against the code and swept
CLI flags, option names/defaults and env vars. Fixed in the docs:
admin groups (consent-records, cookie-review → Privacy; Form messages
global → Forms), tab labels (More, Spam protection, E-mail sending,
Search engines; Sending method), construction field labels, {field} =
label, globalOverrides instead of "a plugin after ipalKit", enabled:false
keeps globals, pages role labels en+pl, switchLocalePath prefix,
accessibility cookie (necessary), seeding summary() shape, prepublishOnly
chain, doctor --strict --offline in the starter, package files list,
ipal-skills --external in PROGRAMISTA, DATABASE_URI (not _URL),
uploadsCollection exists, SiteProviders nonce, buildLinksField labels,
MCP list_pages limit wording, IPAL_DOCTOR_TOKEN in the env table; shipped
seo-check message "Search engines". Reference skills copy refreshed.
Open questions (not changed): forms over-long text, PAYLOAD_SECRET
length, Site settings update access, doctor seen in CI, bare
`ipal-kit create --external`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
243 lines
11 KiB
Markdown
243 lines
11 KiB
Markdown
# 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
|
||
can send cookieless pings — this is **not** "zero requests before consent".
|
||
- `'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.
|
||
|
||
## 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 ipal-kit (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".
|
||
|
||
The rule itself is `shouldLoadGoogle({ consentMode, ready, state })` — a pure function (no React, no DOM)
|
||
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 sends an `update` to
|
||
Google, but **non-Google scripts that are already loaded (Meta, Clarity,
|
||
LinkedIn, TikTok) stay on the page until reload** — the plugin does not unload
|
||
them. The same goes for a Google tag already loaded in `basic` mode — from then
|
||
on it is governed by the Consent Mode `update`.
|
||
|
||
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 `ipalKit({ 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:
|
||
`ipalKit({ 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
|
||
`ipalKit({ 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).
|