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
}
+1
View File
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
@@ -0,0 +1,57 @@
import type { BasePayload } from 'payload'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
locale,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
locale: locale as never,
})) as Record<string, unknown>
const rel = settings.notFound
const id =
typeof rel === 'string' || typeof rel === 'number'
? rel
: rel && typeof rel === 'object'
? (rel as { id?: number | string }).id
: undefined
if (id === undefined) {return null}
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
}
}
+17
View File
@@ -160,5 +160,22 @@ export async function resolveRoute({
const doc = found.docs[0]
if (!doc) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound
const homepage = settings.homepage
const notFoundId =
notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound
const homepageId =
homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage
const docId = (doc as { id?: unknown }).id
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null
}
return { type: 'page', doc: doc as Record<string, unknown> }
}
+30 -2
View File
@@ -7,7 +7,11 @@ import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/in
import type { I18nConfig } from '../i18n/index.js'
import type { RobotsRules, SitemapEntry } from '../seo/index.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import {
getArchiveEntries,
resolveNotFoundPage,
resolveRoute as resolveRouteRaw,
} from '../content/index.js'
import { buildRobots, buildSitemapEntries } from '../seo/index.js'
type CreateContentHelpersArgs = {
@@ -96,6 +100,20 @@ export function createContentHelpers({
},
)
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
const payload = await getCachedPayload()
return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })
} catch {
return null // DB unreachable (container build) — fallback view
}
})
/** One page of a collection's entries, for an archive listing. */
const getEntries = cache(
async (
@@ -202,8 +220,16 @@ export function createContentHelpers({
// Home slug per locale, to exclude the homepage (it's the root, slug []).
const settings = (await payload
.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })
.catch(() => null)) as { homepage?: { id?: number | string; slug?: unknown } } | null
.catch(() => null)) as {
homepage?: { id?: number | string; slug?: unknown }
notFound?: { id?: number | string } | null
} | null
const homeId = settings?.homepage?.id
// The assigned 404 page renders via not-found.tsx, never as its own URL.
const notFoundId =
settings?.notFound?.id !== undefined && settings.notFound.id !== homeId
? settings.notFound.id
: undefined
const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
@@ -228,6 +254,7 @@ export function createContentHelpers({
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
@@ -286,6 +313,7 @@ export function createContentHelpers({
getCachedPayload,
getConfiguredLocales,
getEntries,
getNotFoundPage,
getSettings,
resolveRoute,
robots,
+3
View File
@@ -8,6 +8,7 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js'
const ROLE_LABELS: Record<SystemPageRole, string> = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service',
}
@@ -16,6 +17,8 @@ const ROLE_LABELS: Record<SystemPageRole, string> = {
const ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound:
'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.',
}
+3 -1
View File
@@ -2,13 +2,15 @@
* Built-in "system page" roles — documents from the client's Pages
* collection that the site references by function rather than by slug.
*/
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'
export type SystemPageRole =
'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'
/**
* All system roles in a stable order (used when no subset is configured).
*/
export const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [
'homepage',
'notFound',
'privacyPolicy',
'cookiePolicy',
'termsOfService',