Instrument Feature Flags
PostHogOfficialCreated by PostHog
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to instrumenting PostHog feature flags within your codebase. It handles the end-to-end process, including detecting your platform, setting up the PostHog SDK if necessary, configuring environment variables, and implementing the code required to gate features. It emphasizes best practices such as using environment variables for configuration, preferring server-side evaluation to prevent UI flicker, and ensuring minimal, non-intrusive code changes.
What it does
- Detects your project's platform and language automatically.
- Initializes the PostHog SDK if it is not already present in the project.
- Configures required environment variables securely without hardcoding.
- Provides platform-specific code patterns for implementing feature flag checks.
- Guides the integration of boolean and multivariate feature flags.
- Ensures PostHog configuration does not break application boot or runtime stability.
When to use it
- When you need to gate new functionality for controlled releases.
- After implementing a new feature that requires a safe rollout strategy.
- When reviewing pull requests that introduce features needing toggle controls.
- When you need to set up PostHog instrumentation in a new or existing project.
Advantages
- Supports a wide range of languages, frameworks, and platforms.
- Promotes safe, production-ready instrumentation patterns.
- Prevents common issues like UI flicker through server-side evaluation.
- Maintains clean code by avoiding hardcoded configuration keys.
Usage examples
- “Add a PostHog feature flag to gate the new checkout button in my React app.”
- The agent will analyze your React project, verify PostHog setup, and provide the code snippet using posthog.isFeatureEnabled to conditionally render the button.
- “I need to instrument a new feature flag for my Node.js backend.”
- The agent will detect the Node.js environment, ensure the SDK is initialized, and guide you through adding the flag check logic to your server-side code.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/posthog/instrument-feature-flags/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-feature-flags.zip -d .agents/skills
Documentation by PostHog
Add PostHog feature flags
Use this skill to add PostHog feature flags that gate new or changed functionality. Use it after implementing features or reviewing PRs to ensure safe rollouts with feature flag controls. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any platform or language.
Supported platforms: React, Next.js, React Native, Web (JavaScript), Node.js, Python, PHP, Ruby, Go, Java, Rust, .NET, Elixir, Android, iOS, Flutter, and the REST API.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Look for dependency files (package.json, pubspec.yaml, Podfile, Package.swift, requirements.txt, go.mod, Gemfile, composer.json, mix.exs, etc.) to determine the language and framework.
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) to determine the package manager.
Check for existing PostHog setup (SDK initialization, env vars, etc.). If PostHog is already installed and initialized, skip to STEP 3.
STEP 2: Research instrumentation. (Skip if PostHog is already set up.) 2.1. Find the reference file below that matches the detected platform — it is the source of truth for SDK initialization, flag evaluation methods, and framework-specific patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.
STEP 3: Create or find the feature flag.
Check if a PostHog MCP server is connected. If available, use its tools to search for an existing feature flag the user wants to instrument, or create a new one.
If no MCP server is available, instruct the user to create the flag in the PostHog dashboard.
STEP 4: Plan release conditions.
Determine the rollout strategy (percentage rollout, user targeting, group targeting, etc.).
Plan how the feature flag will gate the new functionality in code.
STEP 5: Instrument the feature.
Add the feature flag code following the platform-specific reference patterns.
Use server-side evaluation when possible to avoid UI flicker.
Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.
You must read a file immediately before attempting to write it.
STEP 6: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.Write these values to the appropriate env file using the framework's naming convention.
Reference these environment variables in code instead of hardcoding them.
Reference files
references/react.md- React feature flags installationreferences/react-native.md- React native feature flags installationreferences/web.md- Web feature flags installationreferences/nodejs.md- Node.js feature flags installationreferences/python.md- Python feature flags installationreferences/django.md- Djangoreferences/flask.md- Flaskreferences/php.md- Php feature flags installationreferences/laravel.md- Laravelreferences/ruby.md- Ruby feature flags installationreferences/ruby-on-rails.md- Ruby on railsreferences/go.md- Go feature flags installationreferences/java.md- Java feature flags installationreferences/rust.md- Rust feature flags installationreferences/dotnet.md- .net feature flags installationreferences/dotnet.md- .netreferences/elixir.md- Elixir feature flags installationreferences/android.md- Android feature flags installationreferences/ios.md- Ios feature flags installationreferences/usage.md- Ios SDK usagereferences/flutter.md- Flutter feature flags installationreferences/api.md- API feature flags installationreferences/next-js.md- Next.jsreferences/adding-feature-flag-code.md- Adding feature flag codereferences/best-practices.md- Best practices for production-ready flagsreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each platform reference contains SDK-specific installation, flag evaluation, and code examples. Find the one matching the user's stack. If unlisted, use the API reference as a fallback.
Key principles
Environment variables: Always use environment variables for PostHog keys. Never hardcode them.
Minimal changes: Add feature flag code alongside existing logic. Don't replace or restructure existing code.
Boolean flags first: Default to boolean flag checks unless the user specifically asks for multivariate flags.
Server-side when possible: Prefer server-side flag evaluation to avoid UI flicker.
Files
- ATTRIBUTION.mdAdded by AutoGineer958 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md5.7 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/adding-feature-flag-code.md114.9 KiB
- references/android.md4.6 KiB
- references/api.md6.2 KiB
- references/best-practices.md21.2 KiB
- references/django.md14.9 KiB
- references/dotnet.md25.8 KiB
- references/elixir.md1.9 KiB
- references/flask.md8.1 KiB
- references/flutter.md8.2 KiB
- references/go.md6.4 KiB
- references/ios.md4.4 KiB
- references/java.md2.9 KiB
- references/laravel.md13.1 KiB
- references/next-js.md18.3 KiB
- references/nodejs.md6.6 KiB
- references/php.md5.3 KiB
- references/python.md6.2 KiB
- references/react-native.md5.2 KiB
- references/react.md9.2 KiB
- references/ruby-on-rails.md19.7 KiB
- references/ruby.md6.0 KiB
- references/rust.md7.8 KiB
- references/usage.md29.2 KiB
- references/web.md7.5 KiB
references/next-js.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Next.js
Canonical URL: https://posthog.com/docs/libraries/next-js
Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use
https://eu.i.posthog.cominstead ofhttps://us.i.posthog.com(ingestion host), and usehttps://eu.posthog.cominstead ofhttps://app.posthog.com(app host for links).
On this page
Prerequisites
Install with the wizard
Client-side setup
Integration
Identifying users
Accessing PostHog
Server-side analytics
Configuring a reverse proxy to PostHog
Further reading
PostHog makes it easy to get data about traffic and usage of your Next.js app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.
This guide walks you through integrating PostHog into your Next.js app using the React and the Node.js SDKs.
You can see a working example of this integration in our Next.js demo app.
Next.js has both client and server-side rendering, as well as pages and app routers. We'll cover all of these options in this guide.
Try
@posthog/next(pre-release): A simplified Next.js integration with synchronized client/server identity, server-side flag bootstrapping, and a built-in API proxy. Read the setup guide →
Prerequisites
To follow this guide along, you need:
A PostHog instance (either Cloud or self-hosted)
A Next.js application
Install with the wizard
Run this command in your project directory to add PostHog to your Next.js project. The wizard detects your framework, installs the SDK, and sets up your first events.
npx @posthog/wizard
Or set it up manually by following the rest of this guide.
Client-side setup
Install posthog-js using your package manager:
npm
npm install --save posthog-jsYarn
yarn add posthog-jspnpm
pnpm add posthog-jsBun
bun add posthog-jsIf your site sets a Content-Security-Policy, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of
posthog.comthat change over time, so allow the wildcard:script-src 'self' https://*.posthog.com; connect-src 'self' https://*.posthog.com; worker-src 'self' blob: data:;
script-srccovers the snippet and the lazy-loaded bundles,connect-srccovers event ingestion and feature flags, andworker-srccovers session replay. The toolbar needs a few more, or use a reverse proxy so everything is first-party. Failing to do so causes silent failures wherecaptureandidentifycalls never send, so the integration looks complete while zero events arrive. Rememberconnect-srcfalls back todefault-src, sodefault-src 'self'blocks event delivery even when the script itself is bundled.
Add your environment variables to your .env.local file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your project settings.
.env.local
NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=<ph_project_token>
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.comThese values need to start with NEXT_PUBLIC_ to be accessible on the client-side.
Integration
Next.js provides the instrumentation-client.ts|js file for client-side setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this:
instrumentation-client.js
import posthog from 'posthog-js'
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
defaults: '2026-08-30'
});instrumentation-client.ts
import posthog from 'posthog-js'
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
defaults: '2026-08-30'
});Bootstrapping with instrumentation-client
When using instrumentation-client, the values you pass to posthog.init remain fixed for the entire session. This means bootstrapping only works if you evaluate flags before your app renders (for example, on the server).
If you need flag values after the app has rendered, you’ll want to:
Evaluate the flag on the server and pass the value into your app, or
Evaluate the flag in an earlier page/state, then store and re-use it when needed.
Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same distinct_id across client and server.
See the bootstrapping guide for more information.
Identifying users
Identifying users is required. Call
posthog.identify('your-user-id')after login to link events to a known user. This is what connects frontend event captures, session replays, LLM traces, and error tracking to the same person — and lets backend events link back too.Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like
"anonymous"or"user", which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned.Call
posthog.reset()on logout, so the next person to use the browser doesn't inherit the last one's identity.See our guide on identifying users for how to set this up.
Linking client and server events
Next.js apps usually capture on both sides. To keep them on the same person, use the same distinct ID in both, and let the browser tell your server which one that is.
If your app calls your own backend, tracing_headers adds X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID to matching fetch and XMLHttpRequest requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths.
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
// Optional: send PostHog session/user context to your backend
tracing_headers: ['api.example.com'],
})This works in local development too, but match on the hostname alone: use 'localhost', not 'localhost:3000'. Ports are never part of a hostname, so a value with one in it never matches anything. localhost and 127.0.0.1 are also different hostnames — use whichever your app actually calls.
Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching distinctId, and pass it in when capturing the event.
Set up a reverse proxy (recommended)
We recommend setting up a reverse proxy, so that events are less likely to be intercepted by tracking blockers.
We have our own managed reverse proxy service, which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy.
If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare, AWS Cloudfront, and Vercel.
Grouping products in one project (recommended)
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and group them in one project.
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
Add IPs to Firewall/WAF allowlists (recommended)
For certain features like heatmaps, your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site.
EU: 3.75.65.221, 18.197.246.42, 3.120.223.253
US: 44.205.89.55, 52.4.194.122, 44.208.188.173
These are public, stable IPs used by PostHog services.
PostHog captures heatmap screenshots using Browserless, which has its own IP addresses. Browserless publishes the current list here.
An allowlist does not help when your app has a private address. For apps on an internal network, see internal and intranet applications.
Accessing PostHog
Once initialized in instrumentation-client.js|ts, import posthog from posthog-js anywhere and call the methods you need on the posthog object.
"use client";
import posthog from "posthog-js";
export default function Home() {
return (
<div>
<button onClick={() => posthog.capture("test_event")}>Click me for an event</button>
</div>
);
}Using React hooks
The React feature flag hooks work automatically when PostHog is initialized via instrumentation-client.ts. The hooks use the initialized posthog-js singleton:
"use client";
import { useFeatureFlagEnabled } from "@posthog/react";
export default function FeatureComponent() {
const showNewFeature = useFeatureFlagEnabled("new-feature");
return showNewFeature ? <NewFeature /> : <OldFeature />;
}Usage
See the React SDK docs for examples of how to use:
You can also read the full posthog-js documentation for all the usable functions.
Server-side analytics
Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the Node SDK.
First, install the posthog-node library:
npm
npm install posthog-node --saveYarn
yarn add posthog-nodepnpm
pnpm add posthog-nodeBun
bun add posthog-nodeRouter-specific instructions
App router
For the app router, we can initialize the posthog-node SDK once with a PostHogClient function, and import it into files.
This enables us to send events and fetch data from PostHog on the server – without making client-side requests.
// app/posthog.js
import { PostHog } from 'posthog-node'
export default function PostHogClient() {
const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
flushAt: 1,
flushInterval: 0
})
return posthogClient
}Note: Because server-side functions in Next.js can be short-lived, we set
flushAtto1andflushIntervalto0.
flushAtsets how many capture calls we should flush the queue (in one batch).
flushIntervalsets how many milliseconds we should wait before flushing the queue. Setting them to the lowest number ensures events are sent immediately and not batched. We also need to callawait posthog.shutdown()once done.
To use this client, we import it into our pages and call it with the PostHogClient function:
import Link from 'next/link'
import PostHogClient from '../posthog'
export default async function About() {
const posthog = PostHogClient()
const flags = await posthog.getAllFlags(
'user_distinct_id' // replace with a user's distinct ID
);
await posthog.shutdown()
return (
<main>
<h1>About</h1>
<Link href="/">Go home</Link>
{ flags['main-cta'] &&
<Link href="http://posthog.com/">Go to PostHog</Link>
}
</main>
)
}Pages router
For the pages router, we can use the getServerSideProps function to access PostHog on the server-side, send events, evaluate feature flags, and more.
This looks like this:
// pages/posts/[id].js
import { useContext, useEffect, useState } from 'react'
import { getServerSession } from "next-auth/next"
import { authOptions } from '@/lib/auth'
import { PostHog } from 'posthog-node'
export default function Post({ post, flags }) {
const [ctaState, setCtaState] = useState()
useEffect(() => {
if (flags) {
setCtaState(flags['blog-cta'])
}
})
return (
<div>
<h1>{post.title}</h1>
<p>By: {post.author}</p>
<p>{post.content}</p>
{ctaState &&
<p><a href="/">Go to PostHog</a></p>
}
<button onClick={likePost}>Like</button>
</div>
)
}
export async function getServerSideProps(ctx) {
// Pass authOptions, or your session callbacks don't run.
const session = await getServerSession(ctx.req, ctx.res, authOptions)
let flags = null
if (session) {
const client = new PostHog(
process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN,
{
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
}
)
// A stable ID from your auth system, not an email. See the note below.
const distinctId = session.user.id
flags = await client.getAllFlags(distinctId);
client.capture({
distinctId,
event: 'loaded blog article',
properties: {
$current_url: ctx.req.url,
},
});
await client.shutdown()
}
const { posts } = await import('../../blog.json')
const post = posts.find((post) => post.id.toString() === ctx.params.id)
return {
props: {
post,
flags
},
}
}Note: next-auth doesn't put a user ID on the session by default. Its session is
{ name, email, image }, sosession.user.idisundefineduntil you add it yourself with a session callback in yourauthOptions:// lib/auth.js export const authOptions = { callbacks: { session({ session, token, user }) { // JWT sessions (the default) carry the user ID in token.sub. // Database sessions get it from user.id instead. session.user.id = token?.sub ?? user.id return session }, }, }Capturing with an
undefineddistinct ID creates events that belong to nobody, so check that the ID arrives before relying on it.
Note: Make sure to always call
await client.shutdown()after sending events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately.
Server-side configuration
Next.js overrides the default fetch behavior on the server to introduce their own cache. PostHog ignores that cache by default, as this is Next.js's default behavior for any fetch call.
You can override that configuration when initializing PostHog, but make sure you understand the pros/cons of using Next.js's cache and that you might get cached results rather than the actual result our server would return. This is important for feature flags, for example.
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, {
// ... your configuration
fetch_options: {
cache: 'force-cache', // Use Next.js cache
next_options: { // Passed to the `next` option for `fetch`
revalidate: 60, // Cache for 60 seconds
tags: ['posthog'], // Can be used with Next.js `revalidateTag` function
},
}
})Configuring a reverse proxy to PostHog
To improve the reliability of client-side tracking and make requests less likely to be intercepted by tracking blockers, you can setup a reverse proxy in Next.js. Read more about deploying a reverse proxy using Next.js rewrites, the Next.js proxy file (middleware.ts on Next.js 15 and earlier), and Vercel rewrites. With the Next.js rewrites and proxy file options, also set skipTrailingSlashRedirect: true in your Next.js config. PostHog API paths end with a slash, and without this setting, Next.js redirects each request before it forwards it.
If you use @posthog/next, its proxy option includes a reverse proxy. See Add the proxy file.
Further reading
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-feature-flags · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog or PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-feature-flags.zip