Posthog Implementation

PostHog Analytics & A/B Testing Implementation Guide

Overview

This guide covers implementing PostHog for:

  • Page view tracking with CMS context (page IDs, content IDs, locale)
  • Event tracking (scroll milestones, time on page, CTA clicks)
  • A/B testing with feature flags

1. Installation & Initialization

Install PostHog

Initialize in instrumentation-client.ts

Environment Variables

2. Analytics Provider Pattern

Create a provider abstraction to decouple your app from PostHog directly:

3. Tracking CMS Content IDs

Add Data Attributes to Components

Components should include data-agility-component={contentID}:

Extract Content IDs from DOM

4. A/B Testing with Feature Flags

Client Component for A/B Testing

5. HogQL Queries for Analytics

Query Pageviews by Content ID

Query Pages Containing a Content ID

Query Scroll Depth for Content

Query Time on Page Distribution

Query CTA Clicks by Content ID

6. Key Implementation Notes

Event Queuing

PostHog may not be ready when your app starts. Queue events and flush when ready to avoid losing early pageviews.

Bot Detection

PostHog filters bots by default. Automated testing (Playwright, Puppeteer, Chrome DevTools Protocol) may trigger bot detection due to navigator.webdriver = true. Events won't be sent in these environments.

Batching

PostHog batches events and sends them periodically (~30 seconds) or on page unload. Events won't appear instantly in the network tab during development.

Content ID Tracking

Use the contentIDs array to track which CMS components appear on each page. This enables per-component analytics like:

  • Which content gets the most impressions
  • Scroll depth by content
  • Time spent viewing specific content

A/B Test Flicker Prevention

Use skeleton loaders while waiting for feature flag evaluation to prevent content flicker. The variant should only render after useFeatureFlagVariantKey returns a defined value.

Container Component Pattern

Ensure wrapper components pass through data attributes: