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]>
76 lines
3.1 KiB
TypeScript
76 lines
3.1 KiB
TypeScript
'use client'
|
|
import { useEffect, useRef } from 'react'
|
|
// .js extension: Node's ESM resolution (this plugin's tsconfig) can't find
|
|
// 'next/navigation' without it.
|
|
import { usePathname } from 'next/navigation.js'
|
|
|
|
import { useConsentContext } from '../consent/ConsentContext.js'
|
|
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js'
|
|
|
|
/** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */
|
|
export const VISITOR_COOKIE = 'ipal_vid'
|
|
|
|
function readCookie(name: string): string | undefined {
|
|
return document.cookie
|
|
.split('; ')
|
|
.find((c) => c.startsWith(`${name}=`))
|
|
?.split('=')[1]
|
|
}
|
|
|
|
function ensureVisitorId(): string {
|
|
const existing = readCookie(VISITOR_COOKIE)
|
|
if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing}
|
|
const bytes = new Uint8Array(16)
|
|
globalThis.crypto.getRandomValues(bytes)
|
|
const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
const secure = location.protocol === 'https:' ? ';secure' : ''
|
|
document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
|
|
return id
|
|
}
|
|
|
|
export type PageStatsProps = {
|
|
/** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */
|
|
endpoint?: string
|
|
/** Current locale code, stored with the visit. */
|
|
locale?: string
|
|
}
|
|
|
|
/**
|
|
* Built-in statistics: sends one beacon per page view to the hit endpoint.
|
|
*
|
|
* - **Everyone, no consent needed** — nothing is stored in the browser; the
|
|
* server joins page views into a visit with a daily-salted hash it can't
|
|
* reverse, and keeps no IP.
|
|
* - **With analytics consent** (the same category that turns on GA4) — sets the
|
|
* `ipal_vid` cookie with a random id, so the panel can show that visitor's
|
|
* history across days. Withdrawing consent deletes the cookie.
|
|
*
|
|
* Renders nothing. Mount once in the locale layout, INSIDE <ConsentProvider>.
|
|
*/
|
|
export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) {
|
|
const pathname = usePathname()
|
|
const { texts } = useConsentContext()
|
|
const firstHit = useRef(true)
|
|
|
|
useEffect(() => {
|
|
if (!pathname) {return}
|
|
const body: Record<string, string> = { p: pathname }
|
|
// the external referrer belongs to the landing page only
|
|
if (firstHit.current && document.referrer) {body.r = document.referrer}
|
|
firstHit.current = false
|
|
if (locale) {body.l = locale}
|
|
// The cookie, not context state: on a full page load this effect runs before
|
|
// useConsent has read the cookie, so state would still say "no consent".
|
|
if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()}
|
|
|
|
const json = JSON.stringify(body)
|
|
if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) {
|
|
void fetch(endpoint, { body: json, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST' }).catch(() => {})
|
|
}
|
|
// texts.version is read, not a trigger: a policy change isn't a page view
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [pathname, endpoint, locale])
|
|
|
|
return null
|
|
}
|