Getting Started
This is a plugin for vite that allows you to integrate with Posthog.
Install
pnpm i vite-plugin-posthog
Configure with Vite
It can be placed anywhere, but it's recommended to place higher up the component tree.
import { vitePostHog } from "vite-plugin-posthog";
// https://vitejs.dev/config/
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
// import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
return defineConfig({
plugins: [
react(),
vitePostHog({
apiKey: process.env.VITE_POSTHOG_KEY, //Required
hostUrl: process.env.VITE_POSTHOG_API_HOST, //Required
isDevModeOn: true, // optional
config: {
autocapture: false,
capture_pageview: false,
// ...other posthog config options
},
}),
],
});
};
Use in your app (React example)
import { useVitePostHog } from "vite-plugin-posthog/react"; //import react specific code from here
const App = () => {
const posthog = useVitePostHog();
return (
<div>
<button
onClick={() => {
posthog?.capture("button clicked", { buttonName: "test" });
}}
>
Click me
</button>
</div>
);
};