Installation
- npm
- yarn
- pnpm
- Script Tag
Initialization
1
Import PostHog
Import the PostHog library at the top of your application:
2
Initialize with your credentials
Call
posthog.init() with your project token and host. You can find these in your project settings.The
defaults option automatically configures PostHog with recommended settings. See SDK defaults for details.3
Verify installation
Open your browser’s developer console and check for PostHog logs, or visit your Activity feed to see events.
Capturing Events
Autocapture
PostHog automatically captures clicks, form submissions, and pageviews without any additional code. Enable autocapture in your project settings.Custom Events
Capture custom events with properties:Pageview Tracking
Pageviews are tracked automatically. For single-page applications, you can manually trigger pageview events:Identifying Users
Identify Known Users
When a user signs up or logs in, identify them with a unique ID:Only call
identify() when you know the user’s identity. PostHog automatically tracks anonymous users before identification.Set User Properties
Update user properties at any time:Reset on Logout
Reset the user identity when they log out:Feature Flags
Check if a Flag is Enabled
Get Flag Value
For multivariate flags:Get Flag Payload
Retrieve JSON payloads attached to flags:Wait for Flags to Load
Group Analytics
Track events for groups (companies, organizations, etc.):Session Replay
Session replay is enabled by default. Configure it during initialization:Privacy Controls
Mask sensitive data:Surveys
Display surveys to collect user feedback:Advanced Configuration
Debugging
Enable debug mode to see detailed logs:TypeScript Support
The SDK includes TypeScript definitions:Best Practices
Performance: PostHog loads asynchronously and won’t block your page. Events are queued if the SDK hasn’t loaded yet.
Privacy: Always mask sensitive data like passwords, credit card numbers, and personal information using the
ph-no-capture class.Event Naming: Use descriptive, consistent event names in snake_case like
button_clicked or checkout_completed.Next Steps
React Integration
Use PostHog with React hooks and components
Feature Flags
Learn more about feature flags
Session Replay
Configure session recording
API Reference
Full JavaScript SDK documentation