or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/posthog-js@1.335.x

docs

index.md
tile.json

tessl/npm-posthog-js

tessl install tessl/npm-posthog-js@1.335.0

PostHog 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.

index.mddocs/

PostHog Browser JS Library

PostHog.js is a comprehensive browser analytics and feature management SDK for web applications.

Package Information

  • Package: posthog-js
  • Type: npm
  • Language: TypeScript
  • Installation: npm install posthog-js

Core Imports

import posthog from 'posthog-js';
// Or with named imports
import { posthog, PostHog } from 'posthog-js';

CommonJS:

const posthog = require('posthog-js').default;

Quick Start

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();

Core Capabilities

Event Capture

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;

Reference: Event Capture

User Identification

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

Feature Flags

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;

Reference: Feature Flags

Session Recording

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

Error Tracking

Capture and monitor exceptions automatically or manually.

function captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined;
function startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void;
function stopExceptionAutocapture(): void;

Reference: Error Tracking

Privacy & Consent

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

Additional Features

FeatureDescriptionReference
SurveysCollect user feedback and run NPS surveysReference
Web ExperimentsA/B test with DOM transformationsReference
HeatmapsVisualize click and movement dataReference
Product ToursGuided walkthroughs for usersReference
ConversationsIn-app chat widgetReference
Early AccessManage beta feature enrollmentsReference
ToolbarDebug and test features visuallyReference
Group AnalyticsTrack organizations and teamsReference
LLM AnalyticsTrack AI/LLM interactionsReference

Instance Properties

// 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;

Configuration Quick Reference

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

Common Types

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;
}

Reference: Type Definitions

Getting Started

For New Users

  1. Quick Start Guide - Get up and running in 5 minutes
  2. Real-World Scenarios - See practical examples
  3. Best Practices - Production deployment guide

For Specific Use Cases

For Advanced Features

Instance Management

// Primary instance
posthog.init('token1');

// Named instance
posthog.init('token2', {}, 'secondary');

// Access named instance
posthog.secondary.capture('event');

Reserved Event Names

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

Reference: Reserved Events

Configuration Defaults

{
    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'
}

Browser Compatibility

  • Chrome/Edge 60+, Firefox 55+, Safari 11+
  • Not supported: Internet Explorer

Reference: Compatibility Details

Documentation Structure

Guides

Examples

Reference

Quick Reference

Essential Methods

MethodPurposeExample
init(token, config?)Initialize SDKposthog.init('key')
capture(event, props?)Track eventposthog.capture('clicked')
identify(id, props?)Identify userposthog.identify('user-123')
isFeatureEnabled(key)Check flagposthog.isFeatureEnabled('new-ui')
startSessionRecording()Start recordingposthog.startSessionRecording()
captureException(error)Track errorposthog.captureException(err)
opt_in_capturing()Enable trackingposthog.opt_in_capturing()
reset()Clear user stateposthog.reset()

Common Patterns

// 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

Troubleshooting

IssueSolution
Events not appearingEnable debug: posthog.debug(true)
Flags not workingCheck: posthog.featureFlags.hasLoadedFlags
Recording not startingForce start: posthog.startSessionRecording(true)
Performance issuesReduce batch size, disable unused features

Detailed Troubleshooting

Migration Guides

Migrating from another platform?

Resources

Documentation

External Links

  • PostHog Docs: https://posthog.com/docs
  • GitHub: https://github.com/PostHog/posthog-js
  • NPM: https://www.npmjs.com/package/posthog-js
  • Community: https://posthog.com/questions