2.8 KiB
2.8 KiB
PostHog Analytics Setup Guide
This guide will help you set up PostHog analytics for your MkSaaS application.
Quick Setup
1. Get PostHog API Key
- Go to PostHog and create an account
- Create a new project (or use an existing one)
- Go to Project Settings → API Keys
- Copy your Project API Key (starts with
phc_
)
2. Configure Environment Variables
Add the following variables to your .env.local
file:
# 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:
pnpm add posthog-js
4. Verify Setup
- Start your development server:
pnpm dev
- Open your browser and visit
http://localhost:3000
- Check the browser's developer console for any errors
- 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:
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 <button onClick={handleClick}>Upgrade</button>;
}
Troubleshooting
Events not appearing in PostHog?
- Check that
NEXT_PUBLIC_POSTHOG_KEY
is set correctly - Verify the API key starts with
phc_
- Ensure you're in production mode or events won't be sent in development
- 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 for advanced features
- Set up user properties and cohorts
- Create custom dashboards and insights
- Consider setting up feature flags for A/B testing