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

Silent Tool Failures in AI Agents — Why Your Agent Lies About Success
Ai Agent ReliabilityTool Call FailuresLlm Error Handling+1 more

Silent Tool Failures in AI Agents — Why Your Agent Lies About Success

Most AI agent bugs never throw an error — the tool call "succeeds" with empty, truncated, or stale data and the agent confidently reports the task as done. Here's how to catch failures that don't look like failures.

September 22, 2026Read more →
AI Coding Agents Compared in 2026 — Claude Code vs Cursor vs GitHub Copilot
Claude Code Vs CursorAI Coding AgentsGithub Copilot

AI Coding Agents Compared in 2026 — Claude Code vs Cursor vs GitHub Copilot

Compare Claude Code, Cursor, and GitHub Copilot for real development work — agentic workflows, codebase understanding, pricing, and which fits your team.

September 18, 2026Read more →
Best Authentication Libraries for Next.js in 2026 — Clerk vs Auth.js vs Better Auth
Nextjs AuthenticationClerk Vs NextauthBetter Auth

Best Authentication Libraries for Next.js in 2026 — Clerk vs Auth.js vs Better Auth

Compare Clerk, Auth.js (NextAuth), and Better Auth for Next.js — setup effort, hosted UI, pricing, and which fits your app.

September 18, 2026Read more →
Best Error Monitoring & Analytics Tools for Next.js in 2026 — Sentry vs PostHog vs Vercel Analytics
Nextjs Error MonitoringSentry Vs PosthogWeb Analytics

Best Error Monitoring & Analytics Tools for Next.js in 2026 — Sentry vs PostHog vs Vercel Analytics

Compare Sentry, PostHog, and Vercel Analytics for a Next.js app — error tracking, product analytics, session replay, and pricing.

September 18, 2026Read more →
How to Add AI Features to an Existing Web App (Without a Rebuild)
Add AI To Existing AppAI SaaS FeaturesOpenAI API Integration

How to Add AI Features to an Existing Web App (Without a Rebuild)

A practical guide to adding real AI features, like matching, extraction, and automation, to a web app or SaaS product you already have, without rebuilding it from scratch.

September 16, 2026Read more →
AI Agent Observability and Tracing in Production
Ai Agent ObservabilityLlm TracingAgent Monitoring+2 more

AI Agent Observability and Tracing in Production

Why logging inputs and outputs isn't enough for AI agents in production — and how trace-level observability catches failures evals and logs miss.

September 14, 2026Read more →

Trending Topics