Decorative background gradient
Back to Blog
PostHog Analytics NextjsWeb Analytics ReactPostHog Feature Flags Tutorial

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.

PostHog Analytics & Feature Flags in Next.js — Full Setup Guide

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

bash
tsx
tsx

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.

ts

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

tsx
tsx

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

ts
tsx

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

tsx

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.

ts
tsx

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.

tsx

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.

Frequently Asked Questions

Why do I need a reverse proxy for PostHog?

Many ad blockers and browser privacy extensions block requests to known analytics domains, including PostHog's default ingestion endpoint. Proxying requests through your own domain (e.g. /ingest/*) makes them indistinguishable from normal first-party traffic, substantially improving data completeness.

Can I check feature flags before the page renders?

Yes. Use the posthog-node SDK's getFeatureFlag on the server (in a Server Component or Route Handler) to gate content before HTML is sent to the browser, avoiding the flicker you'd get from a client-only flag check that resolves after initial render.

Is session recording safe to enable for privacy?

It can be, if configured carefully. PostHog masks password fields by default, but you should explicitly mask other sensitive inputs (payment details, personal data) using the maskAllInputs option or data-attr based exclusions, and disclose recording in your privacy policy.

How is an A/B test different from a plain feature flag?

A feature flag on its own just toggles behavior for a percentage of users. An A/B test additionally requires tracking a goal event (signup, purchase) tagged with which variant the user saw, so PostHog's experiment dashboard can calculate which variant actually performs better with statistical significance.

Working on something similar? Take a look at my services and case studies, or book a free call to talk about your idea.

Related Articles

Caching Strategies and Cache Invalidation — The Complete Guide
CachingSystem DesignPerformance

Caching Strategies and Cache Invalidation — The Complete Guide

A practical guide to caching strategies (cache-aside, write-through, write-behind) and the cache invalidation techniques that keep them from serving stale data.

September 8, 2026Read more →
Database Indexing and Read Replicas — A Practical Guide
DatabasePostgreSQLSystem Design

Database Indexing and Read Replicas — A Practical Guide

How to choose the right database indexes, avoid the ones that quietly hurt write performance, and scale reads with replicas without introducing replication lag bugs.

September 8, 2026Read more →
Load Balancing and Stateless Service Design — A Practical Guide
System DesignLoad BalancingScalability

Load Balancing and Stateless Service Design — A Practical Guide

How load balancers distribute traffic, why stateless services are what actually makes horizontal scaling work, and how to fix the sticky-session traps that quietly reintroduce state.

September 8, 2026Read more →
Session Stores and Database Connection Pooling Explained
BackendRedisDatabase

Session Stores and Database Connection Pooling Explained

Why in-memory sessions break horizontally scaled apps, how to move session state to Redis correctly, and how connection pooling keeps your database from falling over under concurrent load.

September 8, 2026Read more →
Vertical vs Horizontal Scaling: How to Choose and Implement Each
System DesignScalabilityArchitecture

Vertical vs Horizontal Scaling: How to Choose and Implement Each

A practical comparison of vertical and horizontal scaling — what each actually fixes, where each breaks down, and the architecture changes horizontal scaling requires that most guides skip.

September 8, 2026Read more →
AI Agent Guardrails and Safety — Preventing Prompt Injection and Runaway Actions
Ai Agent SafetyPrompt Injection DefenseAgent Guardrails

AI Agent Guardrails and Safety — Preventing Prompt Injection and Runaway Actions

Build practical guardrails for AI agents — prompt injection defenses, destructive-action confirmation, iteration caps, and permission scoping.

September 7, 2026Read more →

Trending Topics