Source:
ocean/docs/posthog-implementation.md| ✏️ Edit on GitHub
PostHog Analytics Implementation Guide
This document describes the comprehensive PostHog analytics implementation for the Ocean project.
Overview
PostHog is fully integrated into the Ocean application with automatic user identification, event tracking, feature flags, and organization-level analytics.
Environment Variables
The following environment variables are configured for PostHog:
# PostHog Analytics
VITE_POSTHOG_API_KEY=phc_hqVEnjLBIdcwVAmYEkTWTHxBaEQVOQ7Mmi31fiUofIp
VITE_POSTHOG_HOST=https://us.posthog.com
VITE_POSTHOG_PROJECT_ID=133001
POSTHOG_PERSONAL_API_KEY=phx_PouzmcqYyxFoAgdAtHgTQQTTWFwktPKQEhkaFLSzMmMQmUI
Project Structure
src/
├── lib/
│ ├── posthog.ts # Client-side PostHog configuration
│ └── posthog-edge.ts # Edge/Server-side PostHog configuration
├── contexts/posthog-context.tsx # React context provider
├── hooks/
│ ├── use-analytics.ts # General analytics hooks
│ └── use-posthog-features.ts # Feature flags and usage tracking
└── components/posthog-auth-tracker.tsx # Auto user identification
api/ # Vercel Edge Functions
└── example-edge.ts # Example Edge Function with tracking
middleware.ts # Edge Middleware for API tracking
Core Components
1. PostHog Service (/src/lib/posthog.ts)
A singleton service that wraps the PostHog JavaScript SDK with:
- Initialization with environment-based configuration
- User identification and properties management
- Event tracking with safeguards
- Feature flags integration
- Session recording controls
- Group analytics for organizations
2. PostHog Provider (/src/contexts/posthog-context.tsx)
React context that:
- Initializes PostHog on app startup
- Provides hooks for analytics functions
- Handles environment configuration
- Ensures PostHog is available throughout the app
3. Auth Tracker (/src/components/posthog-auth-tracker.tsx)
Automatically handles:
- User identification when users log in
- Organization context setting
- User property updates
- PostHog reset on logout
Available Hooks
useAnalytics()
General-purpose analytics hook for common tracking scenarios:
import { useAnalytics } from '@/hooks/use-analytics'
function MyComponent() {
const {
trackPageView,
trackButtonClick,
trackFormStart,
trackFormSubmit,
trackFormError,
trackUserAction,
trackError,
} = useAnalytics()
// Track page views
useEffect(() => {
trackPageView({ page: 'dashboard' })
}, [])
// Track button clicks
const handleClick = () => {
trackButtonClick('create_database', { location: 'header' })
}
// Track form interactions
const handleFormSubmit = async (data) => {
trackFormStart('create_organization', { industry: data.industry })
try {
await submitForm(data)
trackFormSubmit('create_organization', true, { industry: data.industry })
} catch (error) {
trackFormError('create_organization', error.message, { industry: data.industry })
}
}
}
useFeatureFlag()
Feature flag integration:
import { useFeatureFlag, FEATURE_FLAGS } from '@/hooks/use-posthog-features'
function MyComponent() {
const isNewDashboardEnabled = useFeatureFlag(FEATURE_FLAGS.NEW_DASHBOARD)
const isBetaFeaturesEnabled = useFeatureFlag(FEATURE_FLAGS.BETA_FEATURES)
return (
<div>
{isNewDashboardEnabled && <NewDashboard />}
{isBetaFeaturesEnabled && <BetaFeatures />}
<StandardDashboard />
</div>
)
}
trackUsageEvent()
Predefined usage tracking for business events:
import { trackUsageEvent, USAGE_EVENTS } from '@/hooks/use-posthog-features'
function handleCreateDatabase() {
trackUsageEvent(USAGE_EVENTS.DATABASE_CREATED, {
database_type: 'postgresql',
region: 'us-east-1',
})
}
Feature Flags
Centralized feature flag constants in FEATURE_FLAGS:
export const FEATURE_FLAGS = {
// Database features
DATABASE_CREATION: 'database-creation',
DATABASE_DELETION: 'database-deletion',
DATABASE_BACKUP: 'database-backup',
// Member features
MEMBER_INVITES: 'member-invites',
MEMBER_ROLES: 'member-roles',
// Plan features
ADVANCED_ANALYTICS: 'advanced-analytics',
CUSTOM_DOMAINS: 'custom-domains',
SSO: 'single-sign-on',
// Limits
AT_MEMBER_LIMIT: 'at-member-limit',
AT_DATABASE_LIMIT: 'at-database-limit',
AT_STORAGE_LIMIT: 'at-storage-limit',
// UI features
BETA_FEATURES: 'beta-features',
NEW_DASHBOARD: 'new-dashboard',
}
Usage Events
Predefined business event constants in USAGE_EVENTS:
export const USAGE_EVENTS = {
// Organization events
ORGANIZATION_CREATED: 'organization_created',
ORGANIZATION_UPDATED: 'organization_updated',
// Member events
MEMBER_INVITED: 'member_invited',
MEMBER_JOINED: 'member_joined',
MEMBER_REMOVED: 'member_removed',
// Database events
DATABASE_CREATED: 'database_created',
DATABASE_DELETED: 'database_deleted',
DATABASE_BACKUP_CREATED: 'database_backup_created',
// Usage tracking
PLAN_LIMIT_REACHED: 'plan_limit_reached',
PLAN_UPGRADED: 'plan_upgraded',
PLAN_DOWNGRADED: 'plan_downgraded',
}
Automatic Tracking
The implementation includes automatic tracking for:
Authentication Events
- Login attempts and successes
- Signup form submissions
- Email verification flows
- User identification with Supabase user data
Form Interactions
- Form start events
- Form submission success/failure
- Form validation errors
- Field-level interaction data
Navigation
- Page views with route information
- Navigation between sections
- Search queries and results
Errors
- JavaScript errors with stack traces
- API errors with context
- Form validation errors
Organization-Level Analytics
PostHog groups are used for organization-level analytics:
// Automatically set when user switches organizations
group('organization', organizationId, {
name: organizationName,
plan: 'pro',
subscription_status: 'active',
created_at: '2024-01-01',
})
This enables:
- Organization-wide feature flag rollouts
- Plan-based feature access
- Usage analytics by organization
- Cohort analysis by organization type
User Properties
Automatically tracked user properties:
email: User email addressuser_id: Supabase user IDorganization_id: Current organization IDorganization_name: Current organization nameuser_role: Role within current organizationplan: Current subscription plansubscription_status: Billing statuscreated_at: Account creation datelast_sign_in_at: Last login timestamp
Best Practices
1. Event Naming
- Use snake_case for event names
- Use descriptive, action-oriented names
- Include context in event properties
2. Properties
- Always include relevant context properties
- Use consistent property names across events
- Avoid PII in event properties (use hashed values)
3. Feature Flags
- Use descriptive flag names
- Always provide default values
- Test flag behavior in development
4. Performance
- PostHog operations are non-blocking
- Failed tracking doesn't affect user experience
- Debug mode available in development
Development and Testing
Debug Mode
PostHog debug mode is automatically enabled in development:
// Automatically enabled when import.meta.env.DEV is true
posthog.debug()
Testing Events
View events in PostHog dashboard:
- Session: https://us.posthog.com/project/sTMFPsFhdP1Ssg/replay/01985396-8d98-7ad5-8a0a-e69053693f0a?t=132
- Admin: http://go/adminOrgUS/01954963-195f-0000-49c0-278a8f8234d3
Feature Flag Testing
Feature flags can be tested by:
- Setting flags in PostHog dashboard
- Using PostHog's local evaluation
- Testing with different user properties
Security Considerations
API Keys
VITE_POSTHOG_API_KEY: Safe for client-side use (publishable key)POSTHOG_PERSONAL_API_KEY: Server-side only (for admin operations)
Data Privacy
- No PII is tracked in event properties
- User identification uses hashed/encoded user IDs
- GDPR-compliant data handling
- Opt-out functionality available
Rate Limiting
PostHog has built-in rate limiting and will queue events during high traffic.
Static IP Addresses
For allowlisting PostHog's webhook/integration calls:
- 44.205.89.55
- 44.208.188.173
- 52.4.194.122
Monitoring and Alerts
Consider setting up alerts in PostHog for:
- Sudden drops in user activity
- Error rate increases
- Feature flag adoption rates
- Conversion funnel drop-offs
Edge Functions & Server-Side Tracking
PostHog Edge Configuration (/src/lib/posthog-edge.ts)
Server-side tracking for Vercel Edge Functions with:
- Immediate event flushing for serverless environments
- API usage tracking and rate limiting
- Server-side feature flag evaluation
- Error tracking for Edge runtime
Edge Function Usage
import { trackEdgeEvent, evaluateFeatureFlag, shutdownPostHog } from '@/lib/posthog-edge'
export default async function handler(req: NextRequest) {
const userId = req.headers.get('x-user-id') || 'anonymous'
// Track API usage
await trackEdgeEvent(userId, 'api_request', {
endpoint: req.url,
method: req.method,
})
// Check feature flags server-side
const hasAccess = await evaluateFeatureFlag(userId, 'api-access-enabled')
// Always shutdown before function ends
await shutdownPostHog()
}
Middleware Integration
The middleware (/middleware.ts) automatically:
- Tracks all API requests
- Enforces rate limits based on plan
- Adds rate limit headers
- Blocks API access for free plans
- Tracks usage metrics
SaaS Feature Flags
Updated feature flags for subscription business model:
FEATURE_FLAGS = {
// Storage & Limits
STORAGE_LIMIT_GB: 'storage-limit-gb',
STORAGE_LIMIT_WARNING: 'storage-limit-warning',
// Team & Members
MAX_TEAM_MEMBERS: 'max-team-members',
TEAM_INVITES_ENABLED: 'team-invites-enabled',
UNLIMITED_TEAM_MEMBERS: 'unlimited-team-members',
// API & Integration
API_ACCESS_ENABLED: 'api-access-enabled',
API_RATE_LIMIT_PER_HOUR: 'api-rate-limit-per-hour',
// Export & Analytics
DATA_EXPORT_ENABLED: 'data-export-enabled',
ADVANCED_ANALYTICS: 'advanced-analytics',
AUDIT_LOGS_ENABLED: 'audit-logs-enabled',
// Support & Trial
PRIORITY_SUPPORT: 'priority-support',
SHOW_UPGRADE_PROMPTS: 'show-upgrade-prompts',
TRIAL_FEATURES_ENABLED: 'trial-features-enabled',
// Enterprise Features
SSO_ENABLED: 'sso-enabled',
CUSTOM_DATA_RETENTION: 'custom-data-retention',
// Beta & Experimental
BETA_FEATURES: 'beta-features',
}
Future Enhancements
Potential improvements to consider:
- A/B test integration
- Cohort-based feature rollouts
- Advanced funnel analysis
- Integration with customer support tools
- Revenue tracking integration
- Real-time dashboards for API usage
- Webhook tracking for async events