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]>
This commit is contained in:
Radosław Smoliński
2026-10-21 15:10:55 +02:00
co-authored by Claude Opus 5.5
parent 305c564d13
commit 4ec27d9ef0
47 changed files with 1799 additions and 57 deletions
+10
View File
@@ -0,0 +1,10 @@
/** Nav link to /admin/stats (admin.components.afterNavLinks). */
export function StatsNavLink({ adminRoute = '/admin' }: { adminRoute?: string }) {
return (
<a className="nav__link" href={`${adminRoute.replace(/\/$/, '')}/stats`} id="nav-ipal-stats">
<span className="nav__link-label">Statistics</span>
</a>
)
}
export default StatsNavLink
+172
View File
@@ -0,0 +1,172 @@
import type { AdminViewServerProps } from 'payload'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { isAdmin } from '../../access/predicates.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = { adminRoute?: string; timeZone?: string } & AdminViewServerProps
const fmt = (n: number) => n.toLocaleString('en-US')
const when = (iso: string, timeZone: string) =>
new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso))
function TopList({ rows, title, unit }: { rows: [string, number][]; title: string; unit: string }) {
return (
<section>
<h3>{title}</h3>
{rows.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">{title}</th>
<th scope="col">{unit}</th>
</tr>
</thead>
<tbody>
{rows.map(([key, count]) => (
<tr key={key}>
<td><code>{key}</code></td>
<td>{fmt(count)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No data yet.</p>
)}
</section>
)
}
function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
return (
<>
<p><a href={base}>← All statistics</a></p>
<h1>Visitor <code>{visitorId}</code></h1>
<p>
{visits.length} visit{visits.length === 1 ? '' : 's'} recorded with analytics consent. To erase this
visitor’s data, filter <em>Statistics → Visits</em> by this visitor id and delete the results.
</p>
{visits.map((v) => (
<section className="ipal-stats-tile" key={v.id} style={{ marginBottom: '1rem' }}>
<strong>{when(v.startedAt, timeZone)}</strong>
<span>
{' '}· {v.pageCount} page{v.pageCount === 1 ? '' : 's'} · {v.device ?? 'unknown device'}
{v.referrer ? ` · from ${v.referrer}` : ''}
</span>
<ol style={{ margin: '0.5rem 0 0', paddingLeft: '1.25rem' }}>
{(v.pages ?? []).map((p, i) => (
<li key={`${p.t}-${i}`}>
<code>{p.p}</code> <span>{when(p.t, timeZone).split(', ').pop()}</span>
</li>
))}
</ol>
</section>
))}
</>
)
}
/**
* Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the
* last 30 days, top pages, entry pages, referrers, devices, and — for visitors
* who accepted analytics cookies — a per-visitor history (?visitor=<id>).
* Admins only.
*/
export async function StatsView(props: Props) {
const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props
const { req, visibleEntities } = initPageResult
const base = `${adminRoute.replace(/\/$/, '')}/stats`
const visitorParam = typeof searchParams?.visitor === 'string' ? searchParams.visitor : undefined
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
let content: React.ReactNode
if (!isAdmin(req.user)) {
content = <p>Statistics are available to administrators only.</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
} else {
const [stats, recent] = await Promise.all([loadStats(req.payload, { timeZone }), loadRecentVisitors(req.payload, 50)])
const { totals } = stats
const visitors = [...new Map(recent.map((v) => [v.visitorId!, v])).values()].slice(0, 15)
content = (
<>
<h1>Statistics</h1>
<p>
Last 30 days. Counted without cookies, so no consent is needed; no IP addresses are stored. Visitors who accept
analytics cookies also get a history across days.
</p>
<div className="ipal-stats-tiles">
<div className="ipal-stats-tile"><b>{fmt(totals.visits)}</b><span>Visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.views)}</b><span>Page views</span></div>
<div className="ipal-stats-tile">
<b>{totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}</b><span>Pages per visit</span>
</div>
<div className="ipal-stats-tile"><b>{Math.round(totals.bounceRate * 100)}%</b><span>Single-page visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.consented)}</b><span>Visits with analytics consent</span></div>
</div>
<h2>Visits per day</h2>
<VisitsChart days={stats.days} />
<div className="ipal-stats-lists">
<TopList rows={stats.topPages} title="Page" unit="Views" />
<TopList rows={stats.entries} title="Entry page" unit="Visits" />
<TopList rows={stats.referrers} title="Referrer" unit="Visits" />
<TopList rows={stats.devices} title="Device" unit="Visits" />
</div>
<section style={{ marginTop: '2rem' }}>
<h3>Visitor history (analytics consent only)</h3>
{visitors.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Visitor</th>
<th scope="col">Last seen</th>
</tr>
</thead>
<tbody>
{visitors.map((v) => (
<tr key={v.visitorId}>
<td><a aria-label={`Visitor ${v.visitorId}`} href={`${base}?visitor=${v.visitorId}`}><code>{v.visitorId}</code></a></td>
<td>{when(v.lastAt, timeZone)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No visitor has accepted analytics cookies yet.</p>
)}
</section>
</>
)
}
return (
<DefaultTemplate
i18n={req.i18n}
locale={initPageResult.locale}
params={props.params}
payload={req.payload}
permissions={initPageResult.permissions}
req={req}
searchParams={searchParams}
user={req.user ?? undefined}
visibleEntities={visibleEntities}
>
<Gutter>
<div className="ipal-stats" style={{ paddingBottom: '3rem' }}>
<style>{STATS_CSS}</style>
{content}
</div>
</Gutter>
</DefaultTemplate>
)
}
export default StatsView
+42
View File
@@ -0,0 +1,42 @@
import type { Payload, PayloadRequest } from 'payload'
import { isAdmin } from '../../access/predicates.js'
import { loadStats } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
payload?: Payload
req?: PayloadRequest
timeZone?: string
user?: unknown
}
/**
* Dashboard card (admin.components.beforeDashboard): visits per day for the
* last 30 days with a link to the full view. Admins only; renders nothing on
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !isAdmin((req?.user ?? user) as never)) {return null}
let stats
try {
stats = await loadStats(payload, { timeZone })
} catch {
return null
}
return (
<section className="ipal-stats" style={{ marginBottom: '2rem' }}>
<style>{STATS_CSS}</style>
<h2 style={{ marginBottom: '0.25rem' }}>Visits per day</h2>
<p style={{ color: 'var(--theme-elevation-500)', margin: '0 0 0.75rem' }}>
Last 30 days: {stats.totals.visits.toLocaleString('en-US')} visits, {stats.totals.views.toLocaleString('en-US')} page views ·{' '}
<a href={`${adminRoute.replace(/\/$/, '')}/stats`}>All statistics →</a>
</p>
<VisitsChart days={stats.days} />
</section>
)
}
export default StatsWidget
+108
View File
@@ -0,0 +1,108 @@
import type { StatsDay } from '../summarize.js'
const W = 1000
const H = 220
const PAD = { bottom: 24, left: 36, right: 8, top: 12 }
const RADIUS = 4
/** Round up to 1 / 2 / 5 × 10^k, so the gridlines land on readable numbers. */
function niceMax(value: number): number {
if (value <= 4) {return 4}
const pow = 10 ** Math.floor(Math.log10(value))
return ([1, 2, 5, 10].map((s) => s * pow).find((s) => s >= value) ?? 10 * pow)
}
/** Column with a 4px rounded top and a square base on the baseline. */
function column(x: number, y: number, w: number, h: number): string {
const r = Math.min(RADIUS, w / 2, h)
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`
}
const shortDate = (day: string) => `${day.slice(8, 10)}.${day.slice(5, 7)}`
/**
* Visits per day — server-rendered SVG, no client JS. One series, so no
* legend: the heading names it. Each day has a full-height hover target with
* a native tooltip, and the numbers are in a table below for screen readers.
*/
export function VisitsChart({ days }: { days: StatsDay[] }) {
const max = niceMax(Math.max(0, ...days.map((d) => d.visits)))
const plotW = W - PAD.left - PAD.right
const plotH = H - PAD.top - PAD.bottom
const band = plotW / Math.max(1, days.length)
const barW = Math.min(24, band - 2)
const y = (v: number) => PAD.top + plotH - (v / max) * plotH
const ticks = [0, max / 2, max]
return (
<figure className="ipal-stats-chart" style={{ margin: 0 }}>
<svg aria-hidden="true" style={{ display: 'block', height: 'auto', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
{ticks.map((t) => (
<g key={t}>
<line className="ipal-stats-grid" x1={PAD.left} x2={W - PAD.right} y1={y(t)} y2={y(t)} />
<text className="ipal-stats-axis" dominantBaseline="middle" textAnchor="end" x={PAD.left - 6} y={y(t)}>
{Number.isInteger(t) ? t : t.toFixed(1)}
</text>
</g>
))}
{days.map((d, i) => {
const x = PAD.left + i * band
const h = (d.visits / max) * plotH
const label = i % 7 === (days.length - 1) % 7
return (
<g className="ipal-stats-day" key={d.day}>
<title>{`${d.day}: ${d.visits} visits, ${d.views} page views`}</title>
<rect fill="transparent" height={plotH} width={band} x={x} y={PAD.top} />
{h > 0 ? <path className="ipal-stats-bar" d={column(x + (band - barW) / 2, y(d.visits), barW, h)} /> : null}
{label ? (
<text className="ipal-stats-axis" textAnchor="middle" x={x + band / 2} y={H - 6}>
{shortDate(d.day)}
</text>
) : null}
</g>
)
})}
</svg>
<details style={{ marginTop: '0.5rem' }}>
<summary>Table</summary>
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Day</th>
<th scope="col">Visits</th>
<th scope="col">Page views</th>
</tr>
</thead>
<tbody>
{[...days].reverse().map((d) => (
<tr key={d.day}>
<td>{d.day}</td>
<td>{d.visits}</td>
<td>{d.views}</td>
</tr>
))}
</tbody>
</table>
</details>
</figure>
)
}
/** Colors from the reference palette (series 1, light/dark) + Payload's theme tokens for ink. */
export const STATS_CSS = `
.ipal-stats { --ipal-series-1: #2a78d6; }
html[data-theme='dark'] .ipal-stats { --ipal-series-1: #3987e5; }
.ipal-stats-bar { fill: var(--ipal-series-1); }
.ipal-stats-day:hover .ipal-stats-bar { opacity: 0.8; }
.ipal-stats-grid { stroke: var(--theme-elevation-100); stroke-width: 1; }
.ipal-stats-axis { fill: var(--theme-elevation-500); font-size: 11px; }
.ipal-stats-tiles { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 1rem 0 1.5rem; }
.ipal-stats-tile { border: 1px solid var(--theme-elevation-150); border-radius: 4px; padding: 0.75rem 1rem; }
.ipal-stats-tile b { display: block; font-size: 1.75rem; line-height: 1.2; }
.ipal-stats-tile span { color: var(--theme-elevation-500); font-size: 0.85rem; }
.ipal-stats-lists { display: grid; gap: 1.5rem; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); margin-top: 2rem; }
.ipal-stats-table { border-collapse: collapse; width: 100%; }
.ipal-stats-table th, .ipal-stats-table td { border-bottom: 1px solid var(--theme-elevation-100); padding: 0.35rem 0.5rem; text-align: left; }
.ipal-stats-table td:not(:first-child), .ipal-stats-table th:not(:first-child) { font-variant-numeric: tabular-nums; text-align: right; }
.ipal-stats-table code { word-break: break-all; }
`
+63
View File
@@ -0,0 +1,63 @@
import type { Payload } from 'payload'
import type { StatsVisit } from '../collection.js'
import type { StatsSummary } from '../summarize.js'
import { STATS_SLUG } from '../collection.js'
import { lastDays, summarize } from '../summarize.js'
const VISIT_FIELDS = {
day: true,
device: true,
entry: true,
exit: true,
lastAt: true,
pageCount: true,
pages: true,
referrer: true,
startedAt: true,
visitorId: true,
} as const
/** Summary of the last `days` days. Callers check the user is an admin first. */
export async function loadStats(payload: Payload, { days = 30, timeZone = 'Europe/Warsaw' } = {}): Promise<StatsSummary> {
const range = lastDays(days, timeZone)
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
where: { day: { greater_than_equal: range[0] } },
})
return summarize(docs as unknown as StatsVisit[], range)
}
/** Every stored visit of one consenting visitor, newest first. */
export async function loadVisitor(payload: Payload, visitorId: string): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit: 500,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
sort: '-startedAt',
where: { visitorId: { equals: visitorId } },
})
return docs as unknown as StatsVisit[]
}
/** Latest visits that carry a visitor id — the entry points into visitor history. */
export async function loadRecentVisitors(payload: Payload, limit = 20): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit,
overrideAccess: true,
select: VISIT_FIELDS as never,
sort: '-lastAt',
where: { visitorId: { exists: true } },
})
return docs as unknown as StatsVisit[]
}