React web analytics installation

For Next.js, we recommend following the 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. Including 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 if you are using Vite).
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.

Using React Router v7?

You need to set posthog-js and @posthog/react as external packages in your vite.config.ts file to avoid SSR errors.

vite.config.ts
// ... imports
export default defineConfig({
plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
ssr: {
noExternal: ['posthog-js', '@posthog/react']
}
});

See our Remix docs for more details.

Next steps

After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.

PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.

Community questions

Was this page useful?

Questions about this page? or post a community question.