# PostHog Analytics Setup Guide This guide will help you set up PostHog analytics for your MkSaaS application. ## Quick Setup ### 1. Get PostHog API Key 1. Go to [PostHog](https://posthog.com) and create an account 2. Create a new project (or use an existing one) 3. Go to **Project Settings** → **API Keys** 4. Copy your **Project API Key** (starts with `phc_`) ### 2. Configure Environment Variables Add the following variables to your `.env.local` file: ```bash # PostHog Analytics NEXT_PUBLIC_POSTHOG_KEY=your_posthog_project_key_here NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com ``` **Note:** The default host `https://us.i.posthog.com` works for most users. If you're using PostHog Cloud EU, use `https://eu.i.posthog.com` instead. ### 3. Install Dependencies If PostHog isn't already installed, run: ```bash pnpm add posthog-js ``` ### 4. Verify Setup 1. Start your development server: `pnpm dev` 2. Open your browser and visit `http://localhost:3000` 3. Check the browser's developer console for any errors 4. In PostHog dashboard, go to **Live Events** to see real-time tracking ## Available Environment Variables | Variable | Description | Example | |----------|-------------|---------| | `NEXT_PUBLIC_POSTHOG_KEY` | Your PostHog project API key | `phc_abc123...` | | `NEXT_PUBLIC_POSTHOG_HOST` | PostHog instance URL | `https://us.i.posthog.com` | ## Features Included The integration includes: - **Page view tracking** - Automatic tracking of all page views - **Custom event capture** - Ready to use with your own events - **User identification** - Links events to logged-in users - **Cross-domain tracking** - Works with your domain setup - **Performance tracking** - Monitors page load times ## Custom Events Usage You can track custom events in your components: ```typescript import { usePostHog } from 'posthog-js/react'; function MyComponent() { const posthog = usePostHog(); const handleClick = () => { posthog.capture('button_clicked', { button_name: 'upgrade_plan', user_tier: 'free' }); }; return ; } ``` ## Troubleshooting ### Events not appearing in PostHog? 1. Check that `NEXT_PUBLIC_POSTHOG_KEY` is set correctly 2. Verify the API key starts with `phc_` 3. Ensure you're in production mode or events won't be sent in development 4. Check the browser console for any JavaScript errors ### Development vs Production - **Development**: Events are only sent if you manually enable them - **Production**: Events are automatically sent when environment variables are configured ### Next Steps - Explore [PostHog documentation](https://posthog.com/docs) for advanced features - Set up user properties and cohorts - Create custom dashboards and insights - Consider setting up feature flags for A/B testing