PostHog Analytics & Feature Flags in Next.js — Full Setup Guide
Add PostHog to Next.js for custom event tracking, privacy-safe session recording, and feature flags/A-B testing — client and server setup covered.

Page view counts tell you almost nothing about whether a product is working. PostHog gives you custom event tracking, session recordings, and feature flags in one SDK — enough to actually answer "did this change help" instead of just "did people visit this page." This guide covers a production Next.js setup: provider config, event tracking, privacy-safe recording, and feature-flag-driven A/B tests.
Step 1: Install and Initialize PostHog
Step 2: Proxy Requests to Avoid Ad Blockers
Analytics requests sent directly to PostHog's domain are frequently blocked by ad blockers and privacy extensions. Proxying through your own domain avoids this.
With api_host: "/ingest" set in the provider config, every analytics request now looks like a normal first-party request to your own domain, meaningfully improving data completeness versus hitting PostHog's domain directly.
Step 3: Track Page Views and Custom Events
Page views alone tell you traffic; events like upgrade_button_clicked tell you intent. Instrument the moments that actually matter to your product's funnel, not just navigation.
Step 4: Configure Privacy-Safe Session Recording
maskAllInputs masks form field values by default (passwords are always masked regardless), and maskTextSelector lets you mark specific non-input elements — like a displayed SSN or account number — as sensitive so they never appear in recorded sessions.
Step 5: Check Feature Flags Client-Side
Step 6: Check Feature Flags Server-Side to Avoid Flicker
Client-only flag checks resolve after the initial render, causing a flash of the wrong variant. Check flags on the server for anything above the fold.
Step 7: Run an A/B Test on Top of a Feature Flag
A feature flag alone just toggles behavior — an experiment requires tracking which variant led to your goal event.
Set up the corresponding experiment in the PostHog dashboard with purchase_completed as the goal metric, and it will calculate statistical significance between variants automatically as data comes in.
Key Takeaways
Proxy PostHog requests through your own domain to avoid ad-blocker data loss, instrument real product events rather than relying on page views alone, mask sensitive fields explicitly in session recording rather than trusting defaults, and check feature flags server-side wherever a client-only check would cause a visible flicker.






