React product analytics installation
For Next.js, we recommend following the Next.js integration guide instead.
- Install
posthog-jsand@posthog/reactusing your package manager:
- Add your environment variables to your
.env.localfile and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project API key and host in your project settings. IncludingVITE_PUBLIC_in their names ensures they are accessible in the frontend.
.env.local
- Integrate PostHog at the root of your app (such as
main.jsxif you are using Vite).
React
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
See our Remix docs for more details.