tessl install tessl/npm-posthog-js@1.335.0PostHog Browser JS Library is a comprehensive browser analytics and feature management SDK that enables developers to capture user events, track product analytics, manage feature flags, record session replays, and implement feedback mechanisms like surveys and conversations in web applications.
PostHog.js is a comprehensive browser analytics and feature management SDK for web applications.
npm install posthog-jsimport posthog from 'posthog-js';
// Or with named imports
import { posthog, PostHog } from 'posthog-js';CommonJS:
const posthog = require('posthog-js').default;import posthog from 'posthog-js';
// Initialize
posthog.init('<your-project-api-key>', {
api_host: 'https://us.i.posthog.com'
});
// Track events
posthog.capture('button_clicked', { button_id: 'signup' });
// Identify users
posthog.identify('user-123', { email: 'user@example.com' });
// Check feature flags
if (posthog.isFeatureEnabled('new-dashboard')) {
// Show new dashboard
}
// Start session recording
posthog.startSessionRecording();Track user actions and behaviors with custom events and properties.
function capture(event: EventName, properties?: Properties, options?: CaptureOptions): CaptureResult | void;
function register(properties: Properties, days?: number): void;
function register_once(properties: Properties, default_value?: Property, days?: number): void;Identify users, set person properties, and manage user state.
function identify(new_distinct_id?: string, userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void;
function setPersonProperties(userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void;
function alias(alias: string, original?: string): CaptureResult | void | number;
function reset(reset_device_id?: boolean): void;→ Reference: User Identification
Control features, run experiments, and manage feature access dynamically.
function getFeatureFlag(key: string, options?: { send_event?: boolean }): boolean | string | undefined;
function isFeatureEnabled(key: string, options?: { send_event: boolean }): boolean | undefined;
function getFeatureFlagPayload(key: string): JsonType;
function reloadFeatureFlags(): void;
function onFeatureFlags(callback: FeatureFlagsCallback): () => void;Record user sessions for replay and analysis.
function startSessionRecording(override?: { sampling?: boolean; linked_flag?: boolean; url_trigger?: boolean; event_trigger?: boolean; } | true): void;
function stopSessionRecording(): void;
function sessionRecordingStarted(): boolean;
function get_session_id(): string;
function get_session_replay_url(options?: { withTimestamp?: boolean; timestampLookBack?: number; }): string;→ Reference: Session Recording
Capture and monitor exceptions automatically or manually.
function captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined;
function startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void;
function stopExceptionAutocapture(): void;Manage user opt-in/opt-out and comply with privacy regulations.
function opt_in_capturing(options?: { captureEventName?: EventName | null | false; captureProperties?: Properties; }): void;
function opt_out_capturing(): void;
function has_opted_in_capturing(): boolean;
function has_opted_out_capturing(): boolean;
function get_explicit_consent_status(): 'granted' | 'denied' | 'pending';→ Reference: Privacy & Consent
| Feature | Description | Reference |
|---|---|---|
| Surveys | Collect user feedback and run NPS surveys | Reference |
| Web Experiments | A/B test with DOM transformations | Reference |
| Heatmaps | Visualize click and movement data | Reference |
| Product Tours | Guided walkthroughs for users | Reference |
| Conversations | In-app chat widget | Reference |
| Early Access | Manage beta feature enrollments | Reference |
| Toolbar | Debug and test features visually | Reference |
| Group Analytics | Track organizations and teams | Reference |
| LLM Analytics | Track AI/LLM interactions | Reference |
// Version and configuration
readonly version: string;
readonly config: PostHogConfig;
// Sub-API instances
readonly featureFlags: PostHogFeatureFlags;
readonly surveys: PostHogSurveys;
readonly conversations: PostHogConversations;
readonly experiments: WebExperiments;
readonly heatmaps: Heatmaps;
readonly productTours: PostHogProductTours;
readonly sessionRecording?: SessionRecording;
readonly toolbar: Toolbar;
readonly exceptions: PostHogExceptions;
readonly consent: ConsentManager;interface PostHogConfig {
// Core
api_host?: string; // API endpoint
token?: string; // Project API key
loaded?: (posthog: PostHog) => void; // Callback when loaded
// Event Capture
capture_pageview?: boolean | 'history_change'; // Auto page views
autocapture?: boolean | AutocaptureConfig; // Auto click tracking
capture_exceptions?: boolean | ExceptionAutoCaptureConfig; // Auto error capture
// Storage
persistence?: 'cookie' | 'localStorage' | 'sessionStorage' | 'memory' | 'localStorage+cookie';
disable_persistence?: boolean;
// Privacy
opt_out_capturing_by_default?: boolean;
respect_dnt?: boolean;
cookieless_mode?: 'never' | 'always' | 'on_reject';
// Feature Flags
advanced_disable_feature_flags?: boolean;
feature_flag_request_timeout_ms?: number;
// Session Recording
disable_session_recording?: boolean;
session_recording?: SessionRecordingOptions;
// Performance
request_batching?: boolean;
batch_size?: number;
batch_max_wait_ms?: number;
// Person Profiles
person_profiles?: 'always' | 'identified_only' | 'never';
}→ Reference: Complete Configuration
type Property = string | number | boolean | null | undefined;
type Properties = Record<string, Property | Property[]>;
type EventName = string;
type JsonType = any;
interface CaptureResult {
event: string;
properties: Record<string, any>;
}
interface CaptureOptions {
send_instantly?: boolean;
timestamp?: Date;
$set?: Properties;
$set_once?: Properties;
}// Primary instance
posthog.init('token1');
// Named instance
posthog.init('token2', {}, 'secondary');
// Access named instance
posthog.secondary.capture('event');Events starting with $ are reserved by PostHog:
$pageview, $pageleave, $autocapture, $identify, $create_alias, $set, $groupidentify, $feature_flag_called, $survey_shown, $survey_sent, $exception, $web_vitals, $ai_feedback, $ai_metric
{
api_host: 'https://us.i.posthog.com',
autocapture: true,
capture_pageview: true,
persistence: 'localStorage+cookie',
request_batching: true,
batch_size: 50,
session_idle_timeout_seconds: 1800,
person_profiles: 'identified_only'
}→ Reference: Compatibility Details
| Method | Purpose | Example |
|---|---|---|
init(token, config?) | Initialize SDK | posthog.init('key') |
capture(event, props?) | Track event | posthog.capture('clicked') |
identify(id, props?) | Identify user | posthog.identify('user-123') |
isFeatureEnabled(key) | Check flag | posthog.isFeatureEnabled('new-ui') |
startSessionRecording() | Start recording | posthog.startSessionRecording() |
captureException(error) | Track error | posthog.captureException(err) |
opt_in_capturing() | Enable tracking | posthog.opt_in_capturing() |
reset() | Clear user state | posthog.reset() |
// User lifecycle
posthog.alias(userId); // On signup
posthog.identify(userId, props); // Set properties
posthog.reset(); // On logout
// Feature flags
posthog.onFeatureFlags(callback); // Wait for flags
posthog.reloadFeatureFlags(); // Refresh flags
// Groups
posthog.group(type, key, props); // Associate with group
posthog.getGroups(); // Get current groups| Issue | Solution |
|---|---|
| Events not appearing | Enable debug: posthog.debug(true) |
| Flags not working | Check: posthog.featureFlags.hasLoadedFlags |
| Recording not starting | Force start: posthog.startSessionRecording(true) |
| Performance issues | Reduce batch size, disable unused features |
Migrating from another platform?