Files
ipal-kit/src/modules/analytics/Analytics.tsx
T
Radosław SmolińskiandClaude Opus 5.5 4ec27d9ef0 Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet
Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.

Also in this release: meta.description auto-filled from page blocks, <NoSnippet>,
MetaDescriptionCheck in the SEO tab, data-nosnippet on banner/language switcher, GA4 CSP
wildcards, consent version passed to Analytics' default consent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 15:10:55 +02:00

180 lines
6.4 KiB
TypeScript

'use client'
import { useEffect, useRef, useState } from 'react'
import type { AnalyticsConfig } from './types.js'
import { useConsentContext } from '../consent/client.js'
import { gtag } from '../consent/googleConsent.js'
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
declare global {
interface Window {
dataLayer?: unknown[]
}
}
const GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`
const GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`
/**
* Reads the current consent state from cookie, or defaults if none. `version`
* must be the panel's policy version — the same one useConsent checks — or a
* valid consent under any version other than 1 reads as "all denied".
*/
function readConsent(version: number | undefined) {
if (typeof document === 'undefined') {return DEFAULT_CONSENT}
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
return parseConsent(raw, version) ?? DEFAULT_CONSENT
}
function injectScript(src: string) {
if (document.querySelector(`script[src="${src}"]`)) {return}
const s = document.createElement('script')
s.src = src
s.async = true
document.head.appendChild(s)
}
export type AnalyticsProps = {
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
* JS out of the FCP/LCP window.
*
* Consent is unaffected: the Consent Mode default is still pushed immediately
* (a synchronous dataLayer push, no network), and non-Google pixels still
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
*
* Trade-off: visitors who leave before interacting and before the timeout are
* not counted (slightly fewer sessions in GA). Default false.
*/
defer?: boolean
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number
} & AnalyticsConfig
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
/** True once third-party tags may load (immediately, or per `defer` rules). */
function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
const [ready, setReady] = useState(!defer)
useEffect(() => {
if (!defer || ready) {return}
let timer: ReturnType<typeof setTimeout> | undefined
const fire = () => setReady(true)
const onLoad = () => {
timer = setTimeout(() => {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(fire, { timeout: 1000 })
} else {
fire()
}
}, timeoutMs)
}
for (const e of INTERACTION_EVENTS) {
window.addEventListener(e, fire, { once: true, passive: true })
}
if (document.readyState === 'complete') {onLoad()}
else {window.addEventListener('load', onLoad, { once: true })}
return () => {
for (const e of INTERACTION_EVENTS) {window.removeEventListener(e, fire)}
window.removeEventListener('load', onLoad)
if (timer) {clearTimeout(timer)}
}
}, [defer, ready, timeoutMs])
return ready
}
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **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.
* - **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.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export function Analytics(props: AnalyticsProps) {
const {
clarityProjectId,
defer = false,
deferTimeoutMs = 3500,
ga4MeasurementId,
gtmContainerId,
linkedInPartnerId,
metaPixelId,
tiktokPixelId,
} = props
// Live consent state — drives the non-Google pixels.
const { state, texts } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
// --- Consent Mode default: immediately, once — never deferred ---
// No network cost, and it must precede any gtag('config') / GTM start, or
// Google assumes "granted".
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
setDefaultConsent(readConsent(texts.version))
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId, texts.version])
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(() => {
if (!ready) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
injectScript(GTM_SCRIPT(gtmContainerId))
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId))
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ready, 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
// the first time both conditions hold and never doubles up.
useEffect(() => {
if (!ready) {return}
if (state.marketing) {
if (metaPixelId) {loadMetaPixel(metaPixelId)}
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
if (tiktokPixelId) {loadTikTok(tiktokPixelId)}
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
}, [
ready,
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId,
])
return null
}