posthog-js
Version:
Posthog-js allows you to automatically capture usage and send events to PostHog.
2,075 lines • 77.9 kB
TypeScript
import { ConsentManager } from './consent';
import { WebMCP } from './extensions/webmcp';
import { SentryIntegration, sentryIntegration, SentryIntegrationOptions } from './extensions/sentry-integration';
import { PageViewManager } from './page-view';
import { PostHogPersistence } from './posthog-persistence';
import { type DisplaySurveyOptions, type SurveyCallback, type SurveyRenderReason } from '@posthog/browser-common';
import { RateLimiter } from './rate-limiter';
import { RemoteConfigLoader } from './remote-config';
import { RequestQueue } from './request-queue';
import { RetryQueue } from './retry-queue';
import { ScrollManager } from './scroll-manager';
import { SessionPropsManager } from './session-props';
import { SessionIdManager } from './sessionid';
import { CaptureLogOptions, CaptureOptions, CaptureResult, Compression, ConfigDefaults, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, EventName, ExceptionAutoCaptureConfig, FeatureFlagsCallback, FeatureFlagOptions, FeatureFlagResult, IsFeatureEnabledOptions, JsonType, PostHogConfig, Properties, Property, QueuedRequestWithOptions, RemoteConfigResult, RequestCallback, ResetOptions, SessionIdChangedCallback, SnippetArrayItem, ToolbarParams, PostHogInterface } from './types';
import type { TreeShakeable } from '@posthog/types';
import { RequestRouter } from './utils/request-router';
import { SimpleEventEmitter } from '@posthog/browser-common/utils/simple-event-emitter';
import { ExternalIntegrations } from './extensions/external-integration';
import { BrowserClientAdapter } from './extensions/browser-client';
import type { Extension as BrowserCommonExtension, ExtensionToken } from '@posthog/browser-common';
import type { BrowserSurveys } from './browser-surveys';
import type { BrowserAutocapture } from './browser-autocapture';
import type { DeadClicksAutocapture } from './extensions/dead-clicks-autocapture';
import type { ExceptionObserver } from './extensions/exception-autocapture';
import type { HistoryAutocapture } from './extensions/history-autocapture';
import type { TracingHeaders } from './extensions/tracing-headers';
import type { WebVitalsAutocapture } from './extensions/web-vitals';
import type { Heatmaps } from './heatmaps';
import type { PostHogConversations } from './extensions/conversations/posthog-conversations';
import type { PostHogExceptions } from './posthog-exceptions';
import type { PostHogLogs } from './posthog-logs';
import type { PostHogMetrics } from './posthog-metrics';
import type { PostHogProductTours } from './posthog-product-tours';
import type { SiteApps } from './site-apps';
import type { SessionRecording } from './extensions/replay/session-recording';
import type { Toolbar } from './extensions/toolbar';
import type { PostHogFeatureFlags } from './posthog-featureflags';
import type { WebExperiments } from './web-experiments';
type OnlyValidKeys<T, Shape> = T extends Shape ? (Exclude<keyof T, keyof Shape> extends never ? T : never) : never;
export declare const defaultConfig: (defaults?: ConfigDefaults) => PostHogConfig;
export declare const configRenames: (origConfig: Partial<PostHogConfig>) => Partial<PostHogConfig>;
declare class DeprecatedWebPerformanceObserver {
get _forceAllowLocalhost(): boolean;
set _forceAllowLocalhost(value: boolean);
private __forceAllowLocalhost;
}
/**
*
* This is the SDK reference for the PostHog JavaScript Web SDK.
* You can learn more about example usage in the
* [JavaScript Web SDK documentation](/docs/libraries/js).
* You can also follow [framework specific guides](/docs/frameworks)
* to integrate PostHog into your project.
*
* This SDK is designed for browser environments.
* Use the PostHog [Node.js SDK](/docs/libraries/node) for server-side usage.
*
* @constructor
*/
export declare class PostHog implements PostHogInterface {
static __defaultExtensionClasses: PostHogConfig['__extensionClasses'];
__loaded: boolean;
config: PostHogConfig;
_originalUserConfig?: Partial<PostHogConfig>;
rateLimiter: RateLimiter;
scrollManager: ScrollManager;
pageViewManager: PageViewManager;
featureFlags: TreeShakeable<PostHogFeatureFlags>;
surveys: TreeShakeable<BrowserSurveys>;
conversations: TreeShakeable<PostHogConversations>;
logs: TreeShakeable<PostHogLogs>;
metrics: TreeShakeable<PostHogMetrics>;
experiments: TreeShakeable<WebExperiments>;
toolbar: TreeShakeable<Toolbar>;
exceptions: TreeShakeable<PostHogExceptions>;
consent: ConsentManager;
persistence?: PostHogPersistence;
sessionPersistence?: PostHogPersistence;
sessionManager?: SessionIdManager;
sessionPropsManager?: SessionPropsManager;
requestRouter: RequestRouter;
siteApps?: SiteApps;
autocapture?: BrowserAutocapture;
heatmaps?: Heatmaps;
tracingHeaders?: TracingHeaders;
webVitalsAutocapture?: WebVitalsAutocapture;
exceptionObserver?: ExceptionObserver;
deadClicksAutocapture?: DeadClicksAutocapture;
historyAutocapture?: HistoryAutocapture;
productTours?: PostHogProductTours;
webMCP?: WebMCP;
_requestQueue?: RequestQueue;
_retryQueue?: RetryQueue;
_isPageUnloading: boolean;
private _isShutdown;
sessionRecording?: SessionRecording;
externalIntegrations?: ExternalIntegrations;
webPerformance: DeprecatedWebPerformanceObserver;
_initialPageviewCaptured: boolean;
_visibilityStateListener: (() => void) | null;
_personProcessingSetOncePropertiesSent: boolean;
_triggered_notifs: any;
compression?: Compression;
__request_queue: QueuedRequestWithOptions[];
_pendingRemoteConfig?: RemoteConfigResult;
_lastRemoteConfig?: RemoteConfigResult;
_remoteConfigLoader?: RemoteConfigLoader;
analyticsDefaultEndpoint: string;
version: string;
_initialPersonProfilesConfig: 'always' | 'never' | 'identified_only' | null;
_sessionRegisteredPropKeys: Set<string>;
_sessionRegisteredPropertiesStorageKey: string;
_cachedPersonProperties: string | null;
SentryIntegration: typeof SentryIntegration;
sentryIntegration: (options?: SentryIntegrationOptions) => ReturnType<typeof sentryIntegration>;
_internalEventEmitter: SimpleEventEmitter;
private readonly _extensions;
private readonly _extensionEventPropertyProducers;
private _browserClientAdapter;
private _extensionInitTimeout;
private _featureFlagsReloadingUnsubscribe;
private _replayDebugPropertiesPaused;
private _hasStableInitialDistinctId;
private _hasWarnedAboutVolatileIdentity;
private _isConsentTransition;
private _removeExtension;
private _replaceExtension;
private _inCookielessMode;
private _warnIfVolatileIdentityWithoutStableId;
/**
* Reconcile identity when shared consent changes in another tab.
* Rejection must clear retained user state before any cookieless event is constructed.
*
* Consent lives in shared cookie/localStorage, but the in-memory distinct_id does not. A tab
* that started in cookieless mode holds the `$posthog_cookieless` sentinel as its distinct_id;
* when consent is flipped to opted-in in another tab, this tab stops being cookieless
* (`_inCookielessMode()` becomes false) while the sentinel remains in memory. If that sentinel
* then escapes into a real event — or into `identify()` as `$anon_distinct_id` — the plugin
* server never hashes it and every affected browser collapses onto a single
* `$posthog_cookieless` person.
*/
private _syncCookielessIdentity;
/** @deprecated Use `flagsEndpointWasHit` instead. We migrated to using a new feature flag endpoint and the new method is more semantically accurate */
get decideEndpointWasHit(): boolean;
/**
* Whether feature flags have been initialized for this instance.
*
* @remarks
* Despite the name, this is a proxy for processed feature flag values. It may be true for
* bootstrapped flags before a network request completes.
*
* @returns True once the SDK has processed feature flag values.
*/
get flagsEndpointWasHit(): boolean;
/** DEPRECATED: We keep this to support existing usage but now one should just call .setPersonProperties */
people: {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => void;
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => void;
};
/**
* Creates an uninitialized PostHog instance.
*
* @remarks
* Most browser applications should use the default exported singleton and call `posthog.init()`.
* Construct a new instance only when you need to manage a separate SDK instance manually.
*
* @example
* ```js
* const instance = new PostHog()
* instance.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })
* ```
*/
constructor();
/**
* Initializes a new instance of the PostHog capturing object.
*
* @remarks
* All new instances are added to the main posthog object as sub properties (such as
* `posthog.library_name`) and also returned by this function. [Learn more about configuration options](https://posthog.com/docs/libraries/js/config)
*
* @example
* ```js
* // basic initialization
* posthog.init('<ph_project_api_key>', {
* api_host: '<ph_client_api_host>'
* })
* ```
*
* @example
* ```js
* // multiple instances
* posthog.init('<ph_project_api_key>', {}, 'project1')
* posthog.init('<ph_project_api_key>', {}, 'project2')
* ```
*
* @public
*
* @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
*
* {@label Initialization}
*
* @returns The newly initialized PostHog instance
*/
init(token: string, config?: OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>>, name?: string): PostHog;
_init(token: string, config?: Partial<PostHogConfig>, name?: string): PostHog;
private _isSharedExtension;
private _enrollExtension;
private _enrollFeatureFlags;
private _initExtensions;
private _processInitTaskQueue;
_onRemoteConfig(result: RemoteConfigResult): void;
_loaded(): void;
_start_queue_if_opted_in(): void;
_dom_loaded(): void;
_handle_unload(): void;
_send_request(options: QueuedRequestWithOptions): void;
_send_retriable_request(options: QueuedRequestWithOptions, transportOverride?: QueuedRequestWithOptions['transport']): void;
/**
* _execute_array() deals with processing any posthog function
* calls that were called before the PostHog library were loaded
* (and are thus stored in an array so they can be called later)
*
* Note: we fire off all the posthog function calls && user defined
* functions BEFORE we fire off posthog capturing calls. This is so
* identify/register/set_config calls can properly modify early
* capturing calls.
*
* @param {Array} array
*/
_execute_array(array: SnippetArrayItem[]): void;
/**
* push() keeps the standard async-array-push
* behavior around after the lib is loaded.
* This is only useful for external integrations that
* do not wish to rely on our convenience methods
* (created in the snippet).
*
* @example
* ```js
* posthog.push(['register', { a: 'b' }]);
* ```
*
* @param {SnippetArrayItem} item A `[function_name, ...args]` array to be executed.
*/
push(item: SnippetArrayItem): void;
private get _facebookClickIdChannel();
private get _facebookBrowserIdChannel();
private _getPersistedMetaIdentifier;
private _storeMetaIdentifier;
private _readMetaCookie;
private _updateFacebookClickId;
private _updateFacebookBrowserId;
private _markMetaIdentifierDelivered;
/**
* Captures an event with optional properties and configuration.
*
* @remarks
* You can capture arbitrary object-like values as events. [Learn about capture best practices](/docs/product-analytics/capture-events)
*
* @example
* ```js
* // basic event capture
* posthog.capture('cta-button-clicked', {
* button_name: 'Get Started',
* page: 'homepage'
* })
* ```
*
* {@label Capture}
*
* @public
*
* @param event_name - The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase')
* @param properties - Properties to include with the event describing the user or event details
* @param options - Optional configuration for the capture request
*
* @returns The capture result containing event data, or undefined if capture failed
*/
capture(event_name: EventName, properties?: Properties | null, options?: CaptureOptions): CaptureResult | undefined;
_addCaptureHook(callback: (eventName: string, eventPayload?: CaptureResult) => void): () => void;
/**
* Returns an installed browser extension by its typed stable name.
*
* @internal
*/
getExtension<T extends BrowserCommonExtension>(token: ExtensionToken<T>): T | undefined;
/**
* Returns an installed browser extension by its stable name.
*
* @internal
*/
getExtension<T extends BrowserCommonExtension = BrowserCommonExtension>(name: string): T | undefined;
_getBrowserClientAdapter(): BrowserClientAdapter;
_registerExtensionEventProperties(producer: () => Record<string, unknown>): () => void;
private _processCookieIdentityChange;
/**
* This method is used internally to calculate the event properties before sending it to PostHog. It can also be
* used by integrations (e.g. Segment) to enrich events with PostHog properties before sending them to Segment,
* which is required for some PostHog products to work correctly. (e.g. to have a correct $session_id property).
*
* @param {String} eventName The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', '$pageview', etc.
* @param {Object} eventProperties The properties to include with the event.
* @param {Date} [timestamp] The timestamp of the event, e.g. for calculating time on page. If not set, it'll automatically be set to the current time.
* @param {String} [uuid] The uuid of the event, e.g. for storing the $pageview ID.
* @param {Boolean} [readOnly] Set this if you do not intend to actually send the event, and therefore do not want to update internal state e.g. session timeout
*
* @internal
*/
calculateEventProperties(eventName: string, eventProperties: Properties, timestamp?: Date, uuid?: string, readOnly?: boolean): Properties;
/** @deprecated - deprecated in 1.241.0, use `calculateEventProperties` instead */
_calculate_event_properties: (eventName: string, eventProperties: Properties, timestamp?: Date, uuid?: string, readOnly?: boolean) => Properties;
/**
* Add additional set_once properties to the event when creating a person profile. This allows us to create the
* profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in
* persistence.
* @param dataSetOnce
* @param markAsSent - if true, marks the properties as sent so they won't be included in future events.
* Set to false for events like $groupidentify where the server doesn't process person props.
* @param forceIncludeInitialProps - if true, include initial person props even if they've already been sent.
* Used for $identify which creates/merges persons and may be processed out of order.
*/
_calculate_set_once_properties(dataSetOnce?: Properties, markAsSent?: boolean, forceIncludeInitialProps?: boolean): Properties | undefined;
/**
* Registers super properties that are included with all events.
*
* @remarks
* Super properties are stored in persistence and automatically added to every event you capture.
* These values will overwrite any existing super properties with the same keys.
*
* @example
* ```js
* // register a single property
* posthog.register({ plan: 'premium' })
* ```
*
* {@label Capture}
*
* @example
* ```js
* // register multiple properties
* posthog.register({
* email: 'user@example.com',
* account_type: 'business',
* signup_date: '2023-01-15'
* })
* ```
*
* @example
* ```js
* // register with custom expiration
* posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 days
* ```
*
* @public
*
* @param {Object} properties properties to store about the user
* @param {Number} [days] How many days since the user's last visit to store the super properties
*/
register(properties: Properties, days?: number): void;
/**
* Registers super properties only if they haven't been set before.
*
* @remarks
* Unlike `register()`, this method will not overwrite existing super properties.
* Use this for properties that should only be set once, like signup date or initial referrer.
*
* {@label Capture}
*
* @example
* ```js
* // register once-only properties
* posthog.register_once({
* first_login_date: new Date().toISOString(),
* initial_referrer: document.referrer
* })
* ```
*
* @example
* ```js
* // override existing value if it matches default
* posthog.register_once(
* { user_type: 'premium' },
* 'unknown' // overwrite if current value is 'unknown'
* )
* ```
*
* @public
*
* @param {Object} properties An associative array of properties to store about the user
* @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
* @param {Number} [days] How many days since the users last visit to store the super properties
*/
register_once(properties: Properties, default_value?: Property, days?: number): void;
/**
* Registers super properties for the current session only.
*
* @remarks
* Session super properties are automatically added to all events during the current browser session.
* Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage.
*
* {@label Capture}
*
* @example
* ```js
* // register session-specific properties
* posthog.register_for_session({
* current_page_type: 'checkout',
* ab_test_variant: 'control'
* })
* ```
*
* @example
* ```js
* // register properties for user flow tracking
* posthog.register_for_session({
* selected_plan: 'pro',
* completed_steps: 3,
* flow_id: 'signup_flow_v2'
* })
* ```
*
* @public
*
* @param {Object} properties An associative array of properties to store about the user
*/
register_for_session(properties: Properties): void;
/**
* Removes a super property from persistent storage.
*
* @remarks
* This will stop the property from being automatically included in future events.
* The property will be permanently removed from the user's profile.
*
* {@label Capture}
*
* @example
* ```js
* // remove a super property
* posthog.unregister('plan_type')
* ```
*
* @public
*
* @param {String} property The name of the super property to remove
*/
unregister(property: string): void;
/**
* Removes a session super property from the current session.
*
* @remarks
* This will stop the property from being automatically included in future events for this session.
* The property is removed from sessionStorage.
*
* {@label Capture}
*
* @example
* ```js
* // remove a session property
* posthog.unregister_for_session('current_flow')
* ```
*
* @public
*
* @param {String} property The name of the session super property to remove
*/
unregister_for_session(property: string): void;
_register_single(prop: string, value: Property): void;
_clearSessionRegisteredProps(): void;
_persistSessionRegisteredPropKeys(): void;
/**
* Gets the value of a feature flag for the current user.
*
* @remarks
* Returns the feature flag value which can be a boolean, string, or undefined.
* Supports multivariate flags that can return custom string values. An evaluated boolean flag
* returns `true` or `false`; `undefined` means no current evaluation is available for the key.
* Globally inactive flags are omitted from the remote `/flags` response, so after that response
* loads they are unavailable rather than represented by a `false` result.
*
* {@label Feature flags}
*
* @example
* ```js
* // check boolean flag
* if (posthog.getFeatureFlag('new-feature')) {
* // show new feature
* }
* ```
*
* @example
* ```js
* // check multivariate flag
* const variant = posthog.getFeatureFlag('button-color')
* if (variant === 'red') {
* // show red button
* }
* ```
*
* @public
*
* @param {string} key Key of the feature flag.
* @param {FeatureFlagOptions} [options] Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server.
* @returns {boolean | string | undefined} The feature flag value, or undefined if the flag is unavailable.
*/
getFeatureFlag(key: string, options?: FeatureFlagOptions): boolean | string | undefined;
/**
* Get feature flag payload value matching key for user (supports multivariate flags).
*
* {@label Feature flags}
*
* @example
* ```js
* const betaFeature = posthog.getFeatureFlagResult('beta-feature')
* if (betaFeature?.variant === 'some-value') {
* const someValue = betaFeature?.payload
* // do something
* }
* ```
*
* @public
*
* @deprecated Use `getFeatureFlagResult()` instead
*
* @param {string} key Key of the feature flag.
* @returns {JsonType} The feature flag payload.
*/
getFeatureFlagPayload(key: string): JsonType;
/**
* Get a feature flag evaluation result including both the flag value and payload.
*
* A result with `enabled: false` is a conclusive off evaluation. `undefined` means no current
* evaluation is available for the key. This includes globally inactive flags, which are omitted
* from the remote `/flags` response.
*
* By default, this method emits the `$feature_flag_called` event.
*
* {@label Feature flags}
*
* @example
* ```js
* const result = posthog.getFeatureFlagResult('my-flag')
* if (result?.enabled) {
* console.log('Flag is enabled with payload:', result.payload)
* }
* ```
*
* @example
* ```js
* // multivariate flag
* const result = posthog.getFeatureFlagResult('button-color')
* if (result?.variant === 'red') {
* showRedButton(result.payload)
* }
* ```
*
* @public
*
* @param {string} key Key of the feature flag.
* @param {Object} [options] Options for the feature flag lookup.
* @param {boolean} [options.send_event=true] If false, won't send the $feature_flag_called event.
* @param {boolean} [options.fresh=false] If true, won't return cached values from localStorage - only values loaded from the server.
* @returns {FeatureFlagResult | undefined} The feature flag result including key, enabled, variant, and payload.
*/
getFeatureFlagResult(key: string, options?: FeatureFlagOptions): FeatureFlagResult | undefined;
/**
* Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of
* the flags from the last load (no network request); call `reloadFeatureFlags()` first to refresh.
* Conclusive off evaluations are included with `enabled: false`; keys omitted from the response,
* including globally inactive flags, are absent. Unlike `getFeatureFlag()`, this method does not
* send a `$feature_flag_called` event.
*
* @returns {FeatureFlagResult[]} All loaded flags, or an empty array if none are loaded.
*/
getAllFeatureFlags(): FeatureFlagResult[];
/**
* Checks if a feature flag is enabled for the current user.
*
* @remarks
* Returns `true` or `false` when the flag has an evaluation value. A `false` result means the
* value evaluated off; it does not mean the SDK observed the flag's global active setting.
* Returns `undefined` when no current evaluation is available, unless `defaultValue` is given.
* Globally inactive flags are omitted from the remote `/flags` response and therefore have no
* value. This is a convenience method that treats any truthy value as enabled.
*
* {@label Feature flags}
*
* @example
* ```js
* // simple feature flag check
* if (posthog.isFeatureEnabled('new-checkout')) {
* showNewCheckout()
* }
* ```
*
* @example
* ```js
* // disable event tracking
* if (posthog.isFeatureEnabled('feature', { send_event: false })) {
* // flag checked without sending $feature_flag_called event
* }
* ```
*
* @public
*
* @param {string} key Key of the feature flag.
* @param {IsFeatureEnabledOptions} [options] Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. If `{ defaultValue: false }`, we return that value instead of undefined when the flag has no value.
* @returns {boolean | undefined} Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
*/
isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & {
defaultValue: boolean;
}): boolean;
isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined;
/**
* Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
*
* {@label Feature flags}
*
* @example
* ```js
* posthog.reloadFeatureFlags()
* ```
*
* @public
*/
reloadFeatureFlags(): void;
/**
* Manually update feature flag values without making a network request.
*
* This is useful when you have feature flag values from an external source
* (e.g., server-side evaluation, edge middleware) and want to inject them
* into the client SDK.
*
* {@label Feature flags}
*
* @example
* ```js
* // Replace all flags with server-evaluated values
* posthog.updateFlags({
* 'my-flag': true,
* 'my-experiment': 'variant-a'
* })
*
* // Merge with existing flags (update only specified flags)
* posthog.updateFlags(
* { 'my-flag': true },
* undefined,
* { merge: true }
* )
*
* // With payloads
* posthog.updateFlags(
* { 'my-flag': true },
* { 'my-flag': { some: 'data' } }
* )
* ```
*
* @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.
* @public
*/
updateFlags(flags: Record<string, boolean | string>, payloads?: Record<string, JsonType>, options?: {
merge?: boolean;
}): void;
/**
* Opt the user in or out of an early access feature. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation)
*
* {@label Feature flags}
*
* @example
* ```js
* const toggleBeta = (betaKey) => {
* if (activeBetas.some(
* beta => beta.flagKey === betaKey
* )) {
* posthog.updateEarlyAccessFeatureEnrollment(
* betaKey,
* false
* )
* setActiveBetas(
* prevActiveBetas => prevActiveBetas.filter(
* item => item.flagKey !== betaKey
* )
* );
* return
* }
*
* posthog.updateEarlyAccessFeatureEnrollment(
* betaKey,
* true
* )
* setInactiveBetas(
* prevInactiveBetas => prevInactiveBetas.filter(
* item => item.flagKey !== betaKey
* )
* );
* }
*
* const registerInterest = (featureKey) => {
* posthog.updateEarlyAccessFeatureEnrollment(
* featureKey,
* true
* )
* // Update UI to show user has registered
* }
* ```
*
* @public
*
* @param {String} key The key of the feature flag to update.
* @param {Boolean} isEnrolled Whether the user is enrolled in the feature.
* @param {String} [stage] The stage of the feature flag to update.
*/
updateEarlyAccessFeatureEnrollment(key: string, isEnrolled: boolean, stage?: string): void;
/**
* Get the list of early access features. To check enrollment status, use `isFeatureEnabled`. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation)
*
* {@label Feature flags}
*
* @example
* ```js
* const posthog = usePostHog()
* const activeFlags = useActiveFeatureFlags()
*
* const [activeBetas, setActiveBetas] = useState([])
* const [inactiveBetas, setInactiveBetas] = useState([])
* const [comingSoonFeatures, setComingSoonFeatures] = useState([])
*
* useEffect(() => {
* posthog.getEarlyAccessFeatures((features) => {
* // Filter features by stage
* const betaFeatures = features.filter(feature => feature.stage === 'beta')
* const conceptFeatures = features.filter(feature => feature.stage === 'concept')
*
* setComingSoonFeatures(conceptFeatures)
*
* if (!activeFlags || activeFlags.length === 0) {
* setInactiveBetas(betaFeatures)
* return
* }
*
* const activeBetas = betaFeatures.filter(
* beta => activeFlags.includes(beta.flagKey)
* );
* const inactiveBetas = betaFeatures.filter(
* beta => !activeFlags.includes(beta.flagKey)
* );
* setActiveBetas(activeBetas)
* setInactiveBetas(inactiveBetas)
* }, true, ['concept', 'beta'])
* }, [activeFlags])
* ```
*
* @public
*
* @param {Function} callback The callback function will be called when the early access features are loaded.
* @param {Boolean} [force_reload] Whether to force a reload of the early access features.
* @param {String[]} [stages] The stages of the early access features to load.
*/
getEarlyAccessFeatures(callback: EarlyAccessFeatureCallback, force_reload?: boolean, stages?: EarlyAccessFeatureStage[]): void;
/**
* Exposes a set of events that PostHog will emit.
* e.g. `eventCaptured` is emitted immediately before trying to send an event
*
* Unlike `onFeatureFlags` and `onSessionId` these are not called when the
* listener is registered, the first callback will be the next event
* _after_ registering a listener
*
* Available events:
* - `eventCaptured`: Emitted immediately before trying to send an event
* - `featureFlagsReloading`: Emitted when feature flags are being reloaded (e.g. after `identify()`, `group()`, or `reloadFeatureFlags()`)
*
* {@label Capture}
*
* @example
* ```js
* posthog.on('eventCaptured', (event) => {
* console.log(event)
* })
* ```
*
* @example
* ```js
* // Track when feature flags are reloading to show a loading state
* posthog.on('featureFlagsReloading', () => {
* console.log('Feature flags are being reloaded...')
* })
* ```
*
* @public
*
* @param {String} event The event to listen for.
* @param {Function} cb The callback function to call when the event is emitted.
* @returns {Function} A function that can be called to unsubscribe the listener.
*/
on(event: 'eventCaptured' | 'featureFlagsReloading', cb: (...args: any[]) => void): () => void;
/**
* Register an event listener that runs when feature flags become available or when they change.
* If there are flags, the listener is called immediately in addition to being called on future changes.
* Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser,
* including when another open tab of your site stores new flags.
* Do not call `reloadFeatureFlags()` inside this callback: each reload in one tab triggers the callback in the other tabs,
* which can send flag requests in a loop.
*
* {@label Feature flags}
*
* @public
*
* @example
* ```js
* posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
* // do something
* })
* ```
*
* @param callback - The callback function will be called once the feature flags are ready or when they are updated.
* It'll return a list of feature flags enabled for the user, the variants,
* and also a context object indicating whether we succeeded to fetch the flags or not.
* @returns A function that can be called to unsubscribe the listener. Used by `useEffect` when the component unmounts.
*/
onFeatureFlags(callback: FeatureFlagsCallback): () => void;
/**
* Register an event listener that runs when surveys are loaded.
*
* Callback parameters:
* - surveys: Survey[]: An array containing all survey objects fetched from PostHog using the getSurveys method
* - context: { isLoaded: boolean, error?: string }: An object indicating if the surveys were loaded successfully
*
* {@label Surveys}
*
* @example
* ```js
* posthog.onSurveysLoaded((surveys, context) => { // do something })
* ```
*
* @param {SurveyCallback} callback The callback function will be called when surveys are loaded or updated.
* @returns A function that can be called to unsubscribe the listener.
*/
onSurveysLoaded(callback: SurveyCallback): () => void;
/**
* Register an event listener that runs whenever the session id or window id change.
* If there is already a session id, the listener is called immediately in addition to being called on future changes.
*
* Can be used, for example, to sync the PostHog session id with a backend session.
*
* {@label Identification}
*
* @public
*
* @example
* ```js
* posthog.onSessionId(function(sessionId, windowId) { // do something })
* ```
*
* @param {Function} [callback] The callback function will be called once a session id is present or when it or the window id are updated.
* @returns {Function} A function that can be called to unsubscribe the listener. E.g. Used by `useEffect` when the component unmounts.
*/
onSessionId(callback: SessionIdChangedCallback): () => void;
/**
* Get list of all surveys.
*
* {@label Surveys}
*
* @example
* ```js
* function callback(surveys, context) {
* // do something
* }
*
* posthog.getSurveys(callback, false)
* ```
*
* @public
*
* @param {SurveyCallback} callback Function that receives the array of surveys.
* @param {boolean} [forceReload] Optional boolean to force an API call for updated surveys.
*/
getSurveys(callback: SurveyCallback, forceReload?: boolean): void;
/**
* Get surveys that should be enabled for the current user. See [fetching surveys documentation](/docs/surveys/implementing-custom-surveys#fetching-surveys-manually) for more details.
*
* {@label Surveys}
*
* @example
* ```js
* posthog.getActiveMatchingSurveys((surveys) => {
* // do something
* })
* ```
*
* @public
*
* @param {SurveyCallback} callback The callback function will be called when the surveys are loaded or updated.
* @param {boolean} [forceReload] Whether to force a reload of the surveys.
*/
getActiveMatchingSurveys(callback: SurveyCallback, forceReload?: boolean): void;
/**
* Register an event listener that runs when the set of active matching surveys changes.
* The listener receives the initial matching set and updates after event/action triggers,
* cancellation, consumption, session expiry, definitions refresh, captured pageviews,
* feature-flag updates, marking a survey as seen, and reset. Unchanged results are suppressed.
*
* URL conditions are re-evaluated on captured `$pageview` events, including automatic SPA
* pageviews when `capture_pageview` is `'history_change'`. With automatic pageviews disabled,
* capture `$pageview` after navigation. This does not observe arbitrary DOM mutations or time
* passing; selector, device and wait-period conditions are checked on the supported updates.
*
* The optional callback context distinguishes load errors from a successfully loaded empty
* result. New subscribers receive the current snapshot without replaying earlier errors:
* a settled unavailable state is `([], { isLoaded: false })`, while usable cached definitions
* are evaluated normally. An initial load already in progress delivers when it resolves.
* Recoverable load failures keep the subscription alive. Unsubscribing prevents any
* further delivery, including callbacks from an outstanding initial request.
*
* {@label Surveys}
*
* @example
* ```js
* const unsubscribe = posthog.onActiveMatchingSurveysChanged((surveys) => {
* // respond to changes in currently matching surveys
* })
* ```
*
* @public
*
* @param {SurveyCallback} callback The callback to call with active matching surveys.
* @returns A function that can be called to unsubscribe the listener.
*/
onActiveMatchingSurveysChanged(callback: SurveyCallback): () => void;
/**
* Although we recommend using popover surveys and display conditions,
* if you want to show surveys programmatically without setting up all
* the extra logic needed for API surveys, you can render surveys
* programmatically with the renderSurvey method.
*
* This takes a survey ID and an HTML selector to render an unstyled survey.
*
* {@label Surveys}
*
* @example
* ```js
* posthog.renderSurvey(coolSurveyID, '#survey-container')
* ```
*
* @deprecated Use displaySurvey instead - it's more complete and also supports popover surveys.
*
* @public
*
* @param {String} surveyId The ID of the survey to render.
* @param {String} selector The selector of the HTML element to render the survey on.
*/
renderSurvey(surveyId: string, selector: string): void;
/**
* Display a survey programmatically as either a popover or inline element.
*
* @param {string} surveyId The survey ID to display.
* @param {DisplaySurveyOptions} [options] Display configuration. Defaults to a popover that respects dashboard conditions and delays.
*
* @example
* ```js
* // Display as popover (respects all conditions defined in the dashboard)
* posthog.displaySurvey('survey-id-123')
* ```
*
* @example
* ```js
* // Display inline in a specific element
* posthog.displaySurvey('survey-id-123', {
* displayType: DisplaySurveyType.Inline,
* ignoreConditions: false,
* ignoreDelay: false,
* selector: '#survey-container'
* })
* ```
*
* @example
* ```js
* // Force display ignoring conditions and delays
* posthog.displaySurvey('survey-id-123', {
* displayType: DisplaySurveyType.Popover,
* ignoreConditions: true,
* ignoreDelay: true
* })
* ```
*
* {@label Surveys}
*/
displaySurvey(surveyId: string, options?: DisplaySurveyOptions): void;
/**
* Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).
*
* {@label Surveys}
*
* @param {string} surveyId The survey ID whose pending display should be cancelled.
*/
cancelPendingSurvey(surveyId: string): void;
/**
* Checks the feature flags associated with this Survey to see if the survey can be rendered.
* This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded.
* Use `canRenderSurveyAsync` instead.
*
* {@label Surveys}
*
* @public
* @deprecated
*
* @param surveyId The ID of the survey to check.
* @returns A SurveyRenderReason object indicating if the survey can be rendered.
*/
canRenderSurvey(surveyId: string): SurveyRenderReason | null;
/**
* Checks the feature flags associated with this Survey to see if the survey can be rendered.
*
* {@label Surveys}
*
* @example
* ```js
* posthog.canRenderSurveyAsync(surveyId).then((result) => {
* if (result.visible) {
* // Survey can be rendered
* console.log('Survey can be rendered')
* } else {
* // Survey cannot be rendered
* console.log('Survey cannot be rendered:', result.disabledReason)
* }
* })
* ```
*
* @public
*
* @param surveyId The ID of the survey to check.
* @param forceReload If true, the survey will be reloaded from the server, Default: false
* @returns A SurveyRenderReason object indicating if the survey can be rendered.
*/
canRenderSurveyAsync(surveyId: string, forceReload?: boolean): Promise<SurveyRenderReason>;
private _validateIdentifyId;
/**
* Associates a user with a unique identifier instead of an auto-generated ID.
* Learn more about [identifying users](/docs/product-analytics/identify)
*
* {@label Identification}
*
* @remarks
* By default, PostHog assigns each user a randomly generated `distinct_id`. Use this method to
* replace that ID with your own unique identifier (like a user ID from your database).
*
* @example
* ```js
* // basic identification
* posthog.identify('user_12345')
* ```
*
* @example
* ```js
* // identify with user properties
* posthog.identify('user_12345', {
* email: 'user@example.com',
* plan: 'premium'
* })
* ```
*
* @example
* ```js
* // identify with set and set_once properties
* posthog.identify('user_12345',
* { last_login: new Date() }, // updates every time
* { signup_date: new Date() } // sets only once
* )
* ```
*
* @public
*
* @param {String} [new_distinct_id] A non-empty string that uniquely identifies a user.
* @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce,
* it will be overwritten by the value in userPropertiesToSet.
* @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
*/
identify(new_distinct_id: string, userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void;
/**
* Sets properties on the person profile associated with the current `distinct_id`.
* Learn more about [identifying users](/docs/product-analytics/identify)
*
* {@label Identification}
*
* @remarks
* Updates user properties that are stored with the person profile in PostHog.
* If `person_profiles` is set to `identified_only` and no profile exists, this will create one.
*
* @example
* ```js
* // set user properties
* posthog.setPersonProperties({
* email: 'user@example.com',
* plan: 'premium'
* })
* ```
*
* @example
* ```js
* // set properties
* posthog.setPersonProperties(
* { name: 'Max Hedgehog' }, // $set properties
* { initial_url: '/blog' } // $set_once properties
* )
* ```
*
* @public
*
* @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce,
* it will be overwritten by the value in userPropertiesToSet.
* @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
*/
setPersonProperties(userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void;
/**
* Removes properties from the person profile associated with the current `distinct_id`.
* Learn more about [identifying users](/docs/product-analytics/identify)
*
* {@label Identification}
*
* @remarks
* Deletes the given person properties from the person profile in PostHog. This is the
* counterpart to {@link setPersonProperties} — instead of hand-passing `$unset` inside a
* `capture()` call, you can remove properties with a dedicated method.
* If `person_profiles` is set to `never`, this call is ignored.
*
* `$fbc` and `$fbp` read by the SDK are unset for this call only. `save_campaign_params: false` stops the reads.
*
* @example
* ```js
* // remove a single property
* posthog.unsetPersonProperties('plan')
* ```
*
* @example
* ```js
* // remove multiple properties
* posthog.unsetPersonProperties(['plan', 'email'])
* ```
*
* @public
*
* @param {String|String[]} propertyNames The name (or names) of the person properties to remove.
*/
unsetPersonProperties(propertyNames: string | string[]): void;
/**
* Associates the user with a group for group-based analytics.
* Learn more about [groups](/docs/product-analytics/group-analytics)
*
* {@label Identification}
*
* @remarks
* Groups allow you to analyze users collectively (e.g., by organization, team, or account).
* This sets the group association for all subsequent events and reloads feature flags.
*
* @example
* ```js
* // associate user with an organization
* posthog.group('organization', 'org_12345', {
* name: 'Acme Corp',
* plan: 'enterprise'
* })
* ```
*
* @example
* ```js
* // associate with multiple group types
* posthog.group('organization', 'org_12345')
* posthog.group('team', 'team_67890')
* ```
*
* @public
*
* @param {String} groupType Group type (example: 'organization')
* @param {String} groupKey Group key (example: 'org::5')
* @param {Object} groupPropertiesToSet Optional properties to set for group
*/
group(groupType: string, groupKey: string, groupPropertiesToSet?: Properties): void;
/**
* Resets only the group properties of the user currently logged in.
* Learn more about [groups](/docs/product-analytics/group-analytics)
*
* {@label Identification}
*
* @example
* ```js
* posthog.resetGroups()
* ```
*
* @public
*/
resetGroups(): void;
/**
* Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet,
* or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:
*
* {@label Feature flags}
*
* @example
* ```js
* // Set properties
* posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})
* ```
*
* @example
* ```js
* // Set properties without reloading
* posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)
* ```
*
* @public
*
* @param {Object} properties The properties to override.
* @param {Boolean} [reloadFeatureFlags] Whether to reload feature flags.
*/
setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags?: boolean): void;
/**
* Resets the person properties for feature flags.
*
* {@label Feature flags}
*
* @public
*
* @example
* ```js
* posthog.resetPersonPropertiesForFlags()
* ```
*
* @example
* ```js
* // Reset properties without reloading
* posthog.resetPersonPropertiesForFlags(false)
* ```
*
* @param {Boolean} [reloadFeatureFlags=true] Whether to reload feature flags.
*/
resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): void;
/**
* Set override group properties for feature flags.
* This is used when dealing with new groups / where you don't want to wait for ingestion
* to update properties.
* Takes in an object, the key of which is the group type.
*
* {@label Feature flags}
*
* @public
*
* @example
* ```js
* // Set properties with reload
* posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })
* ```
*
* @example
* ```js
* // Set properties without reload
* posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false)
* ```
*
* @param {Object} properties The properties to override, the key of which is the group type.
* @param {Boolean} [reloadFeatureFlags] Whether to reload feature flags.
*/
setGroupPropertiesForFlags(properties: {
[type: string]: Properties;
}, reloadFeatureFlags?: boolean): void;
/**
* Resets the group properties for feature flags.
*
* {@label Feature flags}
*
* @public
*
* @example
* ```js
* posthog.resetGroupPropertiesForFlags()
* ```
*
* @param {string} [group_type] Optional group type to reset. If omitted, all group properties are reset.
*/
resetGroupPropertiesForFlags(group_type?: string): void;
/**
* Resets all user data and starts a fresh session.
*
* ⚠️ **Warning**: Only call this when a user logs out. Calling at the wrong time can cause split sessions.
*
* This clears:
* - Session ID and super properties
* - User identification (sets new random distinct_id)
* - Cached data and consent settings
*
* ⚠️ **Warning**: because consent is cleared, `reset()` returns the instance to the default
* consent state. With `opt_out_capturing_by_default` that default is opted out,
* so calling `reset()` *after* `opt_in_capturing()` silently stops capturing.
* Always `reset()` first, then opt in.
*
* {@label Identification}
* @example
* ```js
* // reset on user logout
* function logout() {
* posthog.reset()
* // redirect to login page
* }
* ```
*
* @example
* ```js
* // reset and generate new device ID
* posthog.reset(true) // also resets device_id
* ```
*
* @example
* ```js
* // reset with a custom anonymous ID and bootstrapped feature flags
* posthog.reset({
* bootstrap: {
* distinctID: myAnonymousID,
* isIdentifiedID: false,
* featureFlags: { 'my-flag': true },
* }
* })
* ```
*
* @example
* ```js
* // with opt_out_capturing_by_default, reset() before opting in, never after
* posthog.reset()
* posthog.opt_in_capturing()
* ```
*
* @public
*
* @param options Boolean to reset the device ID (legacy), or reset options including bootstrap values.
*/
reset(options?: boolean | ResetOptions): void;
private _reset;
/**
* Flushes any queued events and resolves once teardown is complete.
*
* @remarks
* This exists primarily for parity with the server-side
* [Node.js SDK](/docs/libraries/node), whose `shutdown()` you call once before a
* process exits. In the browser there is no process to exit, so this method
* performs synchronous best-effort extension cleanup, flushes the request
* queues, and always resolves.
*
* It is safe to call in isomorphic teardown code (for example a Nuxt/Next module
* that calls `shutdown()` on both the server and the client) so the same
* symmetric cleanup works in either environment without throwing.
*
* {@label Lifecycle}
* @example
* ```js
* // symmetric teardown that runs on both server and client
* await posthog.shutdown()
* ```
*
* @public
*
* @param {number} [_shutdownTimeoutMs] Retained for parity with the Node.js SDK; ignored in browsers.
* @returns {Promise<void>} A promise that resolves once best-effort cleanup and queue flushing complete.
*/
shutdown(_shutdownTimeoutMs?: number): Promise<void>;
/**
* Set HMAC-based identity verification.
*
* @remarks
* When set, products like conversations use server-verified identity
* (distinct_id + HMAC hash) instead of anonymous session identifiers.
* The hash should be computed server-side as HMAC-SHA256 of the
* distinct_id, signed with the Secret API key from Support settings.
* Project secret API keys (project settings) and personal API keys are rejected.
* Any additional signed identity claims are cleared because they are
* bound to the previously configured distinct_id.
*
* @param distinctId - The verified user distinct_id
* @param hash - HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings
*
* @example
* ```js
* posthog.setIdentity('user_123', 'a1b2c3d4e5f6...')
* ```
*
* @public
*/
setIdentity(distinctId: string, hash: string): void;
/**
* Clear HMAC-based identity verification, reverting to anonymous mode.
*
* @example
* ```js
* posthog.clearIdentity()
* ```
*
* @public
*/
clearIdentity(): void;
/**
* Returns the current distinct ID for the user.
*
* @remarks
* This is either the auto-generated ID or the ID set via `identify()`.
* The distinct ID is used to associate events with users in PostHog.
*
* {@label Identification}
*
* @example
* ```js
* // get the current user ID
* const userId = posthog.get_distinct_id()
* console.log('Current user:', userId)
* ```
*
* @example
* ```js
* // use in loaded callback
* posthog.init('token', {
* loaded: (posthog) => {
* const id = posthog.get_distinct_id()
* // use the ID
* }
* })
* ```
*
* @public
*
* @returns The current distinct ID
*/
get_distinct_id(): string;
/**
* Returns the current groups.
*
* {@label Identification}
*
* @public
*
* @returns The current groups
*/
getGroups(): Record<string, any>;
/**
* Returns the current session_id.
*
* @remarks
* This should only be used for informative purposes.
* Any actual internal use case for the session_id should be handled by the sessionManager.
*
* @public
*
* @returns The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.
*/
get_session_id(): string;
/**
* Returns the Replay url for the current session.
*
* {@label Session replay}
*
* @public
*
* @example
* ```js
* // basic usage
* posthog.get_session_replay_url()
* ```
*
* @example
* ```js
* // timestamp
* posthog.get_session_replay_url({ withTimestamp: true })
* ```
*
* @example
* ```js
* // timestamp and lookback
* posthog.get_session_replay_url({
* withTimestamp: true,
* timestampLookBack: 30 // look back 30 seconds
* })
* ```
*
* @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 URL for the current session replay, or an empty string if sessions are unavailable.
*/
get_session_replay_url(options?: {
withTimestamp?: boolean;
timestampLookBack?: number;
}): string;
/**
* Creates an alias linking two distinct user identifiers. Learn more about [identifying users](/docs/product-analytics/identify)
*
* {@label Identification}
*
* @remarks
* PostHog will use this to link two distinct_ids going forward (not retroactively).
* Call this when a user signs up to connect their anonymous session with their account.
*
*
* @example
* ```js
* // link anonymous user to account on signup
* posthog.alias('user_12345')
* ```
*
* @example
* ```js
* // explicit alias with original ID
* posthog.alias('user_12345', 'anonymous_abc123')
* ```
*
* @public
*
* @param {String} alias A unique identifier that you want to use for this user in the future.
* @param {String} [original] The current identifier being used for this user.
* @returns The `$create_alias` capture result, `-1` if alias matches the current distinct ID, `-2` if aliasing would duplicate a People user, or void if person processing is disabled.
*/
alias(alias: string, original?: string): CaptureResult | void | number;
/**
* Updates the configuration of the PostHog instance.
*
* {@label Initialization}
*
* @public
*
* @param {Partial<PostHogConfig>} config A dictionary of new configuration values to update
*/
set_config(config: Partial<PostHogConfig>): void;
/**
* @internal
* Allows wrapper SDKs (e.g. posthog-flutter, posthog-react-native) to override the
* `$lib` and `$lib_version` properties sent with every event.
*
* This is not a public API and may change without notice.
*/
_overrideSDKInfo(sdkName: string, sdkVersion: string): void;
/**
* turns session recording on, and updates the config option `disable_session_recording` to false
*
* {@label Session replay}
*
* @public
*
* @example
* ```js
* // Start and ignore controls
* posthog.startSessionRecording(true)
* ```
*
* @example
* ```js
* // Start and override controls
* posthog.startSessionRecording({
* // you don't have to send all of these
* sampling: true || false,
* linked_flag: true || false,
* url_trigger: true || false,
* event_trigger: true || false
* })
* ```
*
* @param override.sampling - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling config.
* @param override.linked_flag - optional boolean to override the default linked_flag behavior - ensures the next session recording to start will not be skipped by linked_flag config.
* @param override.url_trigger - optional boolean to override the default url_trigger behavior - ensures the next session recording to start will not be skipped by url_trigger config.
* @param override.event_trigger - optional boolean to override the default event_trigger behavior - ensures the next session recording to start will not be skipped by event_trigger config.
* @param override - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config. `true` is shorthand for { sampling: true, linked_flag: true }
*/
startSessionRecording(override?: {
sampling?: boolean;
linked_flag?: boolean;
url_trigger?: true;
event_trigger?: true;
} | true): void;
/**
* turns session recording off, and updates the config option
* disable_session_recording to true
*
* {@label Session replay}
*
* @public
*
* @example
* ```js
* // Stop session recording
* posthog.stopSessionRecording()
* ```
*/
stopSessionRecording(): void;
/**
* returns a boolean indicating whether session recording
* is currently running
*
* {@label Session replay}
*
* @public
*
* @example
* ```js
* // Stop session recording if it's running
* if (posthog.sessionRecordingStarted()) {
* posthog.stopSessionRecording()
* }
* ```
*
* @returns Whether session recording is currently running.
*/
sessionRecordingStarted(): boolean;
/**
* Capture a caught exception manually
*
* {@label Error tracking}
*
* @public
*
* @example
* ```js
* // Capture a caught exception
* try {
* // something that might throw
* } catch (error) {
* posthog.captureException(error)
* }
* ```
*
* @example
* ```js
* // With additional properties
* posthog.captureException(error, {
* customProperty: 'value',
* anotherProperty: ['I', 'can be a list'],
* ...
* })
* ```
*
* @param {unknown} error The error or exception-like value to capture.
* @param {Properties} [additionalProperties] Any additional properties to add to the error event.
* @returns The result of the capture, or undefined if exception capture is unavailable.
*/
captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined;
/**
* Add a breadcrumb-like step that will be attached to the next captured exception.
*
* {@label Error tracking}
*
* @public
*
* @example
* ```js
* posthog.addExceptionStep('Checkout button clicked', {
* checkout_id: 'ch_123',
* })
* ```
*
* @param {string} message The step message.
* @param {Properties} [properties] Additional context for this step.
*/
addExceptionStep(message: string, properties?: Properties): void;
/**
* Capture a log entry and send it to the PostHog logs endpoint.
*
* {@label Logs}
*
* @public
*
* @example
* ```js
* posthog.captureLog({
* body: 'checkout completed',
* level: 'info',
* attributes: { order_id: 'ord_789', amount_cents: 4999 },
* })
* ```
*
* @param {CaptureLogOptions} options The log entry options
*/
captureLog(options: CaptureLogOptions): void;
private static _noopLogger;
/**
* 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' })
* ```
*/
get logger(): import("@posthog/types").Logger;
/**
* turns exception autocapture on, and updates the config option `capture_exceptions` to the provided config (or `true`)
*
* {@label Error tracking}
*
* @public
*
* @example
* ```js
* // Start with default exception autocapture rules. No-op if already enabled
* posthog.startExceptionAutocapture()
* ```
*
* @example
* ```js
* // Start and override controls
* posthog.startExceptionAutocapture({
* // you don't have to send all of these (unincluded values will use the default)
* capture_unhandled_errors: true || false,
* capture_unhandled_rejections: true || false,
* capture_console_errors: true || false
* })
* ```
*
* @param config - optional configuration option to control the exception autocapture behavior
*/
startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void;
/**
* turns exception autocapture off by updating the config option `capture_exceptions` to `false`
*
* {@label Error tracking}
*
* @public
*
* @example
* ```js
* // Stop capturing exceptions automatically
* posthog.stopExceptionAutocapture()
* ```
*/
stopExceptionAutocapture(): void;
/**
* returns a boolean indicating whether the [toolbar](/docs/toolbar) loaded
*
* {@label Toolbar}
*
* @public
*
* @param {ToolbarParams} params Toolbar parameters.
* @returns Whether the toolbar loaded.
*/
loadToolbar(params: ToolbarParams): boolean;
/**
* Returns the value of a super property. Returns undefined if the property doesn't exist.
*
* {@label Identification}
*
* @remarks
* get_property() can only be called after the PostHog library has finished loading.
* init() has a loaded function available to handle this automatically.
*
* @example
* ```js
* // grab value for '$user_id' after the posthog library has loaded
* posthog.init('<YOUR PROJECT TOKEN>', {
* loaded: function(posthog) {
* user_id = posthog.get_property('$user_id');
* }
* });
* ```
* @public
*
* @param {String} property_name The name of the super property you want to retrieve
* @returns The stored property value, or undefined if it is not set.
*/
get_property(property_name: string): Property | undefined;
/**
* Returns the value of the session super property named property_name. If no such
* property is set, getSessionProperty() will return the undefined value.
*
* {@label Identification}
*
* @public
*
* @remarks
* This is based on browser-level `sessionStorage`, NOT the PostHog session.
* getSessionProperty() can only be called after the PostHog library has finished loading.
* init() has a loaded function available to handle this automatically.
*
* @example
* ```js
* // grab value for 'user_id' after the posthog library has loaded
* posthog.init('YOUR PROJECT TOKEN', {
* loaded: function(posthog) {
* user_id = posthog.getSessionProperty('user_id');
* }
* });
* ```
*
* @param {String} property_name The name of the session super property you want to retrieve
* @returns The stored session property value, or undefined if it is not set.
*/
getSessionProperty(property_name: string): Property | undefined;
/**
* Returns a string representation of the PostHog instance.
*
* {@label Initialization}
*
* @internal
*/
toString(): string;
_isIdentified(): boolean;
_hasPersonProcessing(): boolean;
_shouldCapturePageleave(): boolean;
/**
* Creates a person profile for the current user, if they don't already have one and config.person_profiles is set
* to 'identified_only'. Produces a warning and does not create a profile if config.person_profiles is set to
* 'never'. Learn more about [person profiles](/docs/product-analytics/identify)
*
* {@label Identification}
*
* @public
*
* @example
* ```js
* posthog.createPersonProfile()
* ```
*/
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;
/**
* Enables person processing if possible, returns true if it does so or already enabled, false otherwise
*
* @param function_name
*/
_requirePersonProcessing(function_name: string): boolean;
private _is_persistence_disabled;
private _sync_opt_out_with_persistence;
/**
* Opts the user into data capturing and persistence.
*
* {@label Privacy}
*
* @remarks
* Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance.
* By default, captures an `$opt_in` event unless disabled.
*
* @example
* ```js
* // simple opt-in
* posthog.opt_in_capturing()
* ```
*
* @example
* ```js
* // opt-in with custom event and properties
* posthog.opt_in_capturing({
* captureEventName: 'Privacy Accepted',
* captureProperties: { source: 'banner' }
* })
* ```
*
* @example
* ```js
* // opt-in without capturing event
* posthog.opt_in_capturing({
* captureEventName: false
* })
* ```
*
* @public
*
* @param {Object} [options] A dictionary of opt-in options.
* @param {EventName | null | false} [options.captureEventName] Event name to use for capturing the opt-in action. Set to `null` or `false` to skip capturing the opt-in event. Defaults to `$opt_in`.
* @param {Properties} [options.captureProperties] Set of properties to capture along with the opt-in action.
*/
opt_in_capturing(options?: {
captureEventName?: EventName | null | false; /** event name to be used for capturing the opt-in action */
captureProperties?: Properties; /** set of properties to be captured along with the opt-in action */
}): void;
/**
* Opts the user out of data capturing and persistence.
*
* {@label Privacy}
*
* @remarks
* Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance.
* If `opt_out_persistence_by_default` is true, SDK persistence will also be disabled.
*
* @example
* ```js
* // opt user out (e.g., on privacy settings page)
* posthog.opt_out_capturing()
* ```
*
* @public
*/
opt_out_capturing(): void;
private _enterCookielessMode;
/**
* Checks if the user has opted into data capturing.
*
* {@label Privacy}
*
* @remarks
* Returns the current consent status for event tracking and data persistence.
*
* @example
* ```js
* if (posthog.has_opted_in_capturing()) {
* // show analytics features
* }
* ```
*
* @public
*
* @returns {boolean} current opt-in status
*/
has_opted_in_capturing(): boolean;
/**
* Checks if the user has opted out of data capturing.
*
* {@label Privacy}
*
* @remarks
* Returns the current consent status for event tracking and data persistence.
*
* In cookieless `'always'` mode this returns `true`, because the SDK does not store data for the user. Events are
* still captured in this mode. To check if the SDK captures events, use `is_capturing()`.
*
* @example
* ```js
* if (posthog.has_opted_out_capturing()) {
* // disable analytics features
* }
* ```
*
* @public
*
* @returns {boolean} current opt-out status
*/
has_opted_out_capturing(): boolean;
/**
* Returns the explicit consent status of the user.
*
* @remarks
* This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not
* take the default config options into account, only whether the user has made an explicit choice, so this can be
* used to determine whether to show an initial cookie banner or not.
*
* @example
* ```js
* const consentStatus = posthog.get_explicit_consent_status()
* if (consentStatus === "granted") {
* // user has explicitly opted in
* } else if (consentStatus === "denied") {
* // user has explicitly opted out
* } else if (consentStatus === "pending"){
* // user has not made a choice, show consent banner
* }
* ```
*
* @public
*
* @returns The current explicit consent status.
*/
get_explicit_consent_status(): 'granted' | 'denied' | 'pending';
/**
* Checks whether the PostHog library is currently capturing events.
*
* Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by
* some config options.
*
* Additionally, if the cookieless_mode is set to `'on_reject'`, we will capture events in cookieless mode if the
* user has opted out or been defaulted to opt-out.
*
* {@label Privacy}
*
* @see {PostHogConfig.cookieless_mode}
* @see {PostHogConfig.opt_out_persistence_by_default}
* @see {PostHogConfig.respect_dnt}
*
* @returns {boolean} whether the posthog library is capturing events
*/
is_capturing(): boolean;
/**
* Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
*
* {@label Privacy}
*
* @public
*
*/
clear_opt_in_out_capturing(): void;
_is_bot(): boolean | undefined;
_captureInitialPageview(): void;
/**
* Enables or disables debug mode for detailed logging.
*
* @remarks
* Debug mode logs all PostHog calls to the browser console for troubleshooting.
* Can also be enabled by adding `?__posthog_debug=true` to the URL.
*
* {@label Initialization}
*
* @example
* ```js
* // enable debug mode
* posthog.debug(true)
* ```
*
* @example
* ```js
* // disable debug mode
* posthog.debug(false)
* ```
*
* @public
*
* @param {boolean} [debug] If true, will enable debug mode.
*/
debug(debug?: boolean): void;
/**
* Helper method to check if external API calls (flags/decide) should be disabled
* Handles migration from old `advanced_disable_decide` to new `advanced_disable_flags`
*/
_shouldDisableFlags(): boolean;
private _runBeforeSend;
/**
* Returns the current page view ID.
*
* {@label Initialization}
*
* @public
*
* @returns The current page view ID, or undefined if no page view has been captured.
*/
getPageViewId(): string | undefined;
/**
* Capture written user feedback for a LLM trace. Numeric values are converted to strings.
*
* {@label LLM analytics}
*
* @public
*
* @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. Numeric values are converted to strings.
*
* {@label LLM analytics}
*
* @public
*
* @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;
private _checkLocalStorageForDebug;
}
export declare function init_from_snippet(): void;
export declare function init_as_module(): PostHog;
export {};