Analytics
The site uses PostHog (US region) for cookieless, privacy-first analytics. Nothing is stored in the browser and there is no consent banner. The code lives in src/lib/analytics/ and src/modules/providers/. The docs site and the published Storybook send their own, smaller set of events to the same project: see Docs site and Storybook.
A proposed expansion (consent-gated persistent IDs, replay and richer events, all off by default) is specified in the observability architecture spec and ADR 0001. Implemented so far: the event policy stage under Event policy, the consent store and collection policy under Consent and collection policy, the consent interface under Privacy settings interface, the Payload probe, and the Retention, access and cost targets. The rest is not built; this document describes the current behavior.
What is collected
Thirteen product events and one error event, defined in src/lib/analytics/tracking/events.ts:
| Event | When | Properties |
|---|---|---|
$pageview | Every client-side route change (not hash-only moves) | none (PostHog adds URL and referrer itself) |
resume_dialog_opened | The resume request dialog opens | none |
resume_request_submitted | The resume form is submitted with a valid name and email | none |
outbound_link_clicked | A click on an external link | host, location (header, footer, nav, main, other) |
section_viewed | A landing page nav section (summary, impact, experience; ids from NAV_SECTIONS) crosses the middle of the viewport, once per page view. Pages without those ids report nothing | section (the element id) |
internal_link_clicked | A click on an internal link inside a marked surface (data-track-source); ordinary links are not tracked, $pageview already covers where the visitor went | source (floating_nav, header_logo, hero_scroll, skill_index, experience_plate, experience_timeline, experience_cta, detail_back, detail_related, detail_adjacent, detail_usage, footer, resume_page), destination (section, skill, experience, resume, about, home, other), target (section id or skill/experience slug, when there is one) |
contact_email_clicked | A click on a mailto: link | location (as for outbound_link_clicked); never the address |
email_copy | The email copy button on the About page is used | location (as for outbound_link_clicked), method (clipboard, or mailto when the Clipboard API failed and the mail client opened); never the address |
vcard_downloaded | The “Save contact” link on the About page, revealed after a visitor uses one of its links, is clicked | none |
skill_filter_used | A skills index control: search goes empty to non-empty (search) or back (search_cleared) | control, value (on); never the query |
experience_highlight_selected | A highlight card chosen on the landing Experience plate (not first paint) | highlight (content id), via (pointer, keyboard, swipe) |
palette_open | The command palette opens, from the keyboard shortcut or the header chip | via: shortcut or chip |
palette_select | A palette result is activated (Enter or click) | kind: section, role, skill, resume, link or action. Never the query or the label |
resume_email_sent | The server accepted the request and sent the resume by email. Arrival in the inbox is unobservable | none |
Errors are reported as PostHog’s standard $exception event, described under Error tracking.
On the landing page the observed sections are summary, impact and experience. PostHog also reports field Web Vitals (capture_performance) and page leave (capture_pageleave).
What is not collected:
- No cookies and no
localStorageorsessionStorageentries. - No autocapture, no session replay and no person profiles (
person_profiles: "identified_only", and nothing is ever identified). - Heatmaps, dead-click capture and surveys are pinned off in code (
capture_heatmapsandcapture_dead_clicksset tofalse,disable_surveys: true), so a PostHog project setting cannot turn them on. Exception capture is on, narrowly and scrubbed: see Error tracking. Feature flags are not loaded either (advanced_disable_flags: true). - No personal data: product events carry only booleans, enum-like strings and hostnames chosen in code. Never an email, a name, free text or a URL with a query string.
$exceptionevents are scrubbed of query strings, hashes and email-shaped text before they leave the browser. - Do Not Track is honoured (
respect_dnt: true). - The assistant chat sends no browser analytics events, no cookie and no browser storage entry; its session token lives in memory. The server records one event per chat request, described under Assistant telemetry. Answers are never recorded. A visitor’s question is recorded, redacted, only while the server-only flag
assistant-log-questionsis on and the request carries noDNT: 1orSec-GPC: 1header. Questions also go to the model provider. The panel shows no notice about recording, by decision.
Coverage matrix
What each event answers, where it fires, and what already covers the same signal. Events fire at the user-action boundary (a click or a state change handler), never on render, and links are caught by one delegated listener (useInteractionTracking), so a link with several handlers still counts once.
| Journey | Question | Event and trigger | Call site | Already covered by |
|---|---|---|---|---|
| Landing navigation | Which sections do visitors jump to? | internal_link_clicked (floating_nav, section) | FloatingNav | section_viewed says what was seen, not what was chosen |
| Landing hero | Is the scroll-down CTA used? | internal_link_clicked (hero_scroll, section, summary) | LandingHeroScrollIndicator | none |
| Skills | Which skills get opened? | internal_link_clicked (skill_index, skill, slug) | SkillList rows | $pageview of /skills/<slug> counts arrivals from any source |
| Skills | Is the index explored or just scrolled? | skill_filter_used | SkillIndex handlers | none |
| Experience | Which highlight cards are read? | experience_highlight_selected | ExperiencePlate.select | none |
| Experience | Which roles are opened, and from where? | internal_link_clicked (experience_plate or experience_timeline, experience, slug) | plate related roles, timeline | $pageview |
| Detail pages | Do visitors keep exploring? | internal_link_clicked (detail_related, detail_adjacent, detail_usage, detail_back) | PageShell partials | $pageview |
| Resume funnel | Do visitors reach and use the resume? | internal_link_clicked (experience_cta or footer, resume), then resume_dialog_opened, resume_request_submitted, resume_email_sent | LandingExperience, Footer, ResumeDownload | $pageview of /resume |
| Contact | Who emails from the site? | contact_email_clicked, email_copy | delegated | outbound_link_clicked ignores mailto: |
| Off-site | Which outbound destinations? | outbound_link_clicked | delegated | unchanged |
Not instrumented, on purpose: there is no landing scroll assist to report on (the one added in #170 was removed in #295). Route-transition loading is not tracked because there is no completion signal to report truthfully, and errors stay with $exception.
Marking a surface
Add data-track-source="<source>" to a link or any ancestor and add the value to LinkSource in events.ts (it is checked at runtime by linkSource in navigation.ts, so a typo reports nothing instead of a bad value). The destination and target come from the link’s path only (never the query), and slugs must be lowercase URL-safe or they are dropped. Event names and properties never use translated display text.
Suggested funnels and dashboards
- Exploration:
section_viewed(summary) tointernal_link_clicked(skill) tointernal_link_clicked(experience) tointernal_link_clicked(resume). - Resume intent:
resume_dialog_openedtoresume_request_submittedtoresume_email_sent. The gap between the last two is failed sends. - CTA discoverability:
internal_link_clickedbysource, as a bar chart over a month. - Skills index:
skill_filter_usedbycontrol, next tointernal_link_clickedwithsource = skill_index, to see whether filtering leads to opens. - Detail-page depth:
internal_link_clickedwithsourceindetail_related,detail_adjacent.
The resume funnel, the source breakdown and two more charts are saved in PostHog: see Operating the PostHog project.
When it runs
Analytics is a complete no-op unless all of these hold (resolveAnalyticsConfig() in src/lib/analytics/config.ts):
POSTHOG_ANALYTICS_KEY(orNEXT_PUBLIC_POSTHOG_ANALYTICS_KEY) is set.NODE_ENVisproduction.NEXT_PUBLIC_APP_ENVis notstaging.
So development, tests, staging and preview deployments without a key stay out of the production data. The key is the only thing keeping Vercel Preview out: Preview builds run with NODE_ENV=production, so a key set there would send real events into the production data. Local development (including vercel dev) uses NODE_ENV=development and stays silent. posthog-js is loaded with a dynamic import() after the browser is idle and is not part of the initial bundle. track() never throws and never blocks the page; events fired before posthog-js has loaded are buffered (bounded) and flushed once it is ready.
Vercel Speed Insights
@vercel/speed-insights reports Core Web Vitals to Vercel. It is separate from PostHog: it needs no key and reads only the privacy signals, not the consent record. PostHog’s own capture_performance and the Web Vitals page keep working as before. It stores no cookie or identifier in the browser.
SpeedInsightsProvider (src/modules/providers/) is mounted once in the root layout and renders the SDK only when resolveSpeedInsightsEnabled() (src/lib/analytics/speedInsights.ts) holds: NODE_ENV is production and NEXT_PUBLIC_APP_ENV is not staging. Like PostHog, Vercel Preview builds run with NODE_ENV=production, so a preview deployment reports into the project’s Speed Insights data. Unlike PostHog there is no key to withhold, so filter on the deployment environment in the Vercel dashboard.
It is a baseline measurement with no opt-in. Because the SDK has no setting for privacy signals, the provider passes a beforeSend hook that drops every measurement when the browser sends Do Not Track or Global Privacy Control (readPrivacySignals()), the same signals the rest of the analytics honours. An explicit decline in the privacy panel does not reach this hook, since the panel governs only the optional analytics and diagnostics purposes.
To turn it off, remove <SpeedInsightsProvider /> from src/app/layout.tsx, or disable Speed Insights for the project in the Vercel dashboard.
Internal traffic (Vercel Toolbar)
When I browse production while signed in to Vercel with the Toolbar on, those visits would count as real traffic. src/lib/analytics/client/internalTraffic.ts marks them instead. Nothing is dropped: the events are still sent, with two extra properties, and a PostHog filter removes them from reports.
The signal
Observed on antmejia.com in a signed-in browser with the Toolbar showing, and absent in a private window and in a headless browser, including with ?__vercel_toolbar=1:
- A
<script src="https://vercel.live/_next-live/feedback/feedback.js">in<head>, requested about 1 s after navigation. - A
<vercel-live-feedback>element at the end of<body>, present by about 3 s.
The detector looks for either one with a single querySelector, then watches the document with a MutationObserver for 5 seconds and disconnects. It has no negative result, so a visitor it does not detect is counted normally.
Preview and staging deployments serve the same widget to every visitor, so it says nothing there. That does not matter: analytics never runs on staging or on previews without a key.
This is an undocumented heuristic. Vercel publishes no page-side API for the viewer’s role, and the signal shows that the Toolbar was injected, which does not prove team membership. Late requests such as vercel.com/api/www/avatar and /.well-known/vercel/flags only appear once the Toolbar UI is opened, so they are not used.
What is tagged
Every event that passes through before_send after detection gets is_internal_visitor: true and internal_detection_method: "vercel_toolbar". That covers page views, catalog events, web vitals and scrubbed exceptions. The tag runs after the exception scrubber, so it is never scrubbed away. No identity, cookie or person profile is added.
Timing follows from how events are sent. Detection starts when initAnalytics runs, before posthog-js loads, and buffered events (including the first page view) are captured only after the SDK is ready. A Toolbar present at load, which is the usual case, tags all of them. A Toolbar that appears after an event was sent leaves that event untagged, and one that appears after the 5 second window is missed entirely. Once set, the tag stays for the page’s life.
Reporting
In PostHog, add a filter is_internal_visitor is not set (or does not equal true) to the insights and dashboards that should exclude me. This is an event-property filter. It does not change ingestion or billing, and SQL queries ignore it unless they add the condition. Verify a filter against real events before relying on it.
Rollback
Set NEXT_PUBLIC_ANALYTICS_INTERNAL_DETECTION=off and redeploy. The detector is not started and before_send runs only the scrubber. Use it if Vercel changes the Toolbar and events start getting tagged wrongly.
What I have not done yet
- A canary on production to measure false positives (ordinary visitors tagged) and false negatives (signed-in sessions not tagged). The signal was verified on one account in one browser, and a signed-in Vercel user outside the team was not tested.
- The PostHog filter itself.
- Suppressing capture for detected sessions. That needs a measured false-positive rate first.
Error tracking
Runtime errors visitors hit are sent as $exception events and show up in PostHog’s Error Tracking view. Exception capture used to be forced off; it is now switched on deliberately, and only this much (src/lib/analytics/client/client.ts):
capture_exceptions: {
capture_unhandled_errors: true,
capture_unhandled_rejections: true,
capture_console_errors: false,
},
before_send: [scrubExceptionEvent],Everything else stays as it was: cookieless, no autocapture, no session replay, no person profiles, Do Not Track honoured, the same production-only gate (resolveAnalyticsConfig) and the same first-party /_lg proxy. No new env var, host or dependency.
What is captured
- Unhandled errors (
window.onerror) and unhandled promise rejections, byposthog-jsitself. - React render errors, by the two error boundaries:
src/app/error.tsx(a route failed; the site chrome survives) andsrc/app/global-error.tsx(the root layout failed; it renders its own<html>and<body>, and because the layout’s analytics provider is gone it starts analytics itself, gated by the sameresolveAnalyticsConfig). Both calltrackError(error, context)fromsrc/lib/analytics/tracking/track.ts, which hands the error toposthog.captureException. Liketrack(), it is a no-op unless analytics is on, buffers (newest 10) untilposthog-jshas loaded and never throws. The context is{ boundary: "error" | "global-error", digest? }; the error text is never shown on the page. - Not captured:
console.erroroutput.
What is scrubbed and dropped
scrubExceptionEvent (src/lib/analytics/client/errors.ts, pure and unit tested) is the before_send hook. Non-exception events pass through untouched. For $exception events:
- Query strings and hashes are removed from
$current_url,$referrer, every stack-framefilename/URL and any other URL-like field (including$setand$set_once), and from URLs that appear inside message text. - Email-shaped text is replaced with
[email]in every string of the payload. - Exception messages (
$exception_list[].value,$exception_message,$exception_values) are capped at 300 characters. - Dropped entirely: errors from browser extensions (
chrome-extension://,moz-extension://,safari-extension://,safari-web-extension://anywhere in the payload) and the harmlessResizeObserver loopwarnings.
Other free text in an error message, such as a name, is not detectable and is not scrubbed. Keep error messages in the code free of user input.
Limits and deferred work
- Errors thrown before
posthog-jshas finished its dynamic import (it loads after the browser is idle) are not captured. Boundary errors are the exception: they are buffered and flushed. - Stack frames are readable only for builds that uploaded source maps: see Source maps.
- Server-side error capture is out of scope.
/api/resume-requestswallows errors on purpose, and server error text risks carrying personal data. The only server-side events are the assistant’s, below. - Trying it locally: see below. To inspect payloads without sending anything, build with a fake key and intercept
/_lg/requests in the browser (for example with Playwright’spage.route); the SDK posts base64 or gzip bodies to/_lg/e/, so decode them or read the event inbefore_send.
Assistant telemetry
The chat route (POST /api/chat) records one outcome per request. It answers how the assistant is used and how it performs. The code is in src/lib/assistant/telemetry/, and the design is in the spec.
Where it goes
- PostHog, as a
$ai_generationevent (PostHog’s LLM Analytics shape) sent byposthog-nodestraight to the ingest host. It is on under the same gate as the browser analytics: a production key,NODE_ENV=production, not staging. Previews without a key stay out. - Vercel runtime logs, as one JSON line (
evt: "assistant_chat") per request. It is always on and never holds a question or an answer.
Only requests with a verified session produce a PostHog event. Requests rejected before that (a bad body, a missing or forged token, the flag off, the assistant unconfigured) appear only as a log line, so abusive traffic cannot inflate the event count.
Identity
distinct_id and $ai_trace_id are an HMAC of the session ID with ASSISTANT_SESSION_SECRET. One conversation is one trace. There is no cookie, no IP address, no person profile ($process_person_profile: false), and geolocation is off.
Properties
| Property | Meaning |
|---|---|
outcome | answered, refused, unsourced, blocked, provider_error, stream_error, aborted (the visitor stopped or left; not an error) |
blocked_reason | For blocked: session_limit, daily_limit or budget |
$ai_model, $ai_provider | The model that answered. Absent for blocked |
$ai_input_tokens, $ai_output_tokens | Token counts from the provider |
$ai_latency, $ai_time_to_first_token | Seconds from the model call to the end of the reply, and to the first text |
$ai_is_error | True for provider_error and stream_error only |
turn_index | How many questions the visitor has asked in this conversation, counting this one |
source_ids, source_count | The cited sections that passed validation |
answer_chars, question_chars | Lengths only |
finish_reason, prompt_version | Why the model stopped, and which system prompt ran (assistantConfig.promptVersion) |
$ai_input | [{ role: "user", content }] with the redacted question. Only while assistant-log-questions is on and the request has no DNT or Sec-GPC signal |
The question flag
assistant-log-questions is a Vercel flag read by the server on each chat request. It fails closed: an error or a missing flag means no question text. It is not in /api/flags, so the browser never learns its value. Turning it off takes effect within about a minute and stops new capture; events already in PostHog stay until they are deleted there.
The redactor (redact.ts) replaces emails, links, phone-shaped numbers and digit runs of six or more, collapses whitespace and caps the text at 300 characters. It cannot detect a name or other free text, so a recorded question can still hold one, the same limit as error messages. Only the latest question of a request is recorded, and never for a blocked request.
The panel shows no notice about recording, by decision, so the browser never needs the flag value.
Dashboard and suggested insights
The “Assistant usage and performance” dashboard (id 2278096 ) holds 16 tiles over the last 30 days, all on the $ai_generation event. It is empty until the first event arrives, and it is not in the weekly digest, because adding a tile to a subscription sends an immediate email. The tiles, top to bottom:
- Headline numbers: questions asked and conversations (each against the previous 30 days), p95 answer time, and error rate.
- Volume: requests per day split by
outcome(blocked requests included), and total requests by outcome. - Speed: median and p95 of
$ai_latency(answer time), and of$ai_time_to_first_token. Both use onlyansweredandunsourcedoutcomes, because a refusal is fast and has no streamed text. - Quality and failures: the refused rate and the unsourced rate as shares of served answers, and provider and stream errors per day.
- Spend and limits: input and output tokens per day, model calls per day against the 400-call
globalDailyBudget(a goal line; days follow the project’s Eastern time while the budget resets at midnight Pacific), and blocked requests byblocked_reason. - Behavior: conversation length (conversations by number of questions) and the ten most cited
source_ids. - Detail: the 50 newest recorded questions. PostHog keeps message content (
$ai_input) on theposthog.ai_eventstable, not inevents.properties, so a plain events query returns it empty. This tile reads that table and stays empty whileassistant-log-questionsis off.
The ratio tiles (error rate, refused and unsourced) are single series with a HogQL expression. With no data the error rate tile shows 0%, so read it together with the questions-asked tile.
What I have not built
Panel events through track() (opened, starter used, answer copied, retry, contact link clicked after a fallback) answer whether the assistant is useful, which server telemetry cannot. They are specified in the design and left for a later change.
Event policy
Every event passes through one before_send stage (src/lib/analytics/policy/), after the exception scrubber and before the internal-traffic tag, so the per-event cap counts only exceptions that are really sent and not the browser-extension and ResizeObserver noise the scrubber discards. It checks the event against EVENT_REGISTRY, which is typed against the catalog in events.ts:
- An event name that is not listed is dropped, including SDK events other than
$pageview,$pageleave,$web_vitalsand$exception. - A listed event with an unknown property, a wrong value or a missing required property is dropped. Values are booleans, fixed enums, slugs, hostnames or bounded integers, never free text.
- Every URL field, including the SDK’s own
$current_url,$referrerand$session_entry_url, loses its query string and hash. Ad click IDs (gclid,fbclidand similar) are removed.$setand$set_onceare removed. $exceptionmay carry the two properties the React error boundaries attach,boundary(errororglobal-error) anddigest(letters, digits,_and-, up to 64). One that is out of bounds is dropped and the exception still goes out.- Each event name has a per-page-load cap, and a payload over its size cap is dropped.
The stage keeps counts of what it dropped (eventPolicy.stats()) for the data-quality dashboard planned in #557. Adding an event means adding it to events.ts and to the registry; the compiler flags a missing rule.
Consent and collection policy
Collection has three purposes (src/lib/analytics/consent/, src/lib/analytics/policy/registry.ts): baseline (today’s cookieless events, always on once the environment gate passes), and the opt-in analytics and diagnostics. No event or capability uses the optional purposes yet, and there is no consent interface yet, so every visitor is baseline only.
- The choice is one
localStoragerecord (lg-consent): both purposes, a status (decidedorrevoked), a policy version and a calendar day. It holds no identifier. When storage is blocked the choice lasts for the page. resolveCollectionPolicyturns the record, Do Not Track and Global Privacy Control into what may send. Either signal turns both optional purposes off. A record from an older policy version counts as no choice.AnalyticsProviderapplies the policy before buffering starts and again on every change, including a change made in another tab.track()drops an event whose purpose is not granted instead of buffering it, so nothing is sent late after a later grant.
Regional rules
An optional layer, off unless NEXT_PUBLIC_ANALYTICS_REGION_POLICY=on, lets a purpose run without an opt-in for visitors in a regime that has a recorded review. I have confirmed this for the United States and Canada, so with the flag on those visitors run every listed capability and see no privacy control; every other visitor keeps the consent flow above. An explicit decline, Do Not Track and Global Privacy Control always win. The matrix, the legal questions it leaves open, the /api/region route and the rollout steps are in analytics-region-policy.md.
SDK options and capability switches
buildSdkConfig (src/lib/analytics/client/sdkConfig.ts) builds the options for posthog.init. With no capability running it returns exactly the options listed above, and a test pins that. Eight optional capabilities exist (src/lib/analytics/capabilities.ts): persistence, geo, engagement, assistantPanel, correlation (purpose analytics) and replay, networkTiming, friction (purpose diagnostics). One runs only when NEXT_PUBLIC_ANALYTICS_CAPABILITIES lists it and the visitor granted its purpose, so the setting can only remove collection. persistence is implemented; the others change nothing in the SDK yet, and a capability gets its entry in the change that implements it. To switch one off, remove it from the list and redeploy.
persistence. Listing it puts the SDK in cookieless_mode: "on_reject" with persistence: "localStorage" and opt_out_capturing_by_default: true. Every visitor still starts cookieless with nothing stored, which was checked in a browser: no cookie, no localStorage key, a server-derived cookieless_… ID. When the visitor’s analytics purpose is granted (an opt-in, or a reviewed regional default), the app calls opt_in_capturing, which writes a random ID and a consent flag to localStorage and no cookie. The events carry that ID in place of the cookieless one, and no person profile exists (person_profiles stays identified_only). When the purpose is lost or consent is revoked the app opts out first, so capture returns to cookieless instead of stopping, and then clears every ph_ and __ph_ key. The $opt_in event is not sent, because the consent store already records the decision. Two guards follow from how posthog-js behaves (both reproduced in a browser on 1.438.2): a saved opt-in flag outranks opt_out_capturing_by_default, so at start the SDK’s saved keys are removed whenever the analytics purpose is not held; and when localStorage cannot be written the SDK falls back to a cookie, so the ID is not started at all then and the visitor stays cookieless. Without opt_out_capturing_by_default, an undecided visitor sends nothing at all under on_reject, which would stop the baseline.
Privacy settings interface
PrivacySettings (src/partials/PrivacySettings/) is mounted in the root layout, and the footer has a “Privacy settings” link that reopens it. Both render nothing unless the build lists at least one optional capability in NEXT_PUBLIC_ANALYTICS_CAPABILITIES, so the default site has no consent interface. A switch appears only for a purpose a listed capability needs, and the panel describes only the listed capabilities. Add a capability to the list only once its disclosure line in privacy.capability.* is accurate.
- While the choice is unknown and no privacy signal is present, a notice sits at the bottom of the viewport. It never takes focus, covers content or blocks a feature. Accept all, Decline all and Choose settings share one look.
- The footer link opens the panel: one switch per offered purpose (off by default), the retention and deletion note, and Accept all and Decline all, in one look. Closing the panel with the corner X or Escape saves the switches (nothing is written if they still show what the panel opened with, or under a privacy signal). The first-visit notice has no X. Focus moves to the heading and returns to the footer link after the panel has faded out.
- With Do Not Track or Global Privacy Control on, the switches render off and disabled, with a line saying why, and the notice does not appear.
- Saving applies at once without a reload (see Revocation, reset and deletion), and a status region announces “Your choices are saved.” Turning every purpose off after a grant counts as revoking.
- Disclosure copy lives in
privacy.*in the locale file. It is draft copy for me to review, not legal text.
Screenshots are in docs/screenshots/issue-537/. Behavior is covered by the Storybook play functions in PrivacySettings.stories.tsx.
Revocation, reset and deletion
What happens in the browser
A change of choice takes effect without a reload, in this tab and in other open tabs (src/lib/analytics/client/lifecycle.ts, src/lib/analytics/consent/runtime.ts):
- Losing the analytics purpose, or revoking, resets the SDK identity with a new device ID and removes every stored identifier (
ph_and__ph_keys in local and session storage, and cookies for the host and for each parent domain of it, since posthog-js can scope a cookie to the registrable domain). A later grant starts a new anonymous ID that nothing links to the old one. The app never callsidentify(), and no ID is shared with the resume form, the contact flow or the assistant. - Losing the diagnostics purpose stops any recording.
- Events of a purpose that went off are dropped from the pending buffer. Baseline events stay buffered, because the baseline keeps running.
- PostHog’s own
opt_out_capturing()is not used for this: it would stop the baseline too. - On every page load without the analytics purpose (declined, revoked, an older policy version, Do Not Track, Global Privacy Control), leftover SDK identifiers are removed.
- Changing the disclosures or purposes means raising
CONSENT_POLICY_VERSION. Every older choice then counts as unknown, so visitors are asked again and lose the optional purposes until they answer.
The cookieless baseline stores nothing, so none of this touches it.
Deletion runbook
Data already sent stays in PostHog until it is deleted there. What can be deleted depends on what identifies it:
- Baseline events carry no identifier, so a request cannot be matched to a person. They are removed only by the retention period of the plan.
- Events and recordings from the analytics and diagnostics purposes are keyed by a random browser ID. They can be deleted when the requester can supply that ID.
Steps for a request, in order:
- Confirm what the requester wants deleted and obtain their browser ID. The privacy panel is meant to show it (#548); until it does, a request without an ID cannot be matched.
- In PostHog, find the events and any recordings for that ID, and delete them with the deletion options the plan offers. PostHog documents deletion through a person only, and this site creates no person records, so whether it reaches events keyed by a browser ID is unverified (see Deletion limits). Check it before the first real request and write the result here.
- Confirm the deletion and tell the requester what was and was not removed.
- Keep the request date and outcome in private notes. Issues in this repository are public, so do not file the request there.
The response time to promise is my decision (#546, open question 2). Do not promise erasure of data the plan cannot delete.
Payload probe
pnpm probe:analytics-payloads (scripts/probes/analytics-payloads.mjs) checks what the browser really sends. It drives a production build in Chromium with the real posthog-js, answers /_lg itself so nothing reaches PostHog, and tests every request body against synthetic secrets, emails, query strings, a URL fragment and typed form text (FIXTURES in analyticsPayloads.mjs). It also answers any request straight to a PostHog host, records it, and reports it as leaving the proxy, so a configuration that bypasses /_lg cannot send anything from the probe; a self-check fires one such request each run to prove the interception works. It also drives consent: no consent record before a choice, Accept all, a second tab following it, a reload, revocation leaving no SDK keys or cookies, and Global Privacy Control hiding the notice and disabling the switches, with that scenario’s traffic evaluated like the others. Switches are turned off by clicking the drawn track, as a person does.
The build must have analytics on, so it is a probe build and never a deployable one:
NEXT_PUBLIC_POSTHOG_ANALYTICS_KEY=phc_probe NEXT_PUBLIC_ANALYTICS_CAPABILITIES=persistence,replay pnpm build
pnpm start -p 3000
pnpm probe:analytics-payloadsExit code 0 means clean, 1 means findings or failed checks, 2 means the probe could not run. Findings name the check (fixture, url-details, click-id, forbidden-event, unknown-event, origin, person-properties) and the event.
posthog-jsdrops events from what it takes for a bot: aHeadlessuser agent,userAgentDatabrands andnavigator.webdriver. The probe overrides all three. Without that the SDK sends nothing and every check passes on an empty list.- It was checked to fail: a build without the event policy stage makes it report
?token=and the URL fragment in$current_url,$web_vitalsand$pageleave. - The evaluation logic and the allowed event list have unit tests that run in
pnpm test. The browser run does not: no CI job runs it yet, which leaves #555’s CI criterion open. Replay payloads are not covered, because no replay capability exists yet.
Retention, access and cost
Targets, what PostHog’s documentation says it can do, and what is still open. The provider facts were read on 2026-10-30 from PostHog’s documentation (links below); the plan this project is on was not checked in the PostHog billing pages, so every “supported” below means “supported by the documented plan tier”.
Retention by data class
| Data class | Target | What PostHog documents | Status |
|---|---|---|---|
| Baseline events (aggregate, no identifier) | 12 months | Events: free plan “1 year”, paid plans “7 years” (events retention ) | Met by the free plan as documented |
| Events keyed by a browser ID (analytics) | 90 days after last use | “You cannot make your retention period shorter to remove data, and a shorter period is not available on request.” Events are deleted through person deletion, project deletion or organization deletion | A shorter period is not a provider setting. Enforcing it needs a scheduled deletion job, which does not exist |
| Session recordings (diagnostics) | 14 to 30 days | Free plan “Up to 30 days”; the period is set in the project’s replay settings and applies only to recordings captured afterwards (replay retention ) | 30 days is the shortest period the project setting accepts (30d, 90d, 1y, 5y, checked 2026-10-31), so 14 days is not a provider setting. Replay is off, so this applies to nothing captured today |
| Diagnostics events (timing, error context) | 14 days | Same as keyed events: no per-class retention | Not enforceable as a provider setting |
These are proposed targets and not guarantees. Do not state a per-class period in the privacy panel or any public text until the row’s status is met. Until then the panel says only that data is kept for a limited time.
Deletion limits
PostHog documents deletion through a person: the Persons page, or a DELETE request with a personal API key and delete_events=true or delete_recordings=true, plus a bulk_delete endpoint (data storage ). It describes no deletion of a single event or recording on its own.
This site sets person_profiles: "identified_only" and never identifies anyone, so a browser ID has no person record. Whether person deletion removes events that belong to an ID with no person was not verified. Test it in a throwaway project before the first real request, and until then the deletion runbook promises nothing for keyed events beyond retention.
Access and credentials
| Credential | Can do | Holder and where | Rotation |
|---|---|---|---|
Project key NEXT_PUBLIC_POSTHOG_ANALYTICS_KEY | Send events only. Public by design | Browser bundle, Vercel Production | Rotate only if abused; a new key needs a redeploy |
POSTHOG_API_KEY (phx_) | Upload source maps (Error tracking write, Organization read) | Vercel Production, Sensitive | Every 90 days, or at once if exposed |
POSTHOG_PERSONAL_API_KEY (phx_) | Read events for the Web Vitals page | Vercel, server only | Every 90 days, or at once if exposed. Scope it to read-only query access |
| PostHog user accounts | Dashboards, recordings, deletion | The owner only | Keep two-factor sign-in on. Add no one without a written reason |
Least privilege means each key carries only the scopes in its row and no key is shared between jobs. The rotation period is a proposal for me to confirm. Recordings and person deletion need a user account, so the account list is the access list for them: review it at each checklist below.
Volume and cost guardrails
The free plan includes, per month, 1M analytics events, 5K session recordings and 100K exceptions (see Free tier). At the #556 budget of at most 30 events per ordinary visit, 1M events covers about 33,000 visits a month; the site had 55 sessions in the 30 days to 2026-10-26.
- Set a billing limit on each product so an unset limit cannot bill overage.
- Add PostHog alerts on the daily event count, the daily recording count and
$exceptionvolume, each at a small multiple of the normal level, delivered to me. Alert availability on the current plan was not checked. - Re-read the volume tiles on the privacy and data-quality dashboard (#557) when it exists.
Review checklist
Run every three months, and after any change to the capabilities list:
- List the PostHog user accounts and personal API keys. Remove what is unused.
- Rotate any key older than its rotation period.
- Compare the replay retention setting with the table above.
- Read the plan’s current retention and billing pages, and update the table’s status column with the date.
- Check the billing limits and alerts still exist.
- Check
NEXT_PUBLIC_ANALYTICS_CAPABILITIESlists only capabilities whose disclosure lines are still accurate. - Run the payload probe against a probe build.
App version
Every event carries two properties that identify the deployed build:
app_version, the semantic version (for example1.24.0). Release Please bumps it, so it names a release and is the readable one for dashboards. Every deploy between two releases reports the same number.app_commit, the git commit of the deployment. It names the exact deploy: rungit show <app_commit>to see that code. It is the same commit as the source-map release version below, so an$exceptionand its symbol set match.
Break any insight or error down by either.
next.config.tsinlinesversionfrompackage.jsonasNEXT_PUBLIC_APP_VERSION(read only; Release Please still owns the file) and Vercel’sVERCEL_GIT_COMMIT_SHAasNEXT_PUBLIC_COMMIT_SHA. Builds with no commit (local, CI) send noapp_commit.parseAppVersionandparseAppCommit(src/lib/analytics/client/buildInfo.ts) accept only amajor.minor.patchversion (with an optional pre-release tag) and 7 to 40 hex characters, so a bad value never becomes free text.tagBuildInfois abefore_sendhook that runs after the event policy, like the internal-traffic tag. It is not a super property:registerwould write the values to the SDK’s storage, and these need none.- A tab left open across a deploy keeps reporting the build it loaded, which is the version that visitor is running.
Source maps
Production stack frames point into minified chunks (/_next/static/chunks/934-<hash>.js). To make Error Tracking show original files, functions and lines, production builds upload their source maps to PostHog. The maps are never served by the site.
The two keys
| Variable | Role | Secret? | Where |
|---|---|---|---|
POSTHOG_ANALYTICS_KEY (browser name NEXT_PUBLIC_POSTHOG_ANALYTICS_KEY) | Public project key (phc_...). Inlined into the browser bundle; lets the site send events. | No | Vercel Production |
POSTHOG_API_KEY | Personal API key (phx_...). Read only by next.config.ts during the build, to upload source maps. | Yes | Vercel Production only, marked Sensitive |
POSTHOG_API_KEY must never be prefixed with NEXT_PUBLIC_ and is not in the env block of next.config.ts (which inlines only the public project key and the Turnstile site key), so it never reaches the client bundle. Create it in PostHog (Account settings, Personal API keys) with the scopes Error tracking: write and Organization: read. The project id (650381) and host (https://us.posthog.com) are constants in src/lib/analytics/build/sourcemaps.ts and config.ts, not variables.
What happens, and when
resolveSourceMapUpload() (src/lib/analytics/build/sourcemaps.ts, unit tested) turns the upload on only when VERCEL_ENV is production and POSTHOG_API_KEY is non-empty. Local builds, CI, Preview, staging and key-less builds skip it entirely: next.config.ts exports exactly the config it always did, no maps are generated and the output is identical.
When the gate holds, next.config.ts wraps the config with withPostHogConfig from @posthog/nextjs-config (a build-time dev dependency; it brings @posthog/webpack-plugin and the @posthog/cli binary). The plugin:
- generates source maps for the build and injects a chunk id into each JS chunk (a
_posthogChunkIdssnippet plus a//# chunkId=...comment), whichposthog-jsattaches to each stack frame aschunk_id; - uploads the maps with the PostHog CLI under the release
operation-looking-glass, versionVERCEL_GIT_COMMIT_SHA(the deployed commit); - deletes the maps after upload (
deleteAfterUpload).
productionBrowserSourceMaps is never turned on, and no .map file is deployed.
The build runs with next build --webpack, but the plugin cannot see that flag. On Next 16 and later it assumes Turbopack unless WEBPACK=1, and then uploads from runAfterProductionCompile, after the cleanup hook below has already deleted every map. That fails the build (found 0 pairs, Oops! no source files found, exit 1), which is what stopped the v1.6.0 production deploy. So next.config.ts calls pinPostHogToWebpack() whenever the gate holds, which sets WEBPACK=1 and makes the plugin upload during the webpack compile. A build log line Processing source maps from compilation hook... means the pin stopped working. Do not set TURBOPACK: Next rejects it together with --webpack.
Failure behaviour
An upload failure does not fail the build or the deploy. The plugin logs [PostHog Webpack] Error ... and carries on. Because it deletes maps only after a successful upload, next.config.ts also runs a runAfterProductionCompile hook (gated the same way) that deletes any .map file left in .next and logs [source maps] removed N leftover .map file(s). So a failed upload costs only readable frames for that deploy; it never leaves maps on the public site. Look for the [PostHog Webpack] lines in the Vercel build log if frames are unreadable.
The scrubber (scrubExceptionEvent) trims only the query string and hash of filename/abs_path; chunk_id, line, column and function are untouched (covered by a test), and PostHog matches frames to maps by chunk_id.
How to verify
- In PostHog, open Error Tracking, Settings, Symbol sets: a set per chunk should be listed for the release
operation-looking-glassand the deployed commit. - Trigger a deliberate error in a production build of the site (for example a temporary throw in a click handler) and check in Error Tracking that its frames show original file names, functions and lines instead of minified chunk positions.
- Confirm no public maps:
curl -I https://antmejia.com/_next/static/chunks/<any chunk>.js.mapreturns404.
To test the gate locally without a real key (the upload fails with a 401, the build still passes, no maps remain): VERCEL_ENV=production POSTHOG_API_KEY=phx_fake_for_local_test pnpm build. Use a made-up value, never the real key.
Docs site and Storybook
The docs site (Nextra, docs-site/) and the published Storybook send cookieless events to the same PostHog project as the site, told apart by a site property (docs or storybook). The free plan allows one project. Neither app has a consent interface or any optional capability: both run the baseline only, with the posture listed under What is not collected. The design is in the spec.
Events
| Site | Event | When | Properties |
|---|---|---|---|
| both | $pageview | A docs route change, or a story or docs page finishing its render | site, app_commit. On Storybook the URL is /story/<id> or /docs/<id>, built from the entry id |
| both | $exception | An unhandled error or promise rejection | Scrubbed like the site’s: no query strings, no emails, messages capped at 300 characters |
| docs | docs_search_used | The first search in each opening of the search dialog returns a list | result_count: 0, 1-5 or 6+. Never the query |
| docs | outbound_link_clicked | A click on a link to another host | host |
| storybook | story_viewed | A story or docs page finishes rendering; the same entry twice in a row counts once | story_id, group (Foundations, Components, Containers, Partials or Sections; absent otherwise), view_mode (story or docs), theme (system, light or dark) |
PostHog also sends $pageleave and $web_vitals from both apps. Every event carries site and, on a Vercel build, app_commit.
What keeps it narrow
- Each app has one
before_sendstage (docs-site/lib/analytics.mjs,.storybook/analytics/policy.ts). It drops an event name that is not listed, a custom event with an unknown property or a value outside its shape, an event over its per-page-load cap, and a payload over 20,000 characters. It removes query strings and hashes from URL fields and$set/$set_once, and it tagssiteandapp_commit. - posthog-js adds
distinct_id,tokenandtitleto every event. The stage allows those three plain keys, the same asSDK_PLAIN_KEYSin the site’s event policy. Without the exemption every custom event is dropped; the first browser run found this, and unit tests with hand-made events did not. - Campaign parameters are off at the source and removed again by the stage. posthog-js 1.438.2 copies
utm_*tags and ad-network click IDs (gclid,fbclidand about twenty more) from the query string into plain event properties (save_campaign_params, on by default), so a visit to?utm_term=private-searchsent that value on a$pageviewwhile$current_urlwas clean. Both apps setsave_campaign_params: false, and the stage drops the same keys, including the$session_entry_and$initial_copies, before it checks anything else. Without that, a search or outbound click fired while the URL still held a tag would fail its property check and vanish. A test keeps both lists a superset of the site’sCLICK_ID_KEYS. - Events keep the page they were fired on. The SDK reads the location when it captures, so an event queued while posthog-js loads would otherwise report whatever page the visitor is on by then. Reproduced on the docs build: a visit to
/architecture,/stylingand back to/architecturewith the SDK chunk held back reported all three views as/architecture. The docs client now stamps$current_urland$pathnamewhen the event is fired (createTracker), and Storybook writes the story URL into both of a view’s events when it builds them (storyViewEvents). - The docs copy of the scrubber mirrors
src/lib/analytics/client/errors.ts, becausedocs-site/has its own lockfile.src/lib/analytics/client/docsScrubberParity.test.tsruns both on the same fixtures. Storybook imports the site’s scrubber directly. - Storybook reports through the preview iframe, whose own URL is always
iframe.html. A story is therefore reported bystory_id, and events that still carry the iframe URL (page leave, web vitals, errors) get the current story’s URL.
When it runs
Both apps are a no-op unless the build is a Vercel production deployment (VERCEL_ENV === "production") and a key is set. Local runs, CI, preview deployments and the Vitest story run inline an empty key.
- Docs site:
next.config.mjsinlinesNEXT_PUBLIC_POSTHOG_ANALYTICS_KEYand the commit for production only. The key comes fromPOSTHOG_ANALYTICS_KEYorNEXT_PUBLIC_POSTHOG_ANALYTICS_KEY. - Storybook:
.storybook/main.tspasses the key to the preview asSTORYBOOK_POSTHOG_ANALYTICS_KEY, again for production only. Set the key in Vercel asPOSTHOG_ANALYTICS_KEYand leaveSTORYBOOK_*names alone: Storybook exposes those to every build. The Next.js framework layer also bundles the site’s own publicenvblock, includingNEXT_PUBLIC_POSTHOG_ANALYTICS_KEYwhen it is set, into every Storybook build. That was already so. Nothing in Storybook starts the site’s analytics, and the key is public by design, so the only effect is the string in the bundle.
posthog-js loads with a dynamic import() after the browser is idle, so it is not in either app’s initial bundle.
Setup
-
Key (done 2026-11-01). The public
phc_project key is set asPOSTHOG_ANALYTICS_KEY(plain, Production only) in both the docs and the Storybook Vercel projects. It takes effect at the next build of each project. -
Proxy. The docs project has the
/_lgrewrites indocs-site/vercel.json. They go live with the first docs production deploy that includes them and have not been tested against a deployment. The Storybook project has no configuration in the repository (the rootvercel.jsonis the site’s), so its three rewrites are project-level routes (Vercel dashboard, Routing), added and published on 2026-11-01. They must be in regex form with a capture group in the destination, in this order:Source Destination ^/_lg/static/(.*)$https://us-assets.i.posthog.com/static/$1^/_lg/array/(.*)$https://us-assets.i.posthog.com/array/$1^/_lg/(.*)$https://us.i.posthog.com/$1The
:path*form thatvercel.jsonandnext.config.tsuse saves without error in this rule list but is not substituted in the destination, so PostHog received a literal:path*and answered 404. Checked againststorybook.antmejia.comafter the fix:/_lg/static/recorder.js, the arrayconfig.jsandconfigreturn the same status and byte counts as onantmejia.com, and an emptyPOST /_lg/e/gets PostHog’s “request missing data payload” 400 from both. -
After the first production deploys, open Live events in PostHog. Check that events arrive with
siteset, that visitors are not collapsed into one, and that no property holds a query string, a search phrase or an email.
Checked in a browser
A production-style build of each app with a fake key, /_lg answered by a script and any direct PostHog request recorded, on 2026-11-01. The docs site sent $pageview for the first route and a client-side navigation, one docs_search_used with 6+ after a two-word query, and one outbound_link_clicked with the host only. Storybook sent a $pageview and story_viewed for a story, a second story reached through the sidebar search, and a docs page. No body held the query string (?secret=1), the fragment, the typed search text or an email, and no request went straight to PostHog.
Not observed in that run: $pageleave and $web_vitals. They are sent as the page unloads or after a delay, and the script does not capture unload beacons. They go through the same stage as the events above, so a missing one points to configuration. Check for them in Live events after the first deploy.
Limits
- The saved insights on the “Portfolio engagement” dashboard (visitors and sessions, top pages, sessions by device, the landing depth funnel, Web Vitals, exceptions) count every matching event in the project, so once the docs site and Storybook send events they are included. They do not filter on
site. Addsiteis not set (or equalsportfolio) to those insights, or split them bysite, before reading the numbers as the portfolio’s alone. - The project’s default test-account filter keeps only events whose URL starts with
https://antmejia.com/, so an insight with “Filter test accounts” on shows no docs or Storybook events. I left the filter as it is, because widening it would also add their pageviews to every existing site insight that uses it. Leave it off in insights for these two apps, and split bysitewhen comparing. - Events fired before posthog-js has loaded wait in a buffer of 20; the oldest go first.
- A visitor who leaves within a few seconds of the first view may send nothing, since the batch has not flushed. This lowers the counts a little and adds no bias that I can name.
docs_search_usedfires once per opening of the dialog, at the first result list, so it counts searches, one per opening. The bucket is the number of matching pages Pagefind reports.- Story ids are code-derived slugs. A story whose title starts with a group other than the five reports no
group.
Rollback
Remove the key from the project and redeploy. The apps are then a no-op.
Adding an event
- Add a line to
AnalyticsEventsinsrc/lib/analytics/tracking/events.ts. This is the only place events are defined; anything not listed, or with the wrong properties, fails to compile. - Call
track("event_name", props)from@/lib/analytics/tracking/track. - Keep property values to booleans, enum-like strings and hostnames.
- Add the event to the table above.
Trying it locally
Development is deliberately silent. To see events, run a production build with a key (a throwaway PostHog project is best):
POSTHOG_ANALYTICS_KEY=<key> pnpm build && POSTHOG_ANALYTICS_KEY=<key> pnpm start -p 3917The key is inlined at build time, so it has to be set for pnpm build. Port 3917 avoids clashing with a dev server (or another worktree) on 3000. Open the site and watch the Live events view in PostHog.
Setup
- Create a PostHog project in the US region.
- In the PostHog project settings, enable both of these (Settings, project level):
- Cookieless mode. Required. With
cookieless_mode: "always"the browser sends events without an identifier and PostHog derives an anonymous one on the server. If this project setting is off, cookieless events are ignored and nothing shows up. - Discard client IP data. Keeps visitor IP addresses out of stored events. It was off until 2026-10-26, when it was turned on. Before that, none of 150 pageviews carried an IP anyway, because cookieless events drop the IP after PostHog hashes it. The setting makes the guarantee hold even if that behavior changes. Whether visitor counts stay the same with it on was not checked against new traffic.
- Cookieless mode. Required. With
- Set
POSTHOG_ANALYTICS_KEY(the public project key;NEXT_PUBLIC_POSTHOG_ANALYTICS_KEYalso works) in the Vercel Production environment only. Vercel’s env-var UI defaults a new variable to all environments, so untick Preview and Development and set it for Production only (Preview builds also run withNODE_ENV=production, so a key there would send real events into the production data). Staging is silent even if the key is present, but keeping it out of those environments is the simpler guarantee.
After setting the production key
- Confirm events appear at all. If none do, the project’s cookieless mode setting is probably off.
- Confirm unique visitors look plausible and are not collapsed into a single visitor. Cookieless identity is derived from IP and user agent, so a single visitor would mean the client IP is not passed through the first-party
/_lgproxy. Do not expect a country: see Web Analytics. - Confirm no event property contains a name, email or query string.
There is no host variable: the US hosts are constants in src/lib/analytics/config.ts.
Operating the PostHog project
The saved charts, schedules and settings that live inside the PostHog project. The project is “Landing Site” (id 650381, US region).
Dashboard and weekly digest
The “Portfolio engagement” dashboard (id 2259843 ) has ten tiles, each over the last 30 days:
| Insight | Query | Answers |
|---|---|---|
| Resume request funnel | resume_dialog_opened, resume_request_submitted, resume_email_sent, with a one-day window | Where requests drop. The gap between the last two steps is failed sends |
| Internal link clicks by surface | internal_link_clicked broken down by source, as a ranked bar chart | Which calls to action get used |
| Landing sections viewed | section_viewed broken down by section | Which landing sections visitors reach |
| Outbound clicks by host | outbound_link_clicked broken down by host | Where visitors leave for |
| Visitors and sessions per day | $pageview as daily unique visitors and unique sessions | Traffic over time |
| Top pages | $pageview broken down by $pathname, top 10 | Which pages are read |
| Sessions by device | $pageview unique sessions broken down by $device_type | Desktop against mobile |
| Landing depth funnel | $pageview on /, section_viewed for impact, then experience, then resume_dialog_opened, with a one-day window | How far landing visitors get |
| Field Web Vitals (p75) | 75th percentile of $web_vitals LCP, INP and CLS, as a table | Field performance. Samples are few and include the owner’s visits |
| Exceptions per day | $exception count, daily | Whether errors reach visitors |
A dashboard subscription, “Portfolio engagement weekly”, emails all ten tiles to me every Monday at 9am Eastern. Its AI summary is off because it uses AI credits. A subscription stores insight IDs, so after a tile is added, removed or replaced, update the subscription’s selection too. The free plan allows five subscriptions per project.
The schedule is stored as 14:00 UTC, which is 9am Eastern Standard Time. Whether it follows daylight saving time was not checked. Look at the next delivery date after the clocks change in March.
Web Analytics
PostHog’s Web Analytics view reads the $pageview events the app sends, so it works under cookieless mode with no extra setup. On 2026-10-26 it showed 45 visitors, 150 views and 55 sessions for the previous 30 days. A returning visitor counts once per day, as described under Cookieless mode.
Country, region and city are empty for every session, so a geography chart shows nothing. Tested 2026-10-31 with “Discard client IP data” on: an event from a visitor whose analytics purpose was granted (persistent ID, cookieless_mode: "on_reject") carried country and city from PostHog’s GeoIP and no $ip, so geography for those visitors needs no raw IP. City is town-level. Cookieless events still carry none of it. PostHog drops the IP of a cookieless event before its GeoIP step runs, which leaves nothing to look up (posthog#48660 , open at the time of writing). The /_lg proxy is not the cause: no pageview in the project carries an IP.
Error alerts
No alert destinations exist yet. Only two error issues have ever occurred, both resolved with one event each, and the scrubber already drops extension errors and ResizeObserver warnings, so there are no suppression rules either.
When an alert is worth having, use the “issue reopened” trigger. It fires on regressions of issues that were already triaged. Error alerts deliver to Slack, a webhook, Linear or GitHub. The project has only the GitHub integration, which would file an issue per alert, so connect Slack first (Project settings, Integrations). Destinations include 10,000 free trigger events a month.
Replay, heatmaps and console logs
Session replay, heatmaps and console-log capture are off in the code and, since 2026-10-26, off in the project settings too, so a code change cannot start recording by accident. Keep both in step.
Replay would be the only one worth revisiting, for the handful of resume-dialog sessions that stop before submitting. Three things stand in the way:
- PostHog masks input fields by default but not page text.
- An open posthog-js issue reports no recordings at all under
cookieless_mode: "always"(posthog-js#3073 ), and PostHog’s docs do not settle it. - The
before_sendscrubber covers events, and whether it covers replay data was not checked.
If it is revisited, record only sessions that open the dialog or raise an exception, mask all text, and try it in a throwaway project first. PostHog files heatmaps under autocapture, which stays off, and click maps were not confirmed to work without it. Console logs only attach to recordings.
Free tier
The free plan includes, per month, 1M analytics events, 5K session recordings, 1M feature flag requests, 1,500 survey responses and 100K exceptions, with one project and one year of retention (PostHog pricing , read on 2026-10-26). The site had 55 sessions in the 30 days before that date, so no quota is close. The app uses product analytics, Web Vitals and error tracking. Replay, heatmaps, surveys, feature flags and experiments stay off for privacy. If the organization moves to pay-as-you-go, set a billing limit on each product, because an unset limit bills overage.
Field Web Vitals page
/performance shows the 75th percentile of LCP, INP and CLS from the $web_vitals events PostHog already collects (capture_performance). It adds no tracking: the browser sends nothing new, and the page only reads data that exists.
- Read path. The route is a server component (
src/app/performance/page.tsx).getFieldVitals()insrc/lib/analytics/vitals/posts one HogQL query toPOST /api/projects/<id>/query/on the PostHog host and caches the response for a day (revalidate = 86400on the fetch and on the page). The query reads the last 28 days. - Credentials.
POSTHOG_PERSONAL_API_KEY(a personal API key with thequery:readscope only),POSTHOG_PROJECT_ID, and optionallyPOSTHOG_HOST(defaulthttps://us.posthog.com). All three are validated insrc/config/env/server.ts, have noNEXT_PUBLIC_form, and are read only by server code, so they never reach the browser bundle. This key is separate fromPOSTHOG_API_KEY, which uploads source maps at build time and needs different scopes. Set all three in the Vercel Production environment only, marked Sensitive. - When the route exists. Like analytics, only in a production build, never on staging. It returns a 404 when a variable is missing, the request fails, or any of the three metrics has fewer than 100 samples in the window (
MIN_SAMPLESinvitals.ts). The route is not in the sitemap and nothing links to it. Link to it once the figures are worth showing. - Scope. The docs site and Storybook send
$web_vitalsto the same project, taggedsite. The query keeps events whosesiteis missing orportfolio(coalesce(properties.site, 'portfolio') = 'portfolio'), so only the portfolio’s own measurements reach the published percentiles. The portfolio sets nosite. The predicate was run against the live project before it shipped. Insights and dashboards in PostHog are not covered by this: see Docs site and Storybook. - Caveats. Visitors who send Do Not Track are not counted. Samples include my own visits. Cookieless identity changes the visitor count but not the per-event percentiles.
Cookieless mode and its trade-off
The client is initialised with cookieless_mode: "always", which the installed posthog-js (1.438.2) supports. There was no need for the persistence: "memory" fallback. Because nothing is stored in the browser, a returning visitor cannot be linked across days: PostHog counts unique visitors per day, and the same person on two days shows up as two visitors. That is the price of having no cookie and no banner.
First-party proxy
The browser never talks to PostHog directly. next.config.ts rewrites /_lg/* to PostHog (src/lib/analytics/build/proxy.ts): /_lg/static/* and /_lg/array/* go to https://us-assets.i.posthog.com, everything else to https://us.i.posthog.com. Same-origin requests are less likely to be blocked by ad blockers.
The path is deliberately not /analytics, /posthog, /tracking or /telemetry, because blockers match those names. Do not rename it to one of them.
PostHog’s proxy needs skipTrailingSlashRedirect: true in next.config.ts, otherwise its API calls are redirected and fail. This setting is site-wide, not limited to /_lg: Next.js no longer redirects /about/ to /about for any route.