| .. | ||
| AnalyticsTracker.tsx | ||
| capture.ts | ||
| chronicle.tsx | ||
| core.ts | ||
| index.ts | ||
| README.md | ||
Client Analytics SDK (Phase 1)
First-party, blocker-resistant usage analytics for Polaris Task Force, replacing Microsoft Clarity (which stays mounted during the transition; removal is a later release). Usage data only: no rrweb, no recording, no advertising tech.
- Collector endpoint:
src/app/api/collect/route.ts - Server-side ingest + taxonomy validation:
src/lib/analytics/ingest.ts,src/lib/analytics/events.ts - Tables and rollups:
src/lib/analytics/(see its AGENTS.md) - Admin dashboard:
/admin/analytics(src/components/admin/analytics/)
Enablement
The tracker mounts in exactly two layouts (all user-facing surfaces; the Payload admin panel is deliberately NOT tracked):
src/app/(frontend)/layout.tsx(covers guests on the landing page too)src/app/login/layout.tsx
It tracks in production builds always, and in development only when
NEXT_PUBLIC_ANALYTICS_DEV=1 was set at build time. In dev mode every event is
also mirrored to console.debug("[analytics]", ...) and rows carry env='dev'.
Exercise it locally:
NEXT_PUBLIC_ANALYTICS_DEV=1 bun run dev
# open http://localhost:3000, watch console for [analytics] lines,
# then check rows: SELECT * FROM analytics_events ORDER BY id DESC LIMIT 20;
Fire-and-forget contract: every SDK entry point swallows errors with a
console.warn("[analytics] ..."). Analytics must never break the app.
Identity and sessions
- Session id: issued by the collector as the first-party cookie
ptf_analytics_sid(7 days). The client echoes it on every batch; the server also enforces the boundary itself (30 minutes of inactivity starts a new session row). - Anonymous id: random UUID in localStorage (
ptf_analytics_aid) until login; the collector attributes batches via the same-originpayload-tokencookie and links guest sessions to the user retroactively. - No consent banner (locked decision: usage data only, unit-internal tool). doNotTrack/GPC are ignored. No sampling. Full IP + UA stored per session.
Flush lifecycle
Batched fetch keepalive POSTs every 10s, on route change, and via
navigator.sendBeacon on pagehide / tab hidden. Queue is capped at 50 events
(the server's per-batch limit); overflow drops oldest.
SPA navigation is captured by a usePathname() effect plus patched
history.pushState/replaceState; duplicate notifications for the same path are
deduped.
Event taxonomy
All rows land in analytics_events with type one of the seven values below
(the single source of truth is ANALYTICS_EVENT_TYPES in
src/lib/analytics/events.ts). path is the raw pathname as visited; the
dashboard groups by prefix.
| type | when | data |
element |
|---|---|---|---|
pageview |
mount + every SPA route change | referrerPath / externalReferrer; extra keys from annotatePageview() (e.g. wikiSlug) |
- |
click |
delegated click on interactive elements | xPct, yPct (viewport-relative percentages) |
selector, visible text, w/h, trackLabel |
scroll |
emitted when leaving a page | maxScrollPct (0-100), dwellMs |
- |
focus |
focusin/focusout on inputs, selects, buttons, links, editables | action: "focus" | "blur" |
element descriptor |
visible |
opt-in data-track="label" elements, on route change/unload |
trackLabel, visibleMs, maxRatioPct |
- |
heartbeat |
every 15s while document.visibilityState === "visible" |
ms (elapsed visible slice, capped 60s) |
- |
custom |
track(name, props) calls |
name + flattened props; domain events below |
- |
Domain custom events (Phase 1)
| name | fired by | payload |
|---|---|---|
chronicle.read_progress |
first visibility of a beat/journal article | kind: "beat"|"journal", ref, progressPct |
chronicle.read_completed |
>=90% scrolled AND >=10s visible dwell | kind, ref, timeMs (visible dwell to complete) |
wiki.new_clicked |
WikiIndex "New page" links | source: "toolbar" | "empty" |
wiki.article_created |
WikiEditor create success | slug |
Minigames need no per-game events: /minigames/<slug> routes are mapped to
registry keys at rollup time (src/lib/analytics/games.ts), and play-session
length is the heartbeat dwell on those routes.
Public API
import { track, annotatePageview } from "@/lib/client-analytics";
track("market.listing_viewed", { listingId: 42 }); // custom event
annotatePageview({ wikiSlug: "radio-procedures" }); // merge into current pageview
Both are safe to call anywhere in client components; they no-op when tracking is disabled and never throw.
Adding a new event type or domain event
- Extend
ANALYTICS_EVENT_TYPESinsrc/lib/analytics/events.ts(only for a new structural type, not for custom events). - Update this README's taxonomy table.
- If it should appear in aggregates, extend the rollup SQL in
src/lib/analytics/rollup.ts.