PostHog Analytics¶
Complete guide for product analytics with PostHog in the Freeze Design webshop.
Instrumentation is present; delivery depends on the key (verified 2026-11-01, v1.57)
The PostHog client is instrumented in the frontend:
components/providers/PostHogProvider.tsxcallsinitPostHog()fromlib/posthog.tson mount and captures$pageviewon every App Router navigation. It is mounted inapp/(shop)/layout.tsxonly, so admin routes never load posthog-js.instrumentation-client.tsis deliberately empty.lib/posthog.tsinitialises posthog-js withNEXT_PUBLIC_POSTHOG_KEY(capture_exceptions: true,before_send: [dropInternal, privacyBeforeSend, tagEnvironment], super propertyenvironment) and exposesidentifyUser/resetUser,trackEventand theecommerceEventshelpers.
Whether events actually arrive in PostHog depends on NEXT_PUBLIC_POSTHOG_KEY being set in the environment where the frontend runs, and on the visitor's cookie choice: without a choice or with Minimaal, PostHog measures anonymously and cookieless; with Accepteren it also records sessions and profiles; with everything switched off on /cookies nothing is sent. If no events show up, verify the key first. Sentry remains the primary error tracker regardless.
Staging and production share one PostHog project (id 106820). Every event carries environment (NEXT_PUBLIC_ENVIRONMENT), and production numbers are filtered on environment = production and $host = www.freezedesign.nl.
Overview¶
PostHog provides product analytics, session recording, and feature flags. We use the EU-hosted instance for GDPR compliance.
| Feature | Status | Free Tier |
|---|---|---|
| Product Analytics | ✅ Instrumented (delivery needs NEXT_PUBLIC_POSTHOG_KEY; anonymous cookieless events without consent, full events after Accepteren) |
1M events/month |
| Session Recording | ✅ Instrumented (disable_session_recording: false in lib/posthog.ts; records only after Accepteren) |
5K recordings/month |
| Feature Flags | ✅ Available (not used in the shop yet) | Unlimited |
| A/B Testing | ✅ Available (not used yet) | Unlimited |
| Admin "Website" tiles | ✅ Backend reads the query API with a personal key (see below) | — |
Setup¶
1. Create PostHog Account¶
- Go to eu.posthog.com (EU instance for GDPR)
- Sign up with GitHub or email
- Create a new project (e.g., "Freeze Design Production")
- Copy your Project API Key from Settings → Project → Project API Key
2. Configure Environment¶
Add to frontend/.env.local:
For production, add these as secrets in your deployment platform.
3. Verify Installation¶
- Start the frontend:
npm run dev - Choose Accepteren in the cookie banner for full events; with Minimaal (or no choice) you still see anonymous cookieless events, which needs "cookieless server hash mode" enabled in the PostHog project settings
- Open browser DevTools → Network tab
- Filter by "posthog"
- Navigate between pages (shop pages — PostHog is not loaded on admin routes)
- You should see requests to
eu.i.posthog.com
Architecture¶
flowchart TD
LO["app/(shop)/layout.tsx<br/>dynamic import"] --> PP["PostHogProvider<br/>initPostHog() + $pageview per route"]
PP --> LIB["lib/posthog.ts<br/>posthog.init, privacyBeforeSend,<br/>trackEvent / ecommerceEvents"]
CC["lib/cookieConsent.ts<br/>accepted / minimal / rejected"] --> LIB
LIB --> PH[posthog-js client]
PH --> EU["eu.i.posthog.com<br/>(EU instance, GDPR)"]
BE["backend apps/analytics/website.py<br/>HogQL via personal API key"] --> EU
BE --> ADM["Admin → Cijfers → Website"]
The shop sends events through one consent-aware client; the admin never loads it and reads aggregated numbers from the backend instead.
Admin routes are excluded
app/(shop)/layout.tsx loads PostHogProvider via a dynamic import; the
admin layout (app/admin/(protected)/layout.tsx) does not. Admin sessions
are deliberately kept out of the product analytics (and posthog-js stays
out of the admin bundle).
Once PostHog has started in the shop, it stays active after a client-side
navigation to /admin. privacyBeforeSend in lib/posthog.ts therefore
drops every event whose path, or the browser's current path, is under
/admin.
Our own browser counts nowhere in production
Since #1075 the admin layout calls markInternalBrowser() (lib/internalTraffic.ts)
once the admin API answers, which sets freeze_intern in localStorage. In
production (NEXT_PUBLIC_ENVIRONMENT=production) skipsTracking() then keeps
initPostHog and the $pageview capture from running, and dropInternal, first in
before_send, drops events and recordings when the mark arrives mid-visit (shop in
one tab, admin login in another). The switch "Deze browser telt mee in de
websitecijfers" in Cijfers → Website turns the browser back on; that choice is
kept on later logins. Staging counts every browser, so measurements can be tested
there.
Automatic Tracking¶
These events are tracked automatically:
| Event | Trigger | Data |
|---|---|---|
$pageview |
Page navigation (captured by PostHogProvider, capture_pageview: false in the init) |
URL, referrer |
$pageleave |
Page exit | Time on page |
$autocapture |
Clicks, inputs (posthog-js defaults: '2025-05-24') |
Element info |
$exception |
Uncaught errors (capture_exceptions: true); stack traces are readable through the source maps the frontend build uploads (lib/posthogSourcemaps.ts, needs POSTHOG_PERSONAL_API_KEY and POSTHOG_PROJECT_ID) |
Error, URL |
$web_vitals |
LCP/INP/CLS, when web-vitals autocapture is on in the project | Used by the "Snelheid" tile |
Every event also carries environment (development, staging or production): registered
as a super property in loaded and stamped on every event by tagEnvironment in
before_send (v1.57, websitecheck W43). The super property alone was not enough: when a
visitor accepted cookies mid-visit PostHog switched storage and 10–20% of the events lost
the property. The backend queries therefore use
coalesce(properties.environment, 'production') = 'production' on the production host.
Custom E-commerce Events¶
Import and use the e-commerce event helpers (ecommerceEvents in lib/posthog.ts).
Where they fire today (verified against the call sites, v1.57):
| Event | Fires in | Properties |
|---|---|---|
product_viewed |
ProductenSlugPageClient (once per product per page visit, not on category pages) |
productId, productName, price |
product_added_to_cart |
ProductInfo, the designer, and since v1.57 also the Namen & nrs tab and a team order |
productId, productName, quantity, price; bron = namen_nummers or team for those two (absent for the plain button) |
team_order_started |
ProductInfo, the "Ontwerp voor je team" button (v1.53) |
productId, quantity |
team_order_added_to_cart |
designer, the whole team in the cart with one button (v1.53) | productId, quantity, withNames |
checkout_started |
cart page | cartValue, itemCount |
discount_code_applied / discount_code_rejected |
checkout (v1.53, websitecheck W42) | code (max 50 chars), discountAmount; or reason: not_found, expired, minimum, not_applicable, empty_cart, other (discount_code_reason from POST /api/cart/apply-discount/) |
order_completed |
thank-you page | orderId, orderValue, itemCount |
design_saved |
designer | designId |
whatsapp_clicked |
WhatsAppVraagKnop (product page and designer, behind whatsapp_buttons_enabled) |
location (pdp / designer), productId |
design_created, product_removed_from_cart |
helpers exist, no call site | — |
import { ecommerceEvents } from '@/lib/posthog';
// Product viewed
ecommerceEvents.viewProduct('prod-123', 'T-Shirt Classic', 24.99);
// Added to cart
ecommerceEvents.addToCart('prod-123', 'T-Shirt Classic', 2, 24.99);
// Removed from cart
ecommerceEvents.removeFromCart('prod-123', 'T-Shirt Classic');
// Checkout started
ecommerceEvents.beginCheckout(149.97, 3);
// Order completed
ecommerceEvents.completeCheckout('order-456', 149.97, 3);
// Design created in designer
ecommerceEvents.designCreated('prod-123', 'custom-print');
// Design saved
ecommerceEvents.designSaved('design-789');
Custom Events¶
Track any custom event:
import { trackEvent } from '@/lib/posthog';
// Track with properties
trackEvent('size_chart_opened', {
productId: 'prod-123',
sizeType: 'clothing',
});
// Track simple event
trackEvent('newsletter_subscribed');
Add a new event as a named helper on ecommerceEvents with a comment that says where it
fires and why (see whatsappClicked and discountCodeRejected), never raw PII, and keep
free text short (code.slice(0, 50)). Update the table above.
User Identification¶
Identify logged-in users for cross-session tracking:
import { identifyUser, resetUser } from '@/lib/posthog';
// After login
identifyUser(user.id, {
email: user.email,
name: user.name,
plan: user.subscriptionPlan,
});
// After logout
resetUser();
Feature Flags¶
Create a Feature Flag¶
- Go to PostHog → Feature Flags
- Click "New feature flag"
- Set the key (e.g.,
new-checkout-flow) - Configure rollout percentage or user targeting
- Save
Use in Code¶
import posthog from 'posthog-js';
// Check if feature is enabled
if (posthog.isFeatureEnabled('new-checkout-flow')) {
// Show new checkout
} else {
// Show old checkout
}
// Get feature flag value (for multivariate flags)
const variant = posthog.getFeatureFlag('pricing-experiment');
if (variant === 'discount-10') {
// Show 10% discount
}
React Pattern¶
The shop uses its own PostHogProvider (not the one from posthog-js/react), so
the useFeatureFlagEnabled hook is not wired up. Read a flag after the flags
have loaded:
import { useEffect, useState } from 'react';
import posthog from 'posthog-js';
function CheckoutButton() {
const [showNewCheckout, setShowNewCheckout] = useState(false);
useEffect(() => {
return posthog.onFeatureFlags(() => {
setShowNewCheckout(posthog.isFeatureEnabled('new-checkout-flow') === true);
});
}, []);
return showNewCheckout ? <NewCheckoutButton /> : <LegacyCheckoutButton />;
}
No feature flag is used in the shop today; feature switches for Eefje live in
Winkelinstellingen (SiteSettings), not in PostHog.
A/B Testing¶
Create an Experiment¶
- Go to PostHog → Experiments
- Click "New experiment"
- Set experiment name and feature flag key
- Define variants (control, test)
- Set goal metric (e.g.,
order_completed) - Set minimum sample size
- Launch experiment
Track Experiment Goal¶
// The goal event is automatically tracked when you use ecommerceEvents
ecommerceEvents.completeCheckout(orderId, orderValue, itemCount);
// Or track custom goal
trackEvent('experiment_goal_reached', {
experiment: 'pricing-test',
variant: 'discount-10',
});
Session Recording¶
Session recordings are enabled in the init, but PostHog only records after the
visitor chose Accepteren; with Minimaal or no choice it runs cookieless and
records nothing. Configure in lib/posthog.ts:
posthog.init(POSTHOG_KEY, {
// Disable to save quota
disable_session_recording: false,
// Mask sensitive data
mask_all_text: false, // Set true to mask all text
mask_all_element_attributes: false,
});
View Recordings¶
- Go to PostHog → Recordings
- Filter by:
- Page URL
- User properties
- Events performed
- Watch recording to understand user behavior
Dashboard Setup¶
Recommended Dashboards¶
Create these dashboards in PostHog:
1. E-commerce Funnel¶
- Go to Insights → New insight
- Select "Funnel"
- Add steps:
product_viewed,product_added_to_cart,checkout_started,order_completed - Save to dashboard
2. Key Metrics¶
| Metric | Insight Type | Event |
|---|---|---|
| Daily Active Users | Trends | $pageview (unique users) |
| Conversion Rate | Funnel | Full e-commerce funnel |
| Avg Order Value | Trends | order_completed → avg of orderValue |
| Cart Abandonment | Funnel | Cart → Checkout drop-off |
3. Designer Usage¶
Track product designer engagement:
design_saved- Designs saved (fires today)design_created- Helper exists, no call site yetteam_order_started→team_order_added_to_cart- the team flow from product page to cart;product_added_to_cartwithbron = teamornamen_nummerscounts those in the shop funnel too- Time in designer (session recording)
Admin "Website" tiles and the weekly check¶
Since v1.50 the admin shows production numbers without anyone opening PostHog:
- Cijfers → Website (
frontend/components/admin/cijfers/WebsiteTab.tsx,components/admin/dashboard/WebsiteSection.tsx) has five tiles: visitors and sources, the shop funnel (product_viewed→product_added_to_cart→checkout_started→order_completed), orders per source (v1.59:order_completedper session source,$entry_utm_sourceor else$entry_referring_domain, grouped as Google, Instagram, WhatsApp, direct and other), errors customers hit (from Sentry, without admin errors) and the slowest pages (LCP/INP p75 against Google's limits, grey under 5 measurements). - The backend (
backend/apps/analytics/website.py) queries the PostHog query API with HogQL usingPOSTHOG_PERSONAL_API_KEY(read-only, projectPOSTHOG_PROJECT_ID, hostPOSTHOG_API_HOST) and the Sentry issues API withSENTRY_API_TOKEN; the keys never reach the browser. Results are cached for an hour; a tile without a key says "Nog niet ingesteld", a failed call "niet beschikbaar". Paths are scrubbed with the same rules asprivacyUrl.ts. - Every Monday at 06:00 Amsterdam time (
CELERY_TIMEZONE) the Celery taskanalytics.save_website_weekstores the past week as aWebsiteWeekSnapshot; each tile except orders per source shows a line over the last 12 weeks.python manage.py website_weekcijfers_inlezen --weken 12loads earlier weeks;python manage.py website_weekcijfers_status(v1.55) lists the latest snapshots read-only (week, written when, status per tile), so the Monday check can read the week run throughfreeze-rowithout a Django shell. - The cloud routine Websitecheck (
.claude/skills/websitecheck/) reads PostHog and Sentry through the claude.ai connectors on Monday morning, writes.planning/weekrapporten/<year>-W<week>.md(a plain-language part for Eefje, a technical part for Ivar) and proposes todos in a PR;websitecheck-discord.ymlposts the summary. It counts production only (coalesce(properties.environment, 'production') = 'production', v1.57), because staging shares the project. Design:docs/PLAN-website-monitoring.md.
GDPR Compliance¶
Our PostHog setup is GDPR compliant:
| Setting | Value | Purpose |
|---|---|---|
api_host |
eu.i.posthog.com |
EU data residency |
respect_dnt |
true |
Honor Do Not Track |
opt_out_capturing_by_default |
true |
No cookies, recordings or profiles before Accepteren |
cookieless_mode |
'on_reject' (unless everything is off) |
Anonymous measurement without cookies for Minimaal / no choice |
property_denylist |
['$ip'] |
Don't store IP addresses |
before_send |
[dropInternal, privacyBeforeSend, tagEnvironment] |
Nothing from our own browser in production; no secret links, order ids or admin pages (see below); environment on every event |
persistence |
localStorage+cookie |
User consent controls |
Secret links and order ids¶
The key in /auth/reset-password/<key> and /auth/verify-email/<key> gives
access to an account. lib/privacyUrl.ts replaces it with :key, and an order
id in /orders/<id> with :id: in paths, full URLs and paths inside a query
string. It runs before an event leaves the browser:
- PostHog:
privacyBeforeSend(before_send) on all properties, including nested web vitals and person properties; for session recordings only thehrefof meta events. - Sentry:
sentryPrivacyHooksinlib/sentry.ts(beforeSend,beforeSendSpan,beforeBreadcrumb) for the client, server and edge init, andscrubReplayFramefor the frames a replay adds. Since@sentry/nextjs11 spans are streamed one by one and there are no transaction events, sobeforeSendSpanscrubs the name and attributes (url.full) of every span.sentryDataCollectionkeeps the v10 defaults: no visitor IP address, cookies or request bodies in Sentry (v11 collects all of these unless told otherwise).
Events recorded before this change still contain the keys until their
retention ends. Design: docs/PLAN-website-monitoring.md §4.1.
Cookie Consent Integration¶
The cookie banner is implemented in frontend/components/CookieConsent.tsx
(buttons Accepteren and Minimaal) and the full switch on /cookies
(CookieSettings.tsx). lib/cookieConsent.ts stores the choice under the
cookie_consent key in localStorage as accepted, minimal or rejected;
initPostHog() reads it on init and applyConsent() applies a change at once:
import { saveConsent, readConsent } from '@/lib/cookieConsent';
saveConsent('accepted'); // cookies, recordings, profiles → posthog.opt_in_capturing()
saveConsent('minimal'); // anonymous, cookieless (cookieless_mode 'on_reject'), opted out
saveConsent('rejected'); // nothing at all
const current = readConsent(); // 'accepted' | 'minimal' | 'rejected' | null
Debugging¶
Enable Debug Mode¶
Debug mode is automatically enabled in development. For production debugging:
Common Issues¶
| Issue | Solution |
|---|---|
| No events appearing | Check NEXT_PUBLIC_POSTHOG_KEY is set |
| No events despite key set | The visitor switched everything off on /cookies (rejected), or "cookieless server hash mode" is off in the project settings; choose Accepteren to be sure |
| No events on admin pages | Expected: PostHog is deliberately not loaded on admin routes, and privacyBeforeSend drops /admin events |
| Events delayed | PostHog batches events, wait 1-2 minutes |
| Session recording not working | Needs Accepteren; the free tier has 5K recordings/month |
| Staging and production mixed up | Filter on the environment property |
| Admin Website tile says "Nog niet ingesteld" | Set POSTHOG_PERSONAL_API_KEY / SENTRY_API_TOKEN in the backend .env |
| User not identified | identifyUser() exists in lib/posthog.ts but is not called by the shop today (no person profiles) |
Test Event Capture¶
Then check PostHog → Activity → Live Events.
Best Practices¶
- Use semantic event names:
order_completednotclick_buy_button - Include relevant properties: Product ID, value, category
- Don't track PII: No passwords, full credit card numbers
- Use feature flags for rollouts: Gradual feature releases
- Set up alerts: For conversion rate drops
Related Documentation¶
- Monitoring Runbook - Full monitoring stack
- Configuration Guide - Environment setup
docs/PLAN-website-monitoring.md- Design of the privacy scrubbing, the Website tiles and the weekly check- PostHog Official Docs - Full API reference