@posthog/types
Version:
Type definitions for the PostHog JavaScript SDK
748 lines (653 loc) • 26.2 kB
text/typescript
/**
* PostHog instance interface
*
* This interface describes the public API of the PostHog class.
* It can be used to type `window.posthog` when loading PostHog via a script tag.
*/
import type { PostHogConfig, ResetOptions } from './posthog-config'
import type { Properties, JsonType } from './common'
import type { CaptureResult, CaptureOptions } from './capture'
import type { CaptureLogOptions, Logger } from './capture-log'
import type {
FeatureFlagsCallback,
EarlyAccessFeatureCallback,
EarlyAccessFeatureStage,
FeatureFlagResult,
FeatureFlagOptions,
IsFeatureEnabledOptions,
OverrideFeatureFlagsOptions,
} from './feature-flags'
import type { SessionIdChangedCallback } from './session-recording'
import type { RequestCallback } from './request'
import type { SurveyRenderReason } from './survey'
import type { ToolbarParams } from './toolbar'
import type { ExceptionAutoCaptureConfig } from './posthog-config'
import type { TreeShakeable } from './tree-shakeable'
/**
* The PostHog instance interface.
*
* This can be used to type `window.posthog` when loading PostHog via a `<script>` tag.
*
* @example
* ```typescript
* import type { PostHog } from '@posthog/types'
*
* declare global {
* interface Window {
* posthog?: PostHog
* }
* }
*
* // Now you can use window.posthog with type safety
* window.posthog?.capture('my_event', { property: 'value' })
* ```
*/
export interface PostHog {
/**
* The current configuration of the PostHog instance.
*/
config: PostHogConfig
/**
* The library version.
*/
version: string
/**
* Whether the PostHog instance has been loaded.
*/
__loaded: boolean
/**
* Whether the flags endpoint has been hit.
*/
flagsEndpointWasHit: boolean
// ============================================================================
// Initialization
// ============================================================================
/**
* Initializes a new instance of the PostHog capturing object.
*
* @param token - Your PostHog API token
* @param config - A dictionary of config options to override
* @param name - The name for the new posthog instance that you want created
* @returns The newly initialized PostHog instance
*/
init(token: string, config?: Partial<PostHogConfig>, name?: string): PostHog
// ============================================================================
// Event Capture
// ============================================================================
/**
* Capture an event.
*
* @param event_name - The name of the event
* @param properties - A set of properties to include with the event
* @param options - Additional options for the capture
* @returns The capture result
*/
capture(event_name: string, properties?: Properties | null, options?: CaptureOptions): CaptureResult | undefined
/**
* Capture an exception.
*
* @param error - The error to capture
* @param additionalProperties - Additional properties to include with the event
* @returns The capture result
*/
captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined
/**
* Adds a breadcrumb-like step that will be attached to the next captured exception as `$exception_steps`.
*
* @param message - The step message
* @param properties - Additional context for this step
*/
addExceptionStep(message: string, properties?: Properties): void
/**
* Capture a log entry and send it to the PostHog logs endpoint.
*
* @param options - The log entry options (body, level, attributes, etc.)
*/
captureLog(options: CaptureLogOptions): void
/**
* Logger with convenience methods for each severity level.
*
* @example
* ```js
* posthog.logger.info('checkout completed', { order_id: 'ord_789' })
* posthog.logger.error('payment failed', { error_code: 'E001' })
* ```
*/
logger: Logger
// ============================================================================
// User Identification
// ============================================================================
/**
* Identify a user with a distinct ID and optionally set person properties.
*
* @param new_distinct_id - The new distinct ID for the user
* @param userPropertiesToSet - Properties to set on the user (using $set)
* @param userPropertiesToSetOnce - Properties to set once on the user (using $set_once)
*/
identify(new_distinct_id?: string, userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void
/**
* Set HMAC-based identity verification.
*
* @param distinctId - The verified user distinct_id
* @param hash - HMAC-SHA256 of distinctId using the project API secret
*/
setIdentity(distinctId: string, hash: string): void
/**
* Clear HMAC-based identity verification, reverting to anonymous mode.
*/
clearIdentity(): void
/**
* Set properties on the current user.
*
* @param userPropertiesToSet - Properties to set on the user (using $set)
* @param userPropertiesToSetOnce - Properties to set once on the user (using $set_once)
*/
setPersonProperties(userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void
/**
* Remove properties from the current user.
*
* @param propertyNames - The name (or names) of the person properties to remove (using $unset)
*/
unsetPersonProperties(propertyNames: string | string[]): void
/**
* Create an alias for the current user.
*
* @param alias - The alias to create
* @param original - The original distinct ID (defaults to current distinct ID)
*/
alias(alias: string, original?: string): CaptureResult | void | number
/**
* Get the current distinct ID.
*
* @returns The current distinct ID
*/
get_distinct_id(): string
/**
* Reset the user's identity and start a new session.
*
* @remarks
* This also clears the stored consent, so with `opt_out_capturing_by_default` the instance
* is opted out again afterwards — call `reset()` before `opt_in_capturing()`, not after.
*
* @param options - Boolean to reset the device ID (legacy), or reset options including bootstrap values.
*/
reset(options?: boolean | ResetOptions): void
/**
* Flush any queued events and gracefully tear down the SDK.
*
* @remarks
* Provided for parity with the server-side Node.js SDK. In the browser the SDK
* already flushes on page unload, so this best-effort flushes queued events and
* always resolves — it never throws — which makes isomorphic teardown safe.
*
* @param {number} [shutdownTimeoutMs] Accepted for parity with the Node.js SDK; unused in the browser.
* @returns {Promise<void>} Resolves once teardown is complete.
*/
shutdown(shutdownTimeoutMs?: number): Promise<void>
/**
* Create a person profile for the current user.
*/
createPersonProfile(): void
/**
* Marks the current user as a test user by setting the `$internal_or_test_user` person property to `true`.
* This also enables person processing for the current user.
*
* This is useful for using in a cohort your internal/test filters for your posthog org.
* @see https://posthog.com/tutorials/filter-internal-users
* Create a cohort with `$internal_or_test_user` IS SET, and set your internal test filters to be NOT IN that cohort.
*
* {@label Identification}
*
* @example
* ```js
* // Manually mark as test user
* posthog.setInternalOrTestUser()
*
* // Or use internal_or_test_user_hostname config for automatic detection
* posthog.init('token', { internal_or_test_user_hostname: 'localhost' })
* ```
*
* @public
*/
setInternalOrTestUser(): void
// ============================================================================
// Groups
// ============================================================================
/**
* Associate the user with a group.
*
* @param groupType - The type of group (e.g., 'company', 'project')
* @param groupKey - The unique identifier for the group
* @param groupPropertiesToSet - Properties to set on the group
*/
group(groupType: string, groupKey: string, groupPropertiesToSet?: Properties): void
/**
* Get the current groups.
*
* @returns A record of group types to group keys
*/
getGroups(): Record<string, any>
/**
* Reset all groups for the current user.
*/
resetGroups(): void
// ============================================================================
// Feature Flags
// ============================================================================
/**
* The feature flags instance. Provides access to feature flag override methods.
*/
featureFlags: TreeShakeable<{
/**
* Override feature flags on the client-side. Useful for testing/debugging.
*
* @param overrideOptions - The override options
*
* @example
* ```typescript
* posthog.featureFlags.overrideFeatureFlags(false) // clear all overrides
* posthog.featureFlags.overrideFeatureFlags(['beta-feature']) // enable flags
* posthog.featureFlags.overrideFeatureFlags({'beta-feature': 'variant'}) // set variants
* posthog.featureFlags.overrideFeatureFlags({
* flags: {'beta-feature': 'variant'},
* payloads: { 'beta-feature': { someData: true } }
* })
* posthog.featureFlags.overrideFeatureFlags({ // only override payloads
* payloads: { 'beta-feature': { someData: true } }
* })
* ```
*/
overrideFeatureFlags(overrideOptions: OverrideFeatureFlagsOptions): void
/**
* @deprecated Use `overrideFeatureFlags` instead. This will be removed in a future version.
*/
override(flags: boolean | string[] | Record<string, string | boolean>, suppressWarning?: boolean): void
}>
/**
* Get the value of a feature flag.
*
* @param key - The feature flag key
* @param options - Options for the feature flag lookup
* @param options.send_event - Whether to send a $feature_flag_called event (default: true)
* @param options.fresh - If true, only return values loaded from the server, not cached localStorage values (default: false)
* @returns The feature flag value (boolean for simple flags, string for multivariate)
*/
getFeatureFlag(key: string, options?: FeatureFlagOptions): boolean | string | undefined
/**
* Get the payload of a feature flag.
*
* @param key - The feature flag key
* @returns The feature flag payload
* @deprecated Use `getFeatureFlagResult()` instead which properly tracks the feature flag call.
*/
getFeatureFlagPayload(key: string): JsonType
/**
* Get a feature flag evaluation result including both the flag value and payload.
*
* By default, this method emits the `$feature_flag_called` event.
*
* @param key - The feature flag key
* @param options - Options for the feature flag lookup
* @param options.send_event - Whether to send a $feature_flag_called event (default: true)
* @param options.fresh - If true, only return values loaded from the server, not cached localStorage values (default: false)
* @returns The feature flag result including key, enabled, variant, and payload, or undefined if not loaded
*/
getFeatureFlagResult(key: string, options?: FeatureFlagOptions): FeatureFlagResult | undefined
/**
* Check if a feature flag is enabled.
*
* @param key - The feature flag key
* @param options - Options for the feature flag lookup
* @param options.send_event - Whether to send a $feature_flag_called event (default: true)
* @param options.fresh - If true, only return values loaded from the server, not cached localStorage values (default: false)
* @param options.defaultValue - Value to return when the flag has no value (default: undefined)
* @returns Whether the feature flag is enabled
*/
isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & { defaultValue: boolean }): boolean
isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined
/**
* Reload feature flags from the server.
*/
reloadFeatureFlags(): void
/**
* Manually update feature flag values without making a network request.
*
* @param flags - An object mapping flag keys to their values (boolean or string variant)
* @param payloads - Optional object mapping flag keys to their JSON payloads
* @param options - Optional settings. Use `{ merge: true }` to merge with existing flags instead of replacing.
*/
updateFlags(
flags: Record<string, boolean | string>,
payloads?: Record<string, JsonType>,
options?: { merge?: boolean }
): void
/**
* Register a callback to be called when feature flags are loaded.
*
* @param callback - The callback to call
* @returns A function to unsubscribe
*/
onFeatureFlags(callback: FeatureFlagsCallback): () => void
/**
* Set person properties to be used for feature flag evaluation.
*
* @param properties - The properties to set
* @param reloadFeatureFlags - Whether to reload feature flags after setting
*/
setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags?: boolean): void
/**
* Reset person properties used for feature flag evaluation.
*
* @param reloadFeatureFlags - Whether to reload feature flags after resetting
*/
resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): void
/**
* Set group properties to be used for feature flag evaluation.
*
* @param properties - The properties to set (keyed by group type)
* @param reloadFeatureFlags - Whether to reload feature flags after setting
*/
setGroupPropertiesForFlags(properties: { [type: string]: Properties }, reloadFeatureFlags?: boolean): void
/**
* Reset group properties used for feature flag evaluation.
*
* @param group_type - Optional group type to reset (resets all if not provided)
*/
resetGroupPropertiesForFlags(group_type?: string): void
// ============================================================================
// Early Access Features
// ============================================================================
/**
* Get the list of early access features.
*
* @param callback - Callback to receive the features
* @param forceReload - Whether to force a reload from the server
* @param stages - The stages of the early access features to load
*/
getEarlyAccessFeatures(
callback: EarlyAccessFeatureCallback,
forceReload?: boolean,
stages?: EarlyAccessFeatureStage[]
): void
/**
* Update enrollment in an early access feature.
*
* @param key - The feature key
* @param isEnrolled - Whether the user is enrolled
* @param stage - The stage of the feature
*/
updateEarlyAccessFeatureEnrollment(key: string, isEnrolled: boolean, stage?: EarlyAccessFeatureStage): void
// ============================================================================
// Super Properties
// ============================================================================
/**
* Register properties to be sent with every event.
*
* @param properties - The properties to register
* @param days - Number of days to persist the properties
*/
register(properties: Properties, days?: number): void
/**
* Register properties to be sent with every event, but only if they haven't been set before.
*
* @param properties - The properties to register
* @param default_value - Default value for the property
* @param days - Number of days to persist the properties
*/
register_once(properties: Properties, default_value?: any, days?: number): void
/**
* Register properties for the current session only.
*
* @param properties - The properties to register
*/
register_for_session(properties: Properties): void
/**
* Unregister a property so it is no longer sent with events.
*
* @param property - The property name to unregister
*/
unregister(property: string): void
/**
* Unregister a session property.
*
* @param property - The property name to unregister
*/
unregister_for_session(property: string): void
/**
* Get a property value from persistence.
*
* @param property_name - The property name
* @returns The property value
*/
get_property(property_name: string): any | undefined
/**
* Get a session property value.
*
* @param property_name - The property name
* @returns The property value
*/
getSessionProperty(property_name: string): any | undefined
// ============================================================================
// Session & Recording
// ============================================================================
/**
* Get the current session ID.
*
* @returns The current session ID
*/
get_session_id(): string
/**
* Register a callback to be called when the session ID changes.
*
* @param callback - The callback to call
* @returns A function to unsubscribe
*/
onSessionId(callback: SessionIdChangedCallback): () => void
/**
* Get the URL to view the current session recording.
*
* @param {Object} [options] Options for the URL
* @param {boolean} [options.withTimestamp] Whether to include the timestamp in the URL
* @param {number} [options.timestampLookBack] How many seconds to look back for the timestamp
* @returns The session replay URL
*/
get_session_replay_url(options?: { withTimestamp?: boolean; timestampLookBack?: number }): string
/**
* Start session recording (if not already started).
*
* @param override - Options to override default behavior, or `true` to override all controls
* @param override.sampling - Override the default sampling behavior
* @param override.linked_flag - Override the default linked_flag behavior
* @param override.url_trigger - Override the default url_trigger behavior (only accepts `true`)
* @param override.event_trigger - Override the default event_trigger behavior (only accepts `true`)
*/
startSessionRecording(
override?: { sampling?: boolean; linked_flag?: boolean; url_trigger?: true; event_trigger?: true } | true
): void
/**
* Stop session recording.
*/
stopSessionRecording(): void
/**
* Check if session recording has started.
*
* @returns Whether session recording has started
*/
sessionRecordingStarted(): boolean
/**
* The session recording instance. May be undefined if session recording is not initialized.
*/
sessionRecording?: {
/** Force allow network capture on localhost (for debugging) */
_forceAllowLocalhostNetworkCapture: boolean
}
/**
* The session manager instance. May be undefined in cookieless mode.
*/
sessionManager?: {
/** Reset the session ID, creating a new session */
resetSessionId: () => void
}
// ============================================================================
// Consent & Opt-in/out
// ============================================================================
/**
* Opt the user into capturing.
*/
opt_in_capturing(): void
/**
* Opt the user out of capturing.
*/
opt_out_capturing(): void
/**
* Check if the user has opted in to capturing.
*
* @returns Whether the user has opted in
*/
has_opted_in_capturing(): boolean
/**
* Check if the user has opted out of capturing.
*
* @returns Whether the user has opted out
*/
has_opted_out_capturing(): boolean
/**
* Get the explicit consent status.
*
* @returns The consent status
*/
get_explicit_consent_status(): 'granted' | 'denied' | 'pending'
/**
* Clear the opt-in/out status.
*/
clear_opt_in_out_capturing(): void
// ============================================================================
// Configuration
// ============================================================================
/**
* Update the configuration.
*
* @param config - The configuration to merge
*/
set_config(config: Partial<PostHogConfig>): void
/**
* Enable or disable debug mode.
*
* @param debug - Whether to enable debug mode (defaults to true)
*/
debug(debug?: boolean): void
// ============================================================================
// Surveys
// ============================================================================
/**
* Get the list of surveys.
*
* @param callback - Callback to receive the surveys
* @param forceReload - Whether to force a reload from the server
*/
getSurveys(callback: (surveys: any[]) => void, forceReload?: boolean): void
/**
* Get active surveys that match the current user.
*
* @param callback - Callback to receive the surveys
* @param forceReload - Whether to force a reload from the server
*/
getActiveMatchingSurveys(callback: (surveys: any[]) => void, forceReload?: boolean): void
/**
* Render a survey in a specific container.
*
* @param surveyId - The survey ID
* @param selector - CSS selector for the container
*/
renderSurvey(surveyId: string, selector: string): void
/**
* Check if a survey can be rendered.
*
* @param surveyId - The survey ID
* @returns The render reason or null if can't render
*/
canRenderSurvey(surveyId: string): SurveyRenderReason | null
/**
* Check if a survey can be rendered (async version).
*
* @param surveyId - The survey ID
* @param forceReload - Whether to force a reload from the server
* @returns A promise that resolves to the render reason
*/
canRenderSurveyAsync(surveyId: string, forceReload?: boolean): Promise<SurveyRenderReason>
// ============================================================================
// Events
// ============================================================================
/**
* Register an event listener.
*
* @param {'eventCaptured' | 'featureFlagsReloading'} event The event name to listen for
* @param {(...args: any[]) => void} cb The callback to call
* @returns A function to unsubscribe
*/
on(event: 'eventCaptured' | 'featureFlagsReloading', cb: (...args: any[]) => void): () => void
// ============================================================================
// Error Tracking
// ============================================================================
/**
* Start automatic exception capture.
*
* @param config - Optional configuration for exception autocapture
*/
startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void
/**
* Stop automatic exception capture.
*/
stopExceptionAutocapture(): void
// ============================================================================
// Toolbar
// ============================================================================
/**
* Load the PostHog toolbar.
*
* @param params - Toolbar parameters
* @returns Whether the toolbar was loaded
*/
loadToolbar(params: ToolbarParams): boolean
// ============================================================================
// Page View
// ============================================================================
/**
* Get the current page view ID.
*
* @returns The current page view ID
*/
getPageViewId(): string | undefined
// ============================================================================
// LLM Analytics
// ============================================================================
/**
* Capture written user feedback for a LLM trace.
*
* @param traceId - The trace ID to capture feedback for
* @param userFeedback - The feedback to capture
*/
captureTraceFeedback(traceId: string | number, userFeedback: string): void
/**
* Capture a metric for a LLM trace.
*
* @param traceId - The trace ID to capture the metric for
* @param metricName - The name of the metric to capture
* @param metricValue - The value of the metric to capture
*/
captureTraceMetric(traceId: string | number, metricName: string, metricValue: string | number | boolean): void
// ============================================================================
// Deprecated
// ============================================================================
/**
* @deprecated Use `setPersonProperties` instead
*/
people: {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
}
/**
* @deprecated Use `flagsEndpointWasHit` instead
*/
decideEndpointWasHit: boolean
}