Added not-found support for sitesettings

This commit is contained in:
2026-10-12 17:32:31 +02:00
parent c852d7bdae
commit 7aebe24236
52 changed files with 837 additions and 95 deletions
+46 -15
View File
@@ -3,8 +3,10 @@ import { useEffect } 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 {
@@ -34,37 +36,66 @@ function injectScript(src: string) {
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
* Loads every configured analytics / marketing tag, each respecting consent:
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
* 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({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig) {
export function Analytics(props: AnalyticsConfig) {
const {
clarityProjectId,
ga4MeasurementId,
gtmContainerId,
linkedInPartnerId,
metaPixelId,
tiktokPixelId,
} = props
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
// --- Google: load once, Consent Mode handles gating ---
useEffect(() => {
if (!ga4MeasurementId && !gtmContainerId) {return}
// 1. Consent Mode default = the visitor's stored choice, before tags load.
setDefaultConsent(readConsent())
// 2. Load the tag.
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))
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
// real gtag.js wires itself up once the script loads.
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ga4MeasurementId, gtmContainerId])
// --- Non-Google: load each when its consent category is granted ---
// The loaders are idempotent, so re-running on state changes is safe; a tag
// loads the first time its category flips to true and never doubles up.
useEffect(() => {
if (state.marketing) {
if (metaPixelId) {loadMetaPixel(metaPixelId)}
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
if (tiktokPixelId) {loadTikTok(tiktokPixelId)}
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
}, [
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId,
])
return null
}
+3
View File
@@ -1,3 +1,6 @@
'use client'
export { Analytics } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
export { pushDataLayer } from './pushDataLayer.js'
+6 -3
View File
@@ -5,15 +5,18 @@ import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js'
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/
export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {
const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null,
}
}
+118
View File
@@ -0,0 +1,118 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/
type Win = Record<string, any> & typeof window
/** Meta (Facebook) Pixel — fires PageView on load. */
export function loadMetaPixel(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.fbq) {return}
const n: any = (w.fbq = function (...args: unknown[]) {
if (n.callMethod) {
n.callMethod.apply(n, args)
} else {
n.queue.push(args)
}
})
if (!w._fbq) {w._fbq = n}
n.push = n
n.loaded = true
n.version = '2.0'
n.queue = []
const s = document.createElement('script')
s.async = true
s.src = 'https://connect.facebook.net/en_US/fbevents.js'
document.head.appendChild(s)
w.fbq('init', id)
w.fbq('track', 'PageView')
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export function loadClarity(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.clarity) {return}
w.clarity = function (...a: unknown[]) {
;(w.clarity.q = w.clarity.q || []).push(a)
}
const s = document.createElement('script')
s.async = true
s.src = `https://www.clarity.ms/tag/${id}`
document.head.appendChild(s)
}
/** LinkedIn Insight Tag (marketing). */
export function loadLinkedIn(partnerId: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
w._linkedin_partner_id = partnerId
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || []
if (w._linkedin_data_partner_ids.includes(partnerId)) {
if (document.getElementById('ipal-linkedin-insight')) {return}
} else {
w._linkedin_data_partner_ids.push(partnerId)
}
if (document.getElementById('ipal-linkedin-insight')) {return}
const s = document.createElement('script')
s.async = true
s.id = 'ipal-linkedin-insight'
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'
document.head.appendChild(s)
}
/** TikTok Pixel (marketing) — fires page view on load. */
export function loadTikTok(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.ttq) {return}
w.TiktokAnalyticsObject = 'ttq'
const ttq: any = (w.ttq = [])
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie',
]
ttq.setAndDefer = function (t: any, e: string) {
t[e] = function (...args: unknown[]) {
t.push([e, ...args])
}
}
for (const m of ttq.methods) {ttq.setAndDefer(ttq, m)}
ttq.load = function (e: string) {
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js'
ttq._i = ttq._i || {}
ttq._i[e] = []
ttq._i[e]._u = url
ttq._t = ttq._t || {}
ttq._t[e] = Number(new Date())
const s = document.createElement('script')
s.async = true
s.src = `${url}?sdkid=${e}&lib=ttq`
document.head.appendChild(s)
}
ttq.load(id)
ttq.page()
}
+13 -3
View File
@@ -1,9 +1,19 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/
export type AnalyticsConfig = {
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
/** Microsoft Clarity project ID. (analytics consent) */
clarityProjectId?: null | string
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
ga4MeasurementId?: null | string
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
gtmContainerId?: null | string
/** LinkedIn Insight Tag partner ID. (marketing consent) */
linkedInPartnerId?: null | string
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
metaPixelId?: null | string
/** TikTok Pixel ID. (marketing consent) */
tiktokPixelId?: null | string
}