# 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

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

CommonJS:

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

## Quick Start

```typescript
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.

```typescript { .api }
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](./reference/events.md)**

### User Identification
Identify users, set person properties, and manage user state.

```typescript { .api }
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](./reference/identification.md)**

### Feature Flags
Control features, run experiments, and manage feature access dynamically.

```typescript { .api }
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](./reference/feature-flags.md)**

### Session Recording
Record user sessions for replay and analysis.

```typescript { .api }
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](./reference/session-recording.md)**

### Error Tracking
Capture and monitor exceptions automatically or manually.

```typescript { .api }
function captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined;
function startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void;
function stopExceptionAutocapture(): void;
```

**→ [Reference: Error Tracking](./reference/error-tracking.md)**

### Privacy & Consent
Manage user opt-in/opt-out and comply with privacy regulations.

```typescript { .api }
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](./reference/privacy.md)**

## Additional Features

| Feature | Description | Reference |
|---------|-------------|-----------|
| **Surveys** | Collect user feedback and run NPS surveys | [Reference](./reference/surveys.md) |
| **Web Experiments** | A/B test with DOM transformations | [Reference](./reference/web-experiments.md) |
| **Heatmaps** | Visualize click and movement data | [Reference](./reference/heatmaps.md) |
| **Product Tours** | Guided walkthroughs for users | [Reference](./reference/product-tours.md) |
| **Conversations** | In-app chat widget | [Reference](./reference/conversations.md) |
| **Early Access** | Manage beta feature enrollments | [Reference](./reference/early-access-features.md) |
| **Toolbar** | Debug and test features visually | [Reference](./reference/toolbar.md) |
| **Group Analytics** | Track organizations and teams | [Reference](./reference/advanced.md#group-analytics) |
| **LLM Analytics** | Track AI/LLM interactions | [Reference](./reference/advanced.md#llm-analytics) |

## Instance Properties

```typescript { .api }
// 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

```typescript { .api }
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](./reference/initialization.md)**

## Common Types

```typescript { .api }
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](./reference/types.md)**

## Getting Started

### For New Users
1. **[Quick Start Guide](./guides/quick-start.md)** - Get up and running in 5 minutes
2. **[Real-World Scenarios](./examples/real-world-scenarios.md)** - See practical examples
3. **[Best Practices](./guides/best-practices.md)** - Production deployment guide

### For Specific Use Cases
- **E-Commerce** → [Examples: E-Commerce](./examples/real-world-scenarios.md#e-commerce-application)
- **SaaS Platform** → [Examples: SaaS](./examples/real-world-scenarios.md#saas-application)
- **Content Platform** → [Examples: Content](./examples/real-world-scenarios.md#content-platform)
- **AI Application** → [Examples: AI/LLM](./examples/real-world-scenarios.md#aillm-application)

### For Advanced Features
- **A/B Testing** → [Reference: Feature Flags](./reference/feature-flags.md) + [Reference: Web Experiments](./reference/web-experiments.md)
- **Privacy Compliance** → [Reference: Privacy](./reference/privacy.md) + [Guide: Best Practices](./guides/best-practices.md#privacy--compliance-best-practices)
- **Error Monitoring** → [Reference: Error Tracking](./reference/error-tracking.md) + [Reference: Sentry Integration](./reference/sentry-integration.md)
- **Multi-Tenant** → [Reference: Group Analytics](./reference/advanced.md#group-analytics)

## Instance Management

```typescript
// 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](./reference/events.md#reserved-event-names)**

## Configuration Defaults

```typescript
{
    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](./reference/initialization.md#browser-compatibility)**

## Documentation Structure

### Guides
- **[Quick Start](./guides/quick-start.md)** - Get started quickly
- **[Best Practices](./guides/best-practices.md)** - Production deployment

### Examples
- **[Real-World Scenarios](./examples/real-world-scenarios.md)** - Practical implementations
- **[Edge Cases](./examples/edge-cases.md)** - Advanced scenarios

### Reference
- **[Initialization](./reference/initialization.md)** - SDK setup and configuration
- **[Events](./reference/events.md)** - Event tracking API
- **[Identification](./reference/identification.md)** - User identification API
- **[Feature Flags](./reference/feature-flags.md)** - Feature flag API
- **[Session Recording](./reference/session-recording.md)** - Recording API
- **[Surveys](./reference/surveys.md)** - Survey API
- **[Privacy](./reference/privacy.md)** - Privacy and consent API
- **[Error Tracking](./reference/error-tracking.md)** - Exception tracking API
- **[Advanced Features](./reference/advanced.md)** - Groups, LLM, integrations
- **[Web Experiments](./reference/web-experiments.md)** - A/B testing API
- **[Heatmaps](./reference/heatmaps.md)** - Heatmap API
- **[Product Tours](./reference/product-tours.md)** - Tour API
- **[Conversations](./reference/conversations.md)** - Chat API
- **[Early Access](./reference/early-access-features.md)** - Beta features API
- **[Toolbar](./reference/toolbar.md)** - Toolbar API
- **[Sentry Integration](./reference/sentry-integration.md)** - Sentry integration
- **[Types](./reference/types.md)** - TypeScript definitions

## Quick Reference

### Essential Methods

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

### Common Patterns

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

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

**→ [Detailed Troubleshooting](./reference/initialization.md#troubleshooting-configuration-issues)**

## Migration Guides

Migrating from another platform?

- **[From Mixpanel](./reference/events.md#migration-from-mixpanel)**
- **[From Amplitude](./reference/events.md#migration-from-amplitude)**
- **[From Google Analytics](./reference/events.md#migration-from-google-analytics)**
- **[From LaunchDarkly](./reference/feature-flags.md#migration-from-launchdarkly)**
- **[From Split.io](./reference/feature-flags.md#migration-from-splitio)**

## Resources

### Documentation
- **[Quick Start Guide](./guides/quick-start.md)** - 5-minute setup
- **[Best Practices](./guides/best-practices.md)** - Production patterns
- **[Real-World Examples](./examples/real-world-scenarios.md)** - Practical use cases
- **[Edge Cases](./examples/edge-cases.md)** - Advanced scenarios
- **[Complete API Reference](./reference/initialization.md)** - Detailed specifications

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