Sabo includes pre-configured PostHog analytics with automatic pageview tracking, custom event support, and feature flags. PostHog is optional and only activates when environment variables are set.
Overview
PostHog is an open-source product analytics platform that helps you understand how users interact with your application. Sabo’s PostHog integration provides:- Automatic pageview tracking for all routes
- Custom event tracking via the
usePostHog()hook - Server-side analytics for API routes and server components
- Feature flags for gradual feature rollouts
- Session recording (configurable in PostHog dashboard)
- Privacy-first analytics with GDPR compliance options
PostHog is completely optional. If you don’t set the environment variables, Sabo will function normally without analytics.
Quick Setup
1
Create PostHog account
Sign up for PostHog to get your project API key.
- Visit PostHog Cloud or self-host PostHog
- Create a new project
- Copy your Project API Key from Project Settings
- Note your PostHog host URL:
- Cloud:
https://app.posthog.com(US) orhttps://eu.posthog.com(EU) - Self-hosted: Your custom domain
- Cloud:
2
Add environment variables
Add PostHog credentials to your Important: Both variables must be present for PostHog to initialize. If either is missing, PostHog will remain disabled.
.env.local file:.env.local
Restart your development server after adding environment variables.
3
Verify integration
Test that PostHog is tracking events:
- Start your dev server:
pnpm dev - Visit
http://localhost:3000 - Open browser console and look for PostHog debug messages (in development mode)
- Check PostHog dashboard → Activity to see live pageviews
In development mode, PostHog automatically enables debug logging. Check your browser console for
[PostHog] messages.How It Works
Architecture
Sabo’s PostHog integration consists of three main parts:-
Client-side provider (
src/components/posthog-provider.tsx)- Initializes PostHog in the browser
- Wraps the entire app to provide PostHog context
- Enables debug mode in development
-
Server-side client (
src/lib/posthog/server.ts)- Tracks events from API routes and server components
- Uses PostHog Node.js SDK
- Flushes events immediately for real-time tracking
-
Exports module (
src/lib/posthog/index.ts)- Centralizes imports for both client and server utilities
- Re-exports
usePostHoghook andgetPostHogClientfunction
Initialization
PostHog initializes automatically when the app loads, but only if environment variables are set.src/components/posthog-provider.tsx
PHProvider wraps your entire app in src/app/layout.tsx:
src/app/layout.tsx
PHProvider wraps ThemeProvider to ensure PostHog context is available throughout the entire application, including all client components.Tracking Events
Automatic Pageview Tracking
PostHog automatically tracks pageviews for all routes in your app. No additional code required. What’s tracked:- Route changes (including Next.js App Router navigation)
- URL parameters and query strings
- Referrer information
- Browser and device details
- Go to PostHog Dashboard → Activity
- Filter by event type:
$pageview - See real-time page visits with full URL paths
Custom Event Tracking (Client-Side)
Track user interactions, button clicks, form submissions, and other custom events using theusePostHog() hook.
1
Import the hook
2
Call the hook in your component
3
Track events
Complete Example
src/components/marketing/pricing.tsx
Common Events to Track
Here are some recommended events to track in a SaaS application:Server-Side Event Tracking
Track events from API routes, server actions, or server components using the server-side PostHog client.src/app/api/your-route/route.ts
src/lib/posthog/server.ts) is configured to flush events immediately:
src/lib/posthog/server.ts
User Identification
Identifying Users
Callposthog.identify() in whichever component completes your authentication flow (for example, the /sign-in page) so future events are tied to the logged-in user:
Setting User Properties
Update user properties as they change:Resetting User Identity
Clear user identification on logout:Feature Flags
PostHog feature flags allow you to roll out features gradually, run A/B tests, and toggle features without deploying code.Using Feature Flags (Client-Side)
Feature Flag with Variants
Creating Feature Flags
- Go to PostHog Dashboard → Feature Flags
- Click “New feature flag”
- Configure:
- Key:
new-dashboard-ui(use in code) - Rollout: Percentage (e.g., 50% of users)
- Filters: Target specific users, groups, or properties
- Key:
- Save and the flag is immediately available
Want to convert those flags into statistically sound experiments? PostHog’s A/B testing guide explains how to define variants, success metrics, and rollouts using the same flag keys shown above.
Configuration Options
PostHog Initialization Options
You can customize PostHog behavior by modifyingsrc/components/posthog-provider.tsx:
src/components/posthog-provider.tsx
Privacy Options
Configure PostHog to respect user privacy:Best Practices
1. Event Naming Conventions
1. Event Naming Conventions
Use consistent, descriptive names for events:Good:
subscription_starteduser_signed_upfile_uploaded
clickevent1test
- Use
snake_casefor event names - Use past tense verbs (
clicked, notclick) - Be specific (
checkout_completedvspurchase) - Group related events with prefixes (
subscription_*,user_*)
2. Event Properties
2. Event Properties
Include relevant context with every event:Guidelines:
- Keep property names consistent across events
- Include user properties (
plan,role, etc.) - Add context (page location, user state)
- Use appropriate data types (numbers for counts, booleans for flags)
3. Performance Optimization
3. Performance Optimization
PostHog batches events by default, but you can optimize further:Tips:
- Don’t track every keystroke or mouse movement
- Batch similar events (e.g., track scroll milestones: 25%, 50%, 75%, 100%)
- Use feature flags to disable analytics in staging environments
4. Testing Analytics
4. Testing Analytics
Verify events are tracked correctly:In Development:
- Check browser console for
[PostHog]debug messages - Visit PostHog Dashboard → Activity (live view)
- Use PostHog’s “Test mode” to see events in real-time
- Test with different user states (logged in/out, different plans)
- Verify user identification works after sign-in
- Check that properties contain expected values
- Test feature flags with different rollout percentages
Production Deployment
1
Update environment variables
Set PostHog credentials in your production environment (Vercel, Netlify, etc.):
Use separate PostHog projects for development and production to keep analytics data isolated.
2
Disable debug mode
Ensure debug mode is only enabled in development (already configured in
posthog-provider.tsx):3
Configure session recording
Decide whether to enable session recording in PostHog Dashboard:
- Go to Settings → Project Settings → Recordings
- Enable/disable session recording
- Configure privacy settings:
- Mask sensitive inputs (passwords, credit cards)
- Block specific elements by CSS selector
- Disable recording on certain pages
4
Set up alerts
Configure PostHog to notify you of important events:
- Go to Alerts → Create alert
- Choose trigger (e.g., “Subscription cancelled” event)
- Set threshold and frequency
- Connect to Slack, email, or webhooks
Test alerts in PostHog to ensure notifications are working before going live.
Troubleshooting
PostHog not initializing
PostHog not initializing
Symptoms: No events in PostHog dashboard, no debug messages in console.Causes:
- Missing environment variables
- Incorrect API key or host
- Variables not prefixed with
NEXT_PUBLIC_
- Verify both
NEXT_PUBLIC_POSTHOG_KEYandNEXT_PUBLIC_POSTHOG_HOSTare set in.env.local - Restart dev server after adding variables
- Check browser console for PostHog errors
- Confirm API key format:
phc_... - Use correct host (US:
https://app.posthog.com, EU:https://eu.posthog.com)
Events not appearing in dashboard
Events not appearing in dashboard
Symptoms: PostHog initializes but events don’t show up.Causes:
- Wrong project API key
- Ad blockers blocking PostHog
- Network issues
- PostHog ingestion delay
- Check you’re viewing the correct project in PostHog dashboard
- Disable ad blockers (uBlock, Privacy Badger often block analytics)
- Check browser network tab for failed requests to PostHog
- Wait 1-2 minutes for events to appear (PostHog has slight delay)
- Verify API key in PostHog → Project Settings → Project API Key
'usePostHog is not a function' error
'usePostHog is not a function' error
Symptoms: React error when calling
usePostHog().Causes:- Missing
"use client"directive - Component is server component
- PostHog not imported correctly
- Add
"use client"at top of file usingusePostHog() - Import from
@/lib/posthog, notposthog-jsdirectly - Ensure
PHProviderwraps your component tree in layout.tsx
Server-side tracking not working
Server-side tracking not working
Symptoms:
getPostHogClient() returns null on server.Causes:- Environment variables not set in production
- Variables missing
NEXT_PUBLIC_prefix
- Verify environment variables are set in hosting platform (Vercel, Netlify)
- Both client and server use
NEXT_PUBLIC_*variables (this is intentional for consistency) - Redeploy after adding environment variables
- Check server logs for PostHog initialization messages
Feature flags always return false
Feature flags always return false
Symptoms:
isFeatureEnabled() always returns false.Causes:- Feature flag not created in PostHog
- User not identified (
posthog.identify()not called) - Flag filters don’t match current user
- Feature flags not loaded yet
- Create feature flag in PostHog Dashboard → Feature Flags
- Call
posthog.identify(userId)after authentication - Check flag filters/rollout percentage
- Wait for flags to load or call
posthog.reloadFeatureFlags()
Privacy & GDPR Compliance
PostHog provides tools to help you comply with privacy regulations:Cookie Consent
PostHog sets cookies (ph_*) to track users. Implement cookie consent before initializing:
src/components/posthog-provider.tsx