vite-plugin-posthog

raw JSON →
2.1.0 verified Mon Apr 27 auth: no javascript

A Vite plugin that simplifies integrating PostHog analytics into Vite-based applications. Current stable version is 2.1.0 (July 2024). Provides automatic injection of the PostHog snippet, environment-aware configuration, and optional React hooks/components. Released under MIT license with active maintenance (several releases in 2024). Differentiates from direct PostHog usage by handling Vite-specific optimizations (e.g., tree-shaking, environment variables). Peer dependencies include React (>=16.8) for optional React support.

error TypeError: Cannot read properties of undefined (reading 'capture')
cause usePostHog() returns undefined when PostHogProvider is missing or plugin not configured.
fix
Ensure <PostHogProvider> wraps the component tree and vite-plugin-posthog is configured in vite.config.ts.
error Module not found: Can't resolve 'vite-plugin-posthog'
cause Package not installed or import path is wrong.
fix
Run 'npm install vite-plugin-posthog' and verify import statement: import VitePluginPosthog from 'vite-plugin-posthog'.
error PostHog is already initialized. Overwriting.
cause Manual posthog.init() called in app code in addition to plugin initialization.
fix
Remove any manual posthog.init() calls; the plugin handles initialization.
breaking Version 2.0.0 changed import path for React types; require('vite-plugin-posthog/react') no longer valid.
fix Use default import VitePluginPosthog from 'vite-plugin-posthog' and named exports for hooks.
deprecated Using 'posthog-js' directly alongside this plugin may cause double initialization.
fix Rely solely on the plugin to initialize PostHog; avoid manual posthog.init() in application code.
gotcha React hooks like usePostHog require PostHogProvider to be rendered in the component tree; otherwise returns undefined.
fix Wrap your app with <PostHogProvider> imported from 'vite-plugin-posthog'.
npm install vite-plugin-posthog
yarn add vite-plugin-posthog
pnpm add vite-plugin-posthog

Shows how to configure the plugin in vite.config.ts with an API key from environment variable, and how to use the usePostHog React hook to capture events.

// vite.config.ts
import { defineConfig } from 'vite';
import VitePluginPosthog from 'vite-plugin-posthog';

export default defineConfig({
  plugins: [
    VitePluginPosthog({
      apiKey: process.env.VITE_POSTHOG_API_KEY ?? '',
      options: {
        host: 'https://app.posthog.com',
      },
    }),
  ],
});

// React component example
import { usePostHog } from 'vite-plugin-posthog';

function TrackButton() {
  const posthog = usePostHog();
  return <button onClick={() => posthog?.capture('button_clicked')}>Track</button>;
}