Skip to content

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.tsx calls initPostHog() from lib/posthog.ts on mount and captures $pageview on every App Router navigation. It is mounted in app/(shop)/layout.tsx only, so admin routes never load posthog-js. instrumentation-client.ts is deliberately empty.
  • lib/posthog.ts initialises posthog-js with NEXT_PUBLIC_POSTHOG_KEY (capture_exceptions: true, before_send: [dropInternal, privacyBeforeSend, tagEnvironment], super property environment) and exposes identifyUser / resetUser, trackEvent and the ecommerceEvents helpers.

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

  1. Go to eu.posthog.com (EU instance for GDPR)
  2. Sign up with GitHub or email
  3. Create a new project (e.g., "Freeze Design Production")
  4. Copy your Project API Key from Settings → Project → Project API Key

2. Configure Environment

Add to frontend/.env.local:

NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_api_key
NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com

For production, add these as secrets in your deployment platform.

3. Verify Installation

  1. Start the frontend: npm run dev
  2. 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
  3. Open browser DevTools → Network tab
  4. Filter by "posthog"
  5. Navigate between pages (shop pages — PostHog is not loaded on admin routes)
  6. 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

  1. Go to PostHog → Feature Flags
  2. Click "New feature flag"
  3. Set the key (e.g., new-checkout-flow)
  4. Configure rollout percentage or user targeting
  5. 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

  1. Go to PostHog → Experiments
  2. Click "New experiment"
  3. Set experiment name and feature flag key
  4. Define variants (control, test)
  5. Set goal metric (e.g., order_completed)
  6. Set minimum sample size
  7. 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

  1. Go to PostHog → Recordings
  2. Filter by:
  3. Page URL
  4. User properties
  5. Events performed
  6. Watch recording to understand user behavior

Dashboard Setup

Create these dashboards in PostHog:

1. E-commerce Funnel

Product Viewed → Added to Cart → Checkout Started → Order Completed
  1. Go to Insights → New insight
  2. Select "Funnel"
  3. Add steps: product_viewed, product_added_to_cart, checkout_started, order_completed
  4. 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 yet
  • team_order_started → team_order_added_to_cart - the team flow from product page to cart; product_added_to_cart with bron = team or namen_nummers counts 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_completed per session source, $entry_utm_source or 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 using POSTHOG_PERSONAL_API_KEY (read-only, project POSTHOG_PROJECT_ID, host POSTHOG_API_HOST) and the Sentry issues API with SENTRY_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 as privacyUrl.ts.
  • Every Monday at 06:00 Amsterdam time (CELERY_TIMEZONE) the Celery task analytics.save_website_week stores the past week as a WebsiteWeekSnapshot; each tile except orders per source shows a line over the last 12 weeks. python manage.py website_weekcijfers_inlezen --weken 12 loads 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 through freeze-ro without 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.yml posts 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

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 the href of meta events.
  • Sentry: sentryPrivacyHooks in lib/sentry.ts (beforeSend, beforeSendSpan, beforeBreadcrumb) for the client, server and edge init, and scrubReplayFrame for the frames a replay adds. Since @sentry/nextjs 11 spans are streamed one by one and there are no transaction events, so beforeSendSpan scrubs the name and attributes (url.full) of every span. sentryDataCollection keeps 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.

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:

// In browser console
posthog.debug();

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

// In browser console
posthog.capture('test_event', { test: true });

Then check PostHog → Activity → Live Events.

Best Practices

  1. Use semantic event names: order_completed not click_buy_button
  2. Include relevant properties: Product ID, value, category
  3. Don't track PII: No passwords, full credit card numbers
  4. Use feature flags for rollouts: Gradual feature releases
  5. Set up alerts: For conversion rate drops