React feature flags installation

For React-based frameworks, we recommend the Next.js integration guide and Next.js integration guide instead.

  1. Install posthog-js and @posthog/react using your package manager:

npm install --save posthog-js @posthog/react

  1. Add your environment variables to your .env.local file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project API key and host in your project settings. If you're using Vite, include VITE_PUBLIC_ in their names ensures they are accessible in the frontend.
.env.local
VITE_PUBLIC_POSTHOG_KEY=<ph_project_api_key>
VITE_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
  1. Integrate PostHog at the root of your app (such as main.jsx for Vite apps and root.tsx for React Router V7).
React
// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import posthog from 'posthog-js';
import { PostHogProvider } from '@posthog/react'
posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
defaults: '2025-11-30',
});
createRoot(document.getElementById('root')).render(
<StrictMode>
<PostHogProvider client={posthog}>
<App />
</PostHogProvider>
</StrictMode>,
)
Don't directly import PostHog

Do not directly import posthog apart from installation as shown above. This will likely cause errors as the library might not be initialized yet. Initialization is handled automatically when you use the PostHogProvider and usePostHog hook.

Next steps

ResourceDescription
Adding feature flag codeHow to check flags in your code for all platforms
Framework-specific guidesSetup guides for React Native, Next.js, Flutter, and other frameworks
How to do a phased rolloutGradually roll out features to minimize risk
More tutorialsOther real-world examples and use cases

Community questions

Was this page useful?

Questions about this page? or post a community question.