# Client Configuration

Configuration options for initializing and controlling the PostHog client.

## Capabilities

### PostHog Constructor

Initialize a new PostHog client instance with API key and optional configuration.

```typescript { .api }
/**
 * Initialize a new PostHog client instance
 * @param apiKey - Your PostHog project API key
 * @param options - Configuration options for the client
 */
class PostHog {
  constructor(apiKey: string, options?: PostHogOptions);
}
```

**Usage Examples:**

```typescript
import { PostHog } from 'posthog-node';

// Basic initialization
const client = new PostHog('phc_your_api_key');

// With custom host
const client = new PostHog('phc_your_api_key', {
  host: 'https://eu.posthog.com'
});

// With personal API key for local feature flag evaluation
const client = new PostHog('phc_your_api_key', {
  host: 'https://app.posthog.com',
  personalApiKey: 'phx_your_personal_api_key'
});

// With custom configuration
const client = new PostHog('phc_your_api_key', {
  host: 'https://app.posthog.com',
  flushAt: 20,
  flushInterval: 10000,
  requestTimeout: 5000,
  enableExceptionAutocapture: true
});
```

### Debug Control

Enable or disable debug logging to troubleshoot issues.

```typescript { .api }
/**
 * Enable or disable debug logging
 * @param enabled - Whether to enable debug logging (default: true)
 */
debug(enabled?: boolean): void;
```

**Usage Examples:**

```typescript
// Enable debug logging
client.debug(true);

// Disable debug logging
client.debug(false);

// Enable with default (true)
client.debug();
```

### Privacy Controls

Opt users in or out of tracking.

```typescript { .api }
/**
 * Enable the PostHog client (opt-in)
 * @returns Promise that resolves when the client is enabled
 */
enable(): Promise<void>;

/**
 * Disable the PostHog client (opt-out)
 * @returns Promise that resolves when the client is disabled
 */
disable(): Promise<void>;
```

**Usage Examples:**

```typescript
// Enable client (opt-in)
await client.enable();

// Disable client (opt-out)
await client.disable();
```

### Persisted Properties

Get and set persisted properties in memory storage.

```typescript { .api }
/**
 * Get a persisted property value from memory storage
 * @param key - The property key to retrieve
 * @returns The stored property value or undefined if not found
 */
getPersistedProperty(key: PostHogPersistedProperty): any | undefined;

/**
 * Set a persisted property value in memory storage
 * @param key - The property key to set
 * @param value - The value to store (null to remove)
 */
setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
```

**Usage Examples:**

```typescript
// Set a persisted property
client.setPersistedProperty('userId', 'user_123');

// Get a persisted property
const userId = client.getPersistedProperty('userId');

// Remove a persisted property
client.setPersistedProperty('userId', null);
```

### Library Information

Get information about the library version and user agent.

```typescript { .api }
/**
 * Get the library version from package.json
 * @returns The current library version string
 */
getLibraryVersion(): string;

/**
 * Get the custom user agent string for this client
 * @returns The formatted user agent string (e.g., "posthog-node/5.13.2")
 */
getCustomUserAgent(): string;
```

**Usage Examples:**

```typescript
// Get version
const version = client.getLibraryVersion();
console.log(`Using PostHog SDK version: ${version}`);

// Get user agent
const userAgent = client.getCustomUserAgent();
console.log(`User agent: ${userAgent}`);
```

### Shutdown

Gracefully shutdown the client, flushing pending events and stopping pollers.

```typescript { .api }
/**
 * Shutdown the PostHog client gracefully
 * @param shutdownTimeoutMs - Timeout in milliseconds for shutdown (default: 30000)
 * @returns Promise that resolves when shutdown is complete
 */
shutdown(shutdownTimeoutMs?: number): Promise<void>;
```

**Usage Examples:**

```typescript
// Shutdown with default timeout (30 seconds)
await client.shutdown();

// Shutdown with custom timeout (5 seconds)
await client.shutdown(5000);

// In Express shutdown handler
process.on('SIGTERM', async () => {
  await client.shutdown(10000);
  process.exit(0);
});
```

## Types

### PostHogOptions

```typescript { .api }
type PostHogOptions = {
  // Connection settings
  /** PostHog host URL (default: 'https://us.i.posthog.com') */
  host?: string;

  /** Number of events to batch before sending (default: 20) */
  flushAt?: number;

  /** Interval in milliseconds to flush events (default: 10000) */
  flushInterval?: number;

  /** Request timeout in milliseconds (default: 10000) */
  requestTimeout?: number;

  /** Maximum queue size before dropping events (default: 1000) */
  maxQueueSize?: number;

  /** Maximum number of retries for failed requests (default: 3) */
  maxRetries?: number;

  /** Disable the client completely */
  disabled?: boolean;

  /** Capture mode: 'form' or 'json' (default: 'json') */
  captureMode?: 'form' | 'json';

  // Feature flags
  /** Personal API key for local feature flag evaluation */
  personalApiKey?: string;

  /** Polling interval for feature flags in milliseconds (default: 30000, min: 100) */
  featureFlagsPollingInterval?: number;

  /** Enable local evaluation of feature flags (default: true when personalApiKey provided) */
  enableLocalEvaluation?: boolean;

  /** Evaluation environments for feature flags (filter by tags) */
  evaluationEnvironments?: readonly string[];

  /** Custom cache provider for feature flag definitions (experimental) */
  flagDefinitionCacheProvider?: FlagDefinitionCacheProvider;

  /** Whether to send $feature_flag_called events (default: true) */
  sendFeatureFlagEvent?: boolean;

  // Privacy and filtering
  /** Privacy mode - reduces data collection */
  privacyMode?: boolean;

  /** Additional user agent strings to block from tracking */
  custom_blocked_useragents?: string[];

  // Error tracking
  /** Enable automatic exception capture (default: false) */
  enableExceptionAutocapture?: boolean;

  // Advanced
  /** Persistence mode (only 'memory' is supported) */
  persistence?: 'memory';

  /** Maximum size of cache that deduplicates $feature_flag_called events (default: 50000) */
  maxCacheSize?: number;

  /** Custom fetch implementation */
  fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;

  /** Hook(s) to modify or drop events before sending */
  before_send?: BeforeSendFn | BeforeSendFn[];

  // Preview features
  /** PREVIEW: Enable collection of bot traffic as $bot_pageview events */
  __preview_capture_bot_pageviews?: boolean;
};
```

### BeforeSendFn

```typescript { .api }
/**
 * Function to modify or drop events before sending
 * Return null to drop the event, or return modified event to send it
 */
type BeforeSendFn = (event: EventMessage | null) => EventMessage | null;
```

**Usage Example:**

```typescript
const client = new PostHog('phc_your_api_key', {
  before_send: (event) => {
    // Drop events with sensitive data
    if (event?.properties?.password) {
      delete event.properties.password;
    }

    // Drop certain events entirely
    if (event?.event === 'debug_event') {
      return null;
    }

    return event;
  }
});

// Multiple before_send hooks
const client = new PostHog('phc_your_api_key', {
  before_send: [
    (event) => {
      // First hook: sanitize data
      if (event?.properties) {
        event.properties.sanitized = true;
      }
      return event;
    },
    (event) => {
      // Second hook: filter
      if (event?.event === 'spam') {
        return null;
      }
      return event;
    }
  ]
});
```

### PostHogFetchOptions

```typescript { .api }
interface PostHogFetchOptions {
  method?: string;
  headers?: Record<string, string>;
  body?: string;
  signal?: AbortSignal;
}
```

### PostHogFetchResponse

```typescript { .api }
interface PostHogFetchResponse {
  ok: boolean;
  status: number;
  text(): Promise<string>;
  json(): Promise<any>;
}
```

### PostHogPersistedProperty

```typescript { .api }
type PostHogPersistedProperty = string;
```

## Configuration Best Practices

### Production Settings

```typescript
const client = new PostHog('phc_your_api_key', {
  host: 'https://app.posthog.com',
  personalApiKey: 'phx_your_personal_api_key',

  // Batching and performance
  flushAt: 20,
  flushInterval: 10000,
  requestTimeout: 5000,

  // Feature flags
  featureFlagsPollingInterval: 30000,
  enableLocalEvaluation: true,

  // Privacy
  privacyMode: false,

  // Error tracking
  enableExceptionAutocapture: true
});
```

### Development Settings

```typescript
const client = new PostHog('phc_your_api_key', {
  host: 'https://app.posthog.com',

  // Faster feedback in development
  flushAt: 1,
  flushInterval: 1000,

  // Debug logging
  disabled: false
});

client.debug(true);
```

### Serverless/Edge Settings

```typescript
// Use immediate methods for serverless
const client = new PostHog('phc_your_api_key', {
  host: 'https://app.posthog.com',
  personalApiKey: 'phx_your_personal_api_key',

  // Disable polling in serverless
  enableLocalEvaluation: false
});

// Use *Immediate methods
await client.captureImmediate({
  distinctId: 'user_123',
  event: 'function_invoked'
});
```
