PostHog JavaScript Web SDK
Getting started
The JavaScript Web SDK runs in the browser.
To send your first event, add the HTML snippet to your site, or install posthog-js and call posthog.init once. Both take your project token and host from your project settings.
After init, PostHog captures pageviews and clicks by itself, so loading a page sends your first event to the Activity page in PostHog. Use capture for your own events.
For server-side JavaScript, use the Node.js SDK.
Install with the HTML snippet
The snippet is the quickest way to add PostHog to a website. Paste it inside your site's <head> tags, just before </head>, so PostHog loads on every page. Replace the project token and host with your own.
The snippet loads the latest SDK from PostHog and calls init, so you can skip the next two steps.
Install with a package manager
Initialize
Capture an event
Identify a user
Setup
new PostHog(...)
new PostHog():
PostHog
Creates an uninitialized PostHog instance.
Returns
PostHog
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
PostHog.init
init(
token,config?,name?):PostHog
Initializes a new instance of the PostHog capturing object.
Parameters
| Parameter | Type | Description |
|---|---|---|
token | string | Your PostHog API token |
config? | Partial<PostHogConfig> | A dictionary of config options to override |
name? | string | The name for the new posthog instance that you want created |
Returns
PostHog
The newly initialized PostHog instance
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
Examples
PostHog.set_config
set_config(
config):void
Updates the configuration of the PostHog instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | Partial<PostHogConfig> | A dictionary of new configuration values to update |
Returns
void
posthog
constposthog:PostHog
The default PostHog JavaScript Web SDK singleton instance.
Capture
PostHog.capture
capture(
event_name,properties?,options?):CaptureResult|undefined
Captures an event with optional properties and configuration.
Parameters
| Parameter | Type | Description |
|---|---|---|
event_name | EventName | The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase') |
properties? | Properties | null | Properties to include with the event describing the user or event details |
options? | CaptureOptions | Optional configuration for the capture request |
Returns
CaptureResult | undefined
The capture result containing event data, or undefined if capture failed
Remarks
You can capture arbitrary object-like values as events. Learn about capture best practices
Example
Identify
PostHog.clearIdentity
clearIdentity():
void
Clear HMAC-based identity verification, reverting to anonymous mode.
Returns
void
Example
PostHog.identify
identify(
new_distinct_id?,userPropertiesToSet?,userPropertiesToSetOnce?):void
Associates a user with a unique identifier instead of an auto-generated ID. Learn more about identifying users
Parameters
| Parameter | Type | Description |
|---|---|---|
new_distinct_id? | string | A non-empty string that uniquely identifies a user. |
userPropertiesToSet? | Properties | 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. |
userPropertiesToSetOnce? | Properties | Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. |
Returns
void
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).
Examples
PostHog.setIdentity
setIdentity(
distinctId,hash):void
Set HMAC-based identity verification.
Parameters
| Parameter | Type | Description |
|---|---|---|
distinctId | string | The verified user distinct_id |
hash | string | HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings |
Returns
void
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.
Example
Logs
PostHog.logger
get logger():
Logger
Logger with convenience methods for each severity level.
Example
Returns
Logger
PostHog.captureLog
captureLog(
options):void
Capture a log entry and send it to the PostHog logs endpoint.
Note: logs are not subject to the user agent (bot) filter that drops events, so they are still sent from sessions whose events are dropped.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CaptureLogOptions | The log entry options |
Returns
void
Example
Alias
PostHog.alias
alias(
alias,original?):number|void|CaptureResult
Creates an alias linking two distinct user identifiers. Learn more about identifying users
Parameters
| Parameter | Type | Description |
|---|---|---|
alias | string | A unique identifier that you want to use for this user in the future. |
original? | string | The current identifier being used for this user. |
Returns
number | void | CaptureResult
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.
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.
Examples
Capture AI
PostHog.captureTraceFeedback
captureTraceFeedback(
traceId,userFeedback):void
Capture written user feedback for a LLM trace. Numeric values are converted to strings.
Parameters
| Parameter | Type | Description |
|---|---|---|
traceId | string | number | The trace ID to capture feedback for. |
userFeedback | string | The feedback to capture. |
Returns
void
PostHog.captureTraceMetric
captureTraceMetric(
traceId,metricName,metricValue):void
Capture a metric for a LLM trace. Numeric values are converted to strings.
Parameters
| Parameter | Type | Description |
|---|---|---|
traceId | string | number | The trace ID to capture the metric for. |
metricName | string | The name of the metric to capture. |
metricValue | string | number | boolean | The value of the metric to capture. |
Returns
void
Capture exception
PostHog.captureException
captureException(
error,additionalProperties?):CaptureResult|undefined
Capture a caught exception manually
Parameters
| Parameter | Type | Description |
|---|---|---|
error | unknown | The error or exception-like value to capture. |
additionalProperties? | Properties | Any additional properties to add to the error event. |
Returns
CaptureResult | undefined
The result of the capture, or undefined if exception capture is unavailable.
Examples
PostHog.startExceptionAutocapture
startExceptionAutocapture(
config?):void
turns exception autocapture on, and updates the config option capture_exceptions to the provided config (or true)
Parameters
| Parameter | Type | Description |
|---|---|---|
config? | ExceptionAutoCaptureConfig | optional configuration option to control the exception autocapture behavior |
Returns
void
Examples
PostHog.stopExceptionAutocapture
stopExceptionAutocapture():
void
turns exception autocapture off by updating the config option capture_exceptions to false
Returns
void
Example
Create person profile
PostHog.createPersonProfile
createPersonProfile():
void
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
Returns
void
Example
Debug
PostHog.debug
debug(
debug?):void
Enables or disables debug mode for detailed logging.
Parameters
| Parameter | Type | Description |
|---|---|---|
debug? | boolean | If true, will enable debug mode. |
Returns
void
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.
Examples
Exception steps
PostHog.addExceptionStep
addExceptionStep(
message,properties?):void
Add a breadcrumb-like step that will be attached to the next captured exception.
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | The step message. |
properties? | Properties | Additional context for this step. |
Returns
void
Example
Get distinct ID
PostHog.get_distinct_id
get_distinct_id():
string
Returns the current distinct ID for the user.
Returns
string
The current distinct ID
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.
Examples
Get feature flag
PostHog.getFeatureFlag
getFeatureFlag(
key,options?):string|boolean|undefined
Gets the value of a feature flag for the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | 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
string | boolean | undefined
The feature flag value, or undefined if the flag is unavailable.
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.
Examples
Get feature flag payload
PostHog.getFeatureFlagPayload
getFeatureFlagPayload(
key):JsonType
Get feature flag payload value matching key for user (supports multivariate flags).
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
Returns
JsonType
The feature flag payload.
Example
Deprecated
Use getFeatureFlagResult() instead
Get feature flag result
PostHog.getFeatureFlagResult
getFeatureFlagResult(
key,options?):FeatureFlagResult|undefined
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | Options for the feature flag lookup. |
Returns
FeatureFlagResult | undefined
The feature flag result including key, enabled, variant, and payload.
Examples
Get feature flags
PostHog.getAllFeatureFlags
getAllFeatureFlags():
FeatureFlagResult[]
Returns all currently cached feature flags as FeatureFlagResults. 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.
Get session ID
PostHog.get_session_id
get_session_id():
string
Returns the current session_id.
Returns
string
The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.
Remarks
This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.
PostHog.onSessionId
onSessionId(
callback?): () =>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.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback? | SessionIdChangedCallback | The callback function will be called once a session id is present or when it or the window id are updated. |
Returns
A function that can be called to unsubscribe the listener. E.g. Used by useEffect when the component unmounts.
() => void
Example
Group
PostHog.getGroups
getGroups():
Record<string,any>
Returns the current groups.
Returns
Record<string, any>
The current groups
PostHog.group
group(
groupType,groupKey,groupPropertiesToSet?):void
Associates the user with a group for group-based analytics. Learn more about groups
Parameters
| Parameter | Type | Description |
|---|---|---|
groupType | string | Group type (example: 'organization') |
groupKey | string | Group key (example: 'org::5') |
groupPropertiesToSet? | Properties | Optional properties to set for group |
Returns
void
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.
Examples
PostHog.resetGroups
resetGroups():
void
Resets only the group properties of the user currently logged in. Learn more about groups
Returns
void
Example
Is feature enabled
PostHog.isFeatureEnabled
isFeatureEnabled(
key,options?):boolean
Checks if a feature flag is enabled for the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions & object & object | 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
Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
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.
Examples
Call Signature
isFeatureEnabled(
key,options?):boolean|undefined
Checks if a feature flag is enabled for the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | IsFeatureEnabledOptions | 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.
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.
Examples
Is opt out
PostHog.has_opted_in_capturing
has_opted_in_capturing():
boolean
Checks if the user has opted into data capturing.
Returns
boolean
current opt-in status
Remarks
Returns the current consent status for event tracking and data persistence.
Example
PostHog.has_opted_out_capturing
has_opted_out_capturing():
boolean
Checks if the user has opted out of data capturing.
Returns
boolean
current opt-out status
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
PostHog.is_capturing
is_capturing():
boolean
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.
Returns
boolean
whether the posthog library is capturing events
See
Is session replay active
PostHog.sessionRecordingStarted
sessionRecordingStarted():
boolean
returns a boolean indicating whether session recording is currently running
Returns
boolean
Whether session recording is currently running.
Example
On feature flags
PostHog.onFeatureFlags
onFeatureFlags(
callback): () =>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.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | FeatureFlagsCallback | 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.
() => void
Example
Opt in
PostHog.clear_opt_in_out_capturing
clear_opt_in_out_capturing():
void
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
Returns
void
PostHog.opt_in_capturing
opt_in_capturing(
options?):void
Opts the user into data capturing and persistence.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | { captureEventName?: false | EventName | null; captureProperties?: Properties; } | A dictionary of opt-in options. |
options.captureEventName? | false | EventName | null | 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. |
options.captureProperties? | Properties | Set of properties to capture along with the opt-in action. |
Returns
void
Remarks
Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance.
By default, captures an $opt_in event unless disabled. The event is only captured when the user was not
already opted in, so calling this on every page load (for example from a consent tool callback that re-applies
stored consent) sends it once per user rather than once per page.
Examples
PostHog.opt_out_capturing
opt_out_capturing():
void
Opts the user out of data capturing and persistence.
Returns
void
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
Register
PostHog.get_property
get_property(
property_name):any
Returns the value of a super property. Returns undefined if the property doesn't exist.
Parameters
| Parameter | Type | Description |
|---|---|---|
property_name | string | The name of the super property you want to retrieve |
Returns
any
The stored property value, or undefined if it is not set.
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
PostHog.getSessionProperty
getSessionProperty(
property_name):any
Returns the value of the session super property named property_name. If no such property is set, getSessionProperty() will return the undefined value.
Parameters
| Parameter | Type | Description |
|---|---|---|
property_name | string | The name of the session super property you want to retrieve |
Returns
any
The stored session property value, or undefined if it is not set.
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
PostHog.register
register(
properties,days?):void
Registers super properties that are included with all events.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | properties to store about the user |
days? | number | How many days since the user's last visit to store the super properties |
Returns
void
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.
Examples
PostHog.register_for_session
register_for_session(
properties):void
Registers super properties for the current session only.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | An associative array of properties to store about the user |
Returns
void
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.
Examples
PostHog.register_once
register_once(
properties,default_value?,days?):void
Registers super properties only if they haven't been set before.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | An associative array of properties to store about the user |
default_value? | any | Value to override if already set in super properties (ex: 'False') Default: 'None' |
days? | number | How many days since the users last visit to store the super properties |
Returns
void
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.
Examples
Reload feature flags
PostHog.reloadFeatureFlags
reloadFeatureFlags():
void
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
Returns
void
Example
Reset
PostHog.reset
reset(
options?):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.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | boolean | ResetOptions | Boolean to reset the device ID (legacy), or reset options including bootstrap values. |
Returns
void
Examples
Reset group properties for flags
PostHog.resetGroupPropertiesForFlags
resetGroupPropertiesForFlags(
group_type?):void
Resets the group properties for feature flags.
Parameters
| Parameter | Type | Description |
|---|---|---|
group_type? | string | Optional group type to reset. If omitted, all group properties are reset. |
Returns
void
Example
Reset person properties for flags
PostHog.resetPersonPropertiesForFlags
resetPersonPropertiesForFlags(
reloadFeatureFlags?):void
Resets the person properties for feature flags.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
reloadFeatureFlags? | boolean | true | Whether to reload feature flags. |
Returns
void
Examples
Set group properties for flags
PostHog.setGroupPropertiesForFlags
setGroupPropertiesForFlags(
properties,reloadFeatureFlags?):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.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
properties | {[type: string]: Properties; } | undefined | The properties to override, the key of which is the group type. |
reloadFeatureFlags? | boolean | true | Whether to reload feature flags. |
Returns
void
Examples
Set person properties
PostHog.setInternalOrTestUser
setInternalOrTestUser():
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.
Returns
void
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.
Example
PostHog.setPersonProperties
setPersonProperties(
userPropertiesToSet?,userPropertiesToSetOnce?):void
Sets properties on the person profile associated with the current distinct_id.
Learn more about identifying users
Parameters
| Parameter | Type | Description |
|---|---|---|
userPropertiesToSet? | Properties | 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. |
userPropertiesToSetOnce? | Properties | Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. |
Returns
void
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.
Examples
PostHog.unsetPersonProperties
unsetPersonProperties(
propertyNames):void
Removes properties from the person profile associated with the current distinct_id.
Learn more about identifying users
Parameters
| Parameter | Type | Description |
|---|---|---|
propertyNames | string | string[] | The name (or names) of the person properties to remove. |
Returns
void
Remarks
Deletes the given person properties from the person profile in PostHog. This is the
counterpart to 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.
Examples
Set person properties for flags
PostHog.setPersonPropertiesForFlags
setPersonPropertiesForFlags(
properties,reloadFeatureFlags?):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:
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
properties | Properties | undefined | The properties to override. |
reloadFeatureFlags? | boolean | true | Whether to reload feature flags. |
Returns
void
Examples
Shutdown
PostHog.shutdown
shutdown(
_shutdownTimeoutMs?):Promise<void>
Flushes any queued events and resolves once teardown is complete.
Parameters
| Parameter | Type | Description |
|---|---|---|
_shutdownTimeoutMs? | number | 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.
Remarks
This exists primarily for parity with the server-side
Node.js SDK, 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.
Example
Start session recording
PostHog.startSessionRecording
startSessionRecording(
override?):void
turns session recording on, and updates the config option disable_session_recording to false
Parameters
| Parameter | Type | Description |
|---|---|---|
override? | true | { event_trigger?: true; linked_flag?: boolean; sampling?: boolean; url_trigger?: true; } | 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 } |
Returns
void
Examples
Stop session recording
PostHog.stopSessionRecording
stopSessionRecording():
void
turns session recording off, and updates the config option disable_session_recording to true
Returns
void
Example
Unregister
PostHog.unregister
unregister(
property):void
Removes a super property from persistent storage.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The name of the super property to remove |
Returns
void
Remarks
This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile.
Example
PostHog.unregister_for_session
unregister_for_session(
property):void
Removes a session super property from the current session.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The name of the session super property to remove |
Returns
void
Remarks
This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.
Example
Consent gating
PostHog.get_explicit_consent_status
get_explicit_consent_status():
"pending"|"granted"|"denied"
Returns the explicit consent status of the user.
Returns
"pending" | "granted" | "denied"
The current explicit consent status.
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
Surveys
PostHog.cancelPendingSurvey
cancelPendingSurvey(
surveyId):void
Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The survey ID whose pending display should be cancelled. |
Returns
void
PostHog.canRenderSurvey
canRenderSurvey(
surveyId):SurveyRenderReason|null
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The ID of the survey to check. |
Returns
SurveyRenderReason | null
A SurveyRenderReason object indicating if the survey can be rendered.
Deprecated
PostHog.canRenderSurveyAsync
canRenderSurveyAsync(
surveyId,forceReload?):Promise<SurveyRenderReason>
Checks the feature flags associated with this Survey to see if the survey can be rendered.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
surveyId | string | undefined | The ID of the survey to check. |
forceReload? | boolean | false | If true, the survey will be reloaded from the server, Default: false |
Returns
Promise<SurveyRenderReason>
A SurveyRenderReason object indicating if the survey can be rendered.
Example
PostHog.displaySurvey
displaySurvey(
surveyId,options?):void
Display a survey programmatically as either a popover or inline element.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
surveyId | string | undefined | The survey ID to display. |
options? | DisplaySurveyOptions | DEFAULT_DISPLAY_SURVEY_OPTIONS | Display configuration. Defaults to a popover that respects dashboard conditions and delays. |
Returns
void
Examples
PostHog.getActiveMatchingSurveys
getActiveMatchingSurveys(
callback,forceReload?):void
Get surveys that should be enabled for the current user. See fetching surveys documentation for more details.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
callback | SurveyCallback | undefined | The callback function will be called when the surveys are loaded or updated. |
forceReload? | boolean | false | Whether to force a reload of the surveys. |
Returns
void
Example
PostHog.getSurveys
getSurveys(
callback,forceReload?):void
Get list of all surveys.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
callback | SurveyCallback | undefined | Function that receives the array of surveys. |
forceReload? | boolean | false | Optional boolean to force an API call for updated surveys. |
Returns
void
Example
PostHog.onActiveMatchingSurveysChanged
onActiveMatchingSurveysChanged(
callback): () =>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.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | SurveyCallback | The callback to call with active matching surveys. |
Returns
A function that can be called to unsubscribe the listener.
() => void
Example
PostHog.onSurveysLoaded
onSurveysLoaded(
callback): () =>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
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | SurveyCallback | The callback function will be called when surveys are loaded or updated. |
Returns
A function that can be called to unsubscribe the listener.
() => void
Example
PostHog.renderSurvey
renderSurvey(
surveyId,selector):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.
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The ID of the survey to render. |
selector | string | The selector of the HTML element to render the survey on. |
Returns
void
Example
Deprecated
Use displaySurvey instead - it's more complete and also supports popover surveys.
DisplaySurveyType
constDisplaySurveyType:object
Type Declaration
SurveyEventName
constSurveyEventName:object
Type Declaration
SurveyEventProperties
constSurveyEventProperties:object
Type Declaration
SurveyEventType
constSurveyEventType:object
Type Declaration
SurveyPosition
constSurveyPosition:object
Type Declaration
SurveyQuestionBranchingType
constSurveyQuestionBranchingType:object
Type Declaration
SurveyQuestionType
constSurveyQuestionType:object
Type Declaration
SurveySchedule
constSurveySchedule:object
Type Declaration
SurveyTabPosition
constSurveyTabPosition:object
Type Declaration
SurveyType
constSurveyType:object
Type Declaration
SurveyWidgetType
constSurveyWidgetType:object
Type Declaration
SDK utils
PostHog.featureFlags
featureFlags:
TreeShakeable<PostHogFeatureFlags>
The feature flags instance. Provides access to feature flag override methods.
PostHog.version
version:
string=Config.LIB_VERSION
The library version.
PostHog.flagsEndpointWasHit
get flagsEndpointWasHit():
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
boolean
True once the SDK has processed feature flag values.
PostHog.get_session_replay_url
get_session_replay_url(
options?):string
Returns the Replay url for the current session.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | { timestampLookBack?: number; withTimestamp?: boolean; } | Options for the URL. |
options.timestampLookBack? | number | How many seconds to look back for the timestamp. |
options.withTimestamp? | boolean | Whether to include the timestamp in the URL. |
Returns
string
The URL for the current session replay, or an empty string if sessions are unavailable.
Examples
PostHog.getEarlyAccessFeatures
getEarlyAccessFeatures(
callback,force_reload?,stages?):void
Get the list of early access features. To check enrollment status, use isFeatureEnabled. Learn more in the docs
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
callback | EarlyAccessFeatureCallback | undefined | The callback function will be called when the early access features are loaded. |
force_reload? | boolean | false | Whether to force a reload of the early access features. |
stages? | EarlyAccessFeatureStage[] | undefined | The stages of the early access features to load. |
Returns
void
Example
PostHog.getPageViewId
getPageViewId():
string|undefined
Returns the current page view ID.
Returns
string | undefined
The current page view ID, or undefined if no page view has been captured.
PostHog.loadToolbar
loadToolbar(
params):boolean
returns a boolean indicating whether the toolbar loaded
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ToolbarParams | Toolbar parameters. |
Returns
boolean
Whether the toolbar loaded.
PostHog.on
on(
event,cb): () =>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 eventfeatureFlagsReloading: Emitted when feature flags are being reloaded (e.g. afteridentify(),group(), orreloadFeatureFlags())
Parameters
| Parameter | Type | Description |
|---|---|---|
event | "eventCaptured" | "featureFlagsReloading" | The event to listen for. |
cb | (...args) => void | The callback function to call when the event is emitted. |
Returns
A function that can be called to unsubscribe the listener.
() => void
Examples
PostHog.updateEarlyAccessFeatureEnrollment
updateEarlyAccessFeatureEnrollment(
key,isEnrolled,stage?):void
Opt the user in or out of an early access feature. Learn more in the docs
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The key of the feature flag to update. |
isEnrolled | boolean | Whether the user is enrolled in the feature. |
stage? | string | The stage of the feature flag to update. |
Returns
void
Example
PostHog.updateFlags
updateFlags(
flags,payloads?,options?):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.
Parameters
| Parameter | Type | Description |
|---|---|---|
flags | Record<string, boolean | string> | An object mapping flag keys to their values (boolean or string variant) |
payloads? | Record<string, JsonType> | Optional object mapping flag keys to their JSON payloads |
options? | { merge?: boolean; } | Optional settings. Use { merge: true } to merge with existing flags instead of replacing. |
options.merge? | boolean | - |
Returns
void
Example
Compression
constCompression:object
Type Declaration
DEFAULT_PRODUCT_TOUR_APPEARANCE
constDEFAULT_PRODUCT_TOUR_APPEARANCE:Required<ProductTourAppearance>
ProductTourEventName
constProductTourEventName:object
Type Declaration
ProductTourEventProperties
constProductTourEventProperties:object
Type Declaration
severityLevels
constseverityLevels: readonly ["fatal","error","warning","log","info","debug"]
Types
ActionStepStringMatching
ActionStepStringMatching =
"contains"|"exact"|"regex"
Sync with plugin-server/src/types.ts.
ActionStepType
ApiResponse
A minimal response from Client.sendRequest.
Properties
AutocaptureCompatibleElement
AutocaptureCompatibleElement =
"a"|"button"|"form"|"input"|"select"|"textarea"|"label"
AutocaptureConfig
If an array is passed for an allowlist, autocapture events will only be sent for elements matching at least one of the elements in the array. Multiple allowlists can be used
Extended by
AutocaptureConfig
Properties
| Property | Type | Description |
|---|---|---|
capture_copied_text? | boolean | When true, autocapture captures cut, copy, and paste interactions. Paste events do not contain pasted text. |
capture_value_css_selector_allowlist? | string[] | ((element) => boolean) | CSS selectors or a predicate opting individual native fields into value capture on change events. Selectors match the field itself, not its ancestors. An empty array disables value capture. String values are sent in $input_value and may be edited in before_send. Values are not automatically redacted; only opt in fields whose contents you intend to collect. Password fields, no-capture markers, sensitive-field exclusions, and mask_all_text still apply. Default ['[data-ph-capture-value]'] |
css_selector_allowlist? | string[] | List of CSS selectors to allow autocapture on e.g. ['[ph-capture]'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and allow list config ['[id]'] we will capture the click if the click-target or its parents has any id Everything is allowed when there's no allowlist |
css_selector_ignorelist? | string[] | List of CSS selectors to ignore autocapture on e.g. ['[data-ph-no-autocapture]'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and ignore list config ['[id]'] we will ignore the click if the click-target or its parents has any id Nothing is ignored when there's an empty ignorelist, e.g. [] If no ignorelist is set, we default to ignoring .ph-no-autocapture and [data-ph-no-autocapture] Note: providing any custom list fully replaces the defaults — include .ph-no-autocapture and [data-ph-no-autocapture] explicitly if you still want them honoured. |
dom_event_allowlist? | DomAutocaptureEvents[] | List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit'] |
element_allowlist? | AutocaptureCompatibleElement[] | List of DOM elements to allow autocapture on e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'] We consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg if the allowlist has button then we allow the capture when the button or the svg is the click target but not if either of the divs are detected as the click target |
element_attribute_ignorelist? | string[] | Exclude certain element attributes from autocapture E.g. ['aria-label'] or [data-attr-pii] |
url_allowlist? | (string | RegExp)[] | List of URLs to allow autocapture on, can be strings to match or regexes e.g. ['https://example.com', 'test.com/.*'] this is useful when you want to autocapture on specific pages only if you set both url_allowlist and url_ignorelist, we check the allowlist first and then the ignorelist. the ignorelist can override the allowlist |
url_ignorelist? | (string | RegExp)[] | List of URLs to not allow autocapture on, can be strings to match or regexes e.g. ['https://example.com', 'test.com/.*'] this is useful when you want to autocapture on most pages but not some specific ones if you set both url_allowlist and url_ignorelist, we check the allowlist first and then the ignorelist. the ignorelist can override the allowlist |
BasicSurveyQuestion
SurveyQuestionBase
Properties
BeforeSendFn
BeforeSendFn = (
cr) =>CaptureResult|null
Parameters
| Parameter | Type |
|---|---|
cr | CaptureResult |
Returns
CaptureResult | null
BeforeSendLogFn
BeforeSendLogFn = (
record) =>CaptureLogOptions|null
Pre-send filter. Inspect, mutate, or drop a captured log record before it
enters the rate cap or the buffer. Return the (possibly transformed) record
to keep it; return null to drop it.
Configure as a single function or an array. Arrays form a left-to-right
chain: each function receives the previous function's return value, and a
null from any link short-circuits the chain and drops the record. A
function that throws also drops the record (the error is logged).
Parameters
| Parameter | Type |
|---|---|
record | CaptureLogOptions |
Returns
CaptureLogOptions | null
Example
Redact secrets from log bodies
BeforeSendMetricFn
BeforeSendMetricFn = (
sample) =>MetricSample|null
Pre-aggregation filter. Return the (possibly transformed) sample to keep
it; return null to drop it. Configure as a single function or an array
forming a left-to-right chain; a null from any link drops the sample and
a thrown error also drops it (the error is logged).
Parameters
| Parameter | Type |
|---|---|
sample | MetricSample |
Returns
MetricSample | null
Example
Drop debug metrics in production
BootstrapConfig
BrowserMetricsConfig
Metrics configuration options for the browser SDK. Adds the options that only the browser SDK implements to the shared metrics options.
Extends
MetricsConfig
Properties
CanvasMaskRegion
CanvasMaskRegion =
object
A rectangle to paint over a recorded canvas frame, in CSS pixels relative to the canvas element.
Properties
CapturedEventInfo
A captured event, as observed by onEvent.
Properties
CapturedNetworkRequest
CapturedNetworkRequest =
Writable<Omit<PerformanceEntry,"toJSON">> &object
Type Declaration
| Name | Type |
|---|---|
endTime? | number |
initiatorType? | InitiatorType |
isInitial? | boolean |
method? | string |
requestBody? | string | null |
requestHeaders? | Headers |
responseBody? | string | null |
responseHeaders? | Headers |
startTime? | number |
status? | number |
timeOrigin? | number |
timestamp? | number |
CaptureLogOptions
CaptureMetricOptions
Options accepted by posthog.metrics.count/gauge/histogram.
Extended by
HistogramOptions
Properties
CaptureOptions
CaptureOptions
Per-call capture overrides, mirroring the client's public capture options.
Properties
CapturePageviewOptions
Selects which same-page URL changes automatically capture a $pageview.
Each option defaults to false when omitted.
Properties
CaptureResult
Client
The host SDK surface handed to an extension in setup. A conforming host
provides it as an adapter over its own analytics, transport, persistence,
event, and remote-config internals.
Properties
Methods
capture()
capture(
event,properties?,options?):boolean
Synchronously admits an analytics event to the client's normal pipeline.
Returns false when the client rate limit dropped the event, so the caller can send it again later.
An event that is dropped for another reason, for example by before_send, returns true.
Parameters
| Parameter | Type |
|---|---|
event | string |
properties? | Properties | null |
options? | CaptureOptions |
Returns
boolean
getExtension()
Call Signature
getExtension<
T>(token):T|undefined
Returns the extension registered under a typed stable name, or undefined when it is not installed.
Type Parameters
Parameters
| Parameter | Type |
|---|---|
token | ExtensionToken<T> |
Returns
T | undefined
Call Signature
getExtension<
T>(name):T|undefined
Returns the extension registered under a stable name, or undefined when it is not installed.
Type Parameters
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
T | undefined
registerDynamicEventProperties()
registerDynamicEventProperties(
producer):Disposable
Registers a synchronous producer of properties merged into every captured event.
Parameters
| Parameter | Type |
|---|---|
producer | () => Record<string, unknown> |
Returns
Disposable
sendRequest()
sendRequest(
path,init?):Promise<ApiResponse>
Sends a request through the host SDK's transport.
Parameters
| Parameter | Type |
|---|---|
path | string |
init? | SendRequestInit |
Returns
Promise<ApiResponse>
Compression
Compression = typeof
Compression[keyof typeofCompression]
ConfigDefaults
ConfigDefaults =
"latest"| typeofCONFIG_DEFAULTS_DATES[number] |"unset"
Configuration defaults snapshot used by PostHogConfig.defaults.
Later dates include all earlier default changes. latest includes all changes in the loaded SDK version.
ConversationsConfig
Conversations configuration options
Properties
ConversationsRemoteConfig
Remote configuration for conversations from the PostHog server.
Properties
ConversationsTheme
Theme of the conversations widget. The top-level colors are the light colors; dark holds the dark ones.
Values are applied as --ph-conv-* CSS custom properties (--ph-conv-primary, --ph-conv-on-primary,
--ph-conv-bg, --ph-conv-surface, --ph-conv-text, --ph-conv-muted, --ph-conv-border,
--ph-conv-agent-bubble, --ph-conv-font, --ph-conv-radius, --ph-conv-launcher-shadow,
--ph-conv-window-shadow). Rules in your own stylesheet that set them on
#ph-conversations-widget-container take precedence over the theme.
Extends
ConversationsThemeColors
Properties
ConversationsThemeColors
Colors of the conversations widget. Any CSS color value is accepted.
Extended by
ConversationsTheme
Properties
ConversationsTraits
User traits to send with messages
Indexable
[
key:string]:string|number|boolean|null|undefined
Properties
ConversationsUnavailableReason
ConversationsUnavailableReason =
"disabled_by_config"|"consent_opted_out"|"disabled_for_toolbar"|"remote_config_pending"|"remote_config_failed"|"disabled_in_project"|"missing_token"|"extensions_unavailable"|"load_failed"|"initializing"|"not_loaded"
ConversationsWidgetState
ConversationsWidgetState =
"open"|"closed"
Visual state of the conversations widget
DeadClickCandidate
DeadClicksAutoCaptureConfig
DeadClicksAutoCaptureConfig =
object&Pick<AutocaptureConfig,"element_attribute_ignorelist">
Type Declaration
| Name | Type | Description |
|---|---|---|
__onCapture()? | (click, properties) => void | Allows setting behavior for when a dead click is captured. For e.g. to support capture to heatmaps If not provided the default behavior is to auto-capture dead click events Only intended to be provided by our own SDK |
capture_clicks_with_modifier_keys? | boolean | By default, clicks with modifier keys (ctrl, shift, alt, meta/cmd) held down are not considered dead clicks, since these typically indicate intentional actions like "open in new tab". Set this to true to capture dead clicks even when modifier keys are held. Default false |
capture_dead_swipes? | boolean | Determines whether PostHog should also detect "dead swipes" — touch swipe gestures (typically on mobile/touch devices) that produce no observable screen change (no scroll, mutation or selection change while the gesture is in progress, and no scroll, mutation, selection or visibility change afterwards). These usually indicate a failed navigation, e.g. swiping to go back or to move a carousel with nothing happening. Dead swipes are captured as $dead_swipe events. This only applies to the dead-click autocapture path, not the heatmaps path. Swipes over surfaces whose response cannot be observed — canvas, video and other media/plugin elements under the finger — are never captured, and capture is limited per page load (see max_dead_swipes_per_page_load). Default true |
css_selector_ignorelist? | string[] | List of CSS selectors to ignore dead clicks on e.g. ['.my-download-link'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > a > svg and ignore list config ['[download]'] we will ignore the dead click if the click-target or its parents has any download attribute Nothing is ignored when there's an empty ignorelist, e.g. [] If no ignorelist is set, we default to ignoring .ph-no-deadclick and .ph-no-capture A custom ignorelist fully replaces the default — include .ph-no-capture if you want it to suppress dead-click capture as well |
max_dead_swipes_per_page_load? | number | The maximum number of dead swipes captured per page load. Swipe gestures are plentiful on touch devices, so a page whose responses the detector cannot see is capped rather than allowed to flood events. Only used when capture_dead_swipes is enabled. Default 10 |
mutation_threshold_ms? | number | We'll not consider a click to be a dead click, if it's followed by a mutation within mutation_threshold_ms milliseconds Default 2500 |
scroll_threshold_ms? | number | We'll not consider a click to be a dead click, if it's followed by a scroll within scroll_threshold_ms milliseconds Default 100 |
selection_change_threshold_ms? | number | We'll not consider a click to be a dead click if it selects/unselects text or moves a caret in editable content during its mouse gesture, regardless of how long the button is held. Selection changes outside a matching gesture suppress the click when they occur within selection_change_threshold_ms milliseconds immediately before or after it. When a closed shadow root hides whether a caret belongs to editable content, only the timed window applies. A value of 0 disables selection-based suppression. Default 100 |
swipe_threshold_px? | number | The minimum straight-line distance in CSS pixels between where a touch gesture starts and ends for it to be considered a swipe (rather than a tap). Only used when capture_dead_swipes is enabled. Default 30 |
DisplaySurveyInlineOptions
DisplaySurveyOptionsBase
Properties
DisplaySurveyOptions
DisplaySurveyOptions =
DisplaySurveyPopoverOptions|DisplaySurveyInlineOptions
Options for posthog.displaySurvey().
DisplaySurveyOptionsBase
DisplaySurveyPopoverOptionsDisplaySurveyInlineOptions
Properties
DisplaySurveyPopoverOptions
Options for displaying a survey as a popover.
Extends
DisplaySurveyOptionsBase
Properties
DisplaySurveyType
DisplaySurveyType = typeof
DisplaySurveyType[keyof typeofDisplaySurveyType]
Disposable
A resource handle with idempotent, best-effort cleanup.
Methods
dispose()
dispose():
void
Release resources owned by this object.
Returns
void
DomAutocaptureEvents
DomAutocaptureEvents =
"click"|"change"|"submit"
EarlyAccessFeature
A feature that isn't publicly available yet.
Properties
EarlyAccessFeatureCallback
EarlyAccessFeatureCallback = (
earlyAccessFeatures) =>void
Parameters
| Parameter | Type |
|---|---|
earlyAccessFeatures | EarlyAccessFeature[] |
Returns
void
EarlyAccessFeatureResponse
EarlyAccessFeatureStage
EarlyAccessFeatureStage =
"concept"|"alpha"|"beta"|"general-availability"
EndBranching
ErrorEventArgs
ErrorEventArgs = [
event:string|Event,source?:string|undefined,lineno?:number|undefined,colno?:number|undefined,error?:Error|undefined]
ErrorTrackingOptions
Shared configuration for the error tracking burst-protection rate limiter.
Burst protection is scoped per exception type — the limiter is keyed by exception type, so
each distinct $exception type gets its own token bucket and there is no aggregate cap across
all types. It applies only to autocaptured exceptions; manual captureException calls are
never rate limited. These options let customers with high-cardinality exception types tune the
per-type allowance, and are shared between the browser and Node SDKs.
Extends
ExceptionRateLimiterConfig
Properties
ErrorTrackingSuppressionRule
ErrorTrackingSuppressionRuleValue
EvaluationReason
EvaluationReason =
object
Properties
EventHandler
EventHandler = (
event) =>boolean|void
Parameters
| Parameter | Type |
|---|---|
event | Event |
Returns
boolean | void
EventName
EventName =
KnownUnsafeEditableEvent|KnownEventName|string&object
ExceptionAutoCaptureConfig
ExceptionAutoCaptureConfig =
object
Properties
ExceptionRateLimiterConfig
Shared configuration for the error tracking burst-protection rate limiter.
Burst protection is scoped per exception type — the limiter is keyed by exception type, so
each distinct $exception type gets its own token bucket and there is no aggregate cap across
all types. It applies only to autocaptured exceptions; manual captureException calls are
never rate limited. These options let customers with high-cardinality exception types tune the
per-type allowance, and are shared between the browser and Node SDKs.
Extended by
ErrorTrackingOptions
Properties
ExceptionStepsConfig
ExceptionStepsConfig =
object
Controls buffering and payload limits for exception steps added via addExceptionStep.
NOTE: This type is also defined in @posthog/core (exception-steps.ts). Keep both in sync.
Properties
Extension
A shared browser extension. The client calls setup(client) once to start it
and optional dispose() once for final best-effort resource cleanup.
Everything an extension consumes flows through its host, Client by default.
setup may be async so an extension can read async KV state or remote config
before it is ready. Async extensions must guard work after each await so
cleanup cannot be followed by late listener, timer, or patch installation.
The disposables an extension creates in setup are its own to release.
An extension that exposes app-facing controls extends Extension with named
methods that share its state, e.g.:
Type Parameters
Properties
Methods
dispose()?
optionaldispose():void
Release final resources synchronously. Feature-level start/stop remains extension-owned.
Returns
void
flush()?
optionalflush(reason?):Promise<void>
Flush buffered work. Shutdown awaits this within the host's timeout before disposal.
Parameters
| Parameter | Type |
|---|---|
reason? | "shutdown" | "flush" |
Returns
Promise<void>
setup()
setup(
client):void|Promise<void>
Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.
Parameters
| Parameter | Type |
|---|---|
client | Host |
Returns
void | Promise<void>
ExtensionToken
ExtensionToken<
T> =string&object
A typed stable name for resolving an installed extension.
Tokens are plain strings at runtime, so independently compiled scripts can
share them without a registry or object-identity contract. The generic brand
lets Client.getExtension infer the extension type. A token's string
value must match an installed extension's stable name or one of its bindings keys.
Type Parameters
Type Declaration
| Name | Type |
|---|---|
[extensionTokenType] | T |
ExternalIntegrationKind
ExternalIntegrationKind =
"intercom"|"crispChat"
FeatureFlagDetail
FeatureFlagDetail =
object
Properties
FeatureFlagMetadata
FeatureFlagMetadata =
object
Properties
FeatureFlagOptions
FeatureFlagOptions =
object
Options for feature flag lookup methods (getFeatureFlag, isFeatureEnabled, getFeatureFlagResult).
Properties
FeatureFlagOverrideOptions
FeatureFlagOverrideOptions =
object
Properties
FeatureFlagOverrides
FeatureFlagOverrides =
object
Index Signature
[flagName: string]: string | boolean
FeatureFlagPayloadOverrides
FeatureFlagPayloadOverrides =
object
Index Signature
[flagName: string]: JsonType
FeatureFlagResult
FeatureFlagResult =
object
Result of evaluating a feature flag, including both the flag value and its payload.
Properties
FeatureFlagsCallback
FeatureFlagsCallback = (
flags,variants,context?) =>void
Parameters
| Parameter | Type |
|---|---|
flags | string[] |
variants | Record<string, string | boolean> |
context? | { errorsLoading?: boolean; } |
context.errorsLoading? | boolean |
Returns
void
FeatureFlagsConfig
FeatureFlagsConfigSource
get()
get():
Readonly<FeatureFlagsConfig>
Returns
Readonly<FeatureFlagsConfig>
FeatureFlagsReloadResult
FlagsResponse
Flags returns feature flags and their payloads
Extends
RemoteConfig
Properties
FlagVariant
FlagVariant =
object
Properties
GetMessagesResponse
Response from fetching messages
Properties
GetTicketsOptions
Options for fetching tickets list
Properties
GetTicketsResponse
Response from fetching tickets list
Properties
Headers
Headers =
Record<string,string>
Request-related types
HeatmapConfig
HistogramOptions
Options accepted by posthog.metrics.histogram.
Extends
CaptureMetricOptions
Properties
InferredSelector
InitiatorType
InitiatorType =
"audio"|"beacon"|"body"|"css"|"early-hint"|"embed"|"fetch"|"frame"|"iframe"|"icon"|"image"|"img"|"input"|"link"|"navigation"|"object"|"ping"|"script"|"track"|"video"|"xmlhttprequest"
IsFeatureEnabledOptions
IsFeatureEnabledOptions =
FeatureFlagOptions&object
Options for isFeatureEnabled.
Type Declaration
| Name | Type | Description |
|---|---|---|
defaultValue? | boolean | Value to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists. |
JSONContent
JsonRecord
JsonRecord =
object
Index Signature
[key: string]: JsonType
JsonType
JsonType =
string|number|boolean|null|undefined|JsonRecord|JsonType[]
KeyValueStore
Key-value store for small extension state. A host may initialize an asynchronous
backend before exposing synchronous operations over its in-memory buffer. Writes
must update that buffer before returning; ordered durable flushing remains the
host's responsibility. Reads treat undefined values as absent.
Keys map verbatim to the host client's shared persistence. In browser-v1, unknown keys are normally included as event properties, collisions overwrite host/core state, and reset clears them. Every SDK-owned key therefore needs an explicit event/hidden/derived exposure policy in each host, and sensitive data must not be stored unless its transmission is approved. Values must be JSON-serializable.
Methods
get()
Call Signature
get<
T>(keys):Partial<T>
Read several initialized values in one operation. Missing keys are omitted.
Type Parameters
Parameters
| Parameter | Type |
|---|---|
keys | readonly (keyof T & string)[] |
Returns
Partial<T>
Call Signature
get<
T>(key):T|undefined
Read one initialized value by key, returning undefined when it is missing.
Type Parameters
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
T | undefined
initialize()
initialize():
void|Promise<void>
Populate the in-memory buffer from durable storage. Calls are idempotent.
Returns
void | Promise<void>
remove()
remove(
keyOrKeys):void
Remove one or several values from the initialized buffer in one operation.
Parameters
| Parameter | Type |
|---|---|
keyOrKeys | string | readonly string[] |
Returns
void
set()
Call Signature
set(
key,value):void
Immediately update the initialized buffer. null is durable; undefined is
accepted for compatibility but treated as absent by reads and is not portable.
Parameters
| Parameter | Type |
|---|---|
key | string |
value | unknown |
Returns
void
Call Signature
set(
values):void
Coherently update several related values in the initialized buffer.
Parameters
| Parameter | Type |
|---|---|
values | Record<string, unknown> |
Returns
void
KnownEventName
KnownEventName =
"$heatmaps_data"|"$opt_in"|"$exception"|"$$heatmap"|"$web_vitals"|"$dead_click"|"$dead_swipe"|"$autocapture"|"$copy_autocapture"|"$rageclick"
These are known events PostHog events that can be processed by the beforeCapture function
That means PostHog functionality does not rely on receiving 100% of these for calculations
So, it is safe to sample them to reduce the volume of events sent to PostHog
KnownUnsafeEditableEvent
KnownUnsafeEditableEvent = typeof
knownUnsafeEditableEvent[number]
These events can be processed by the beforeCapture function
but can cause unexpected confusion in data.
Some features of PostHog rely on receiving 100% of these events
KnownUnsafeEditableEvent
KnownUnsafeEditableEvent =
"$set"|"$pageview"|"$pageleave"|"$identify"|"$groupidentify"|"$create_alias"|"$feature_flag_called"
Known events that can be safely edited in beforeCapture without breaking PostHog functionality
LinkSurveyQuestion
SurveyQuestionBase
Properties
Listener
Listener<
T> = (handler) =>Disposable
Call it with a handler to start listening; dispose the returned
Disposable to stop. There is one Listener per event type, so every
event carries its own payload type. The handler is called synchronously, and
stateful listeners may replay their current value during registration when
documented. The returned disposable unregisters it from future payloads.
Type Parameters
Parameters
| Parameter | Type |
|---|---|
handler | (payload) => void |
Returns
Disposable
LogAttributes
LogAttributes =
Record<string,LogAttributeValue>
LogAttributeValue
LogAttributeValue =
string|number|boolean|null|undefined|unknown[] |Record<string,unknown>
LogCaptureOptions
Options for the captureLog API and posthog.logger convenience methods.
Extended by
LogsConfigBrowserLogsConfig
Properties
Logger
Per-level convenience logger. Each method captures a structured log record
at the corresponding severity, equivalent to
posthog.captureLog({ body, level, attributes }).
Example
Methods
debug()
debug(
body,attributes?):void
Debug-level detail. Verbose, only useful while diagnosing.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
error()
error(
body,attributes?):void
Error. Operation failed; the app may continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
fatal()
fatal(
body,attributes?):void
Fatal. Operation failed; the app likely cannot continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
info()
info(
body,attributes?):void
Informational. Normal app events worth recording.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
trace()
trace(
body,attributes?):void
Lowest severity. Trace-level diagnostic detail.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
warn()
warn(
body,attributes?):void
Warning. Something unexpected but non-fatal.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
Returns
void
Logger
Logger =
object
Properties
LogsConfig
Logs configuration options
Extends
LogCaptureOptions
Properties
LogSdkContext
SDK-internal context the host SDK passes to buildOtlpLogRecord at capture
time. Each SDK populates the fields that apply to it: browser fills
currentUrl, mobile fills screenName / appState. Missing fields are
omitted from the OTLP record (no stray attributes).
Internal to @posthog/core — customers don't see this in autocomplete.
Properties
LogSeverityLevel
LogSeverityLevel =
"trace"|"debug"|"info"|"warn"|"error"|"fatal"
Log capture types
MarkAsReadResponse
Response from marking messages as read
Properties
MaskInputOptions
Mask input options for session recording
Properties
Message
A message in a conversation
Properties
MessageAuthorType
MessageAuthorType =
"customer"|"AI"|"human"
Author types for messages in a conversation
MetricAttributes
MetricAttributes =
Record<string,MetricAttributeValue>
MetricAttributeValue
MetricAttributeValue =
string|number|boolean
Metric attribute values are restricted to scalars. Every distinct attribute-value combination creates a new metric series, so high-cardinality values (user IDs, request IDs, URLs) must not be used as attributes — put those on logs or events instead.
MetricSample
A captured metric as seen by beforeSend, before aggregation. Mutating
name, value, unit, attributes, or bounds changes what gets aggregated;
returning null drops the sample.
Properties
MetricsConfig
Options for the posthog.metrics API (count, gauge, histogram).
Shared by every SDK; browser-only options live in BrowserMetricsConfig.
Extended by
BrowserMetricsConfig
Properties
MetricType
MetricType =
"count"|"gauge"|"histogram"
MultipleSurveyQuestion
SurveyQuestionBase
Properties
NetworkMetricsConfig
Options for automatic HTTP and HTTPS fetch and XMLHttpRequest duration
metrics. Recording never changes the request or its settlement. Fetch returns
a derived promise so rejected requests remain observable to the caller.
Properties
NetworkMetricsRequest
The request a network metric describes.
Properties
NetworkMetricsResponse
How a network request ended.
Properties
NetworkRecordOptions
NetworkRecordOptions =
object
Properties
NetworkRequest
NetworkRequest =
object
Deprecated
- use CapturedNetworkRequest instead
Properties
NextOptions
NextOptions =
object
Properties
NextOptions
NextOptions =
object
Properties
NextQuestionBranching
OtlpAnyValue
OtlpExemplar
A sampled measurement linked to the span it was recorded in. IDs are lowercase hex.
Properties
OtlpHistogramDataPoint
OtlpKeyValue
OtlpLogRecord
OtlpLogsPayload
OtlpMetric
OtlpMetricsPayload
OtlpNumberDataPoint
OtlpSeverityEntry
OtlpSeverityText
OtlpSeverityText =
"TRACE"|"DEBUG"|"INFO"|"WARN"|"ERROR"|"FATAL"
OverrideConfig
OverrideConfig =
object
Properties
OverrideFeatureFlagsOptions
OverrideFeatureFlagsOptions =
boolean|string[] |FeatureFlagOverrides|FeatureFlagOverrideOptions
Options for overriding feature flags on the client-side.
Can be:
falseto clear all overridesstring[]to enable a list of flagsFeatureFlagOverridesto set variants directlyFeatureFlagOverrideOptionsfor granular control over flags and payloads
PerformanceCaptureConfig
PersistentStore
PostHog
The PostHog instance interface.
This can be used to type window.posthog when loading PostHog via a <script> tag.
Example
Properties
Methods
addExceptionStep()
addExceptionStep(
message,properties?):void
Adds a breadcrumb-like step that will be attached to the next captured exception as $exception_steps.
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | The step message |
properties? | Properties | Additional context for this step |
Returns
void
alias()
alias(
alias,original?):number|void|CaptureResult
Create an alias for the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
alias | string | The alias to create |
original? | string | The original distinct ID (defaults to current distinct ID) |
Returns
number | void | CaptureResult
canRenderSurvey()
canRenderSurvey(
surveyId):SurveyRenderReason|null
Check if a survey can be rendered.
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The survey ID |
Returns
SurveyRenderReason | null
The render reason or null if can't render
canRenderSurveyAsync()
canRenderSurveyAsync(
surveyId,forceReload?):Promise<SurveyRenderReason>
Check if a survey can be rendered (async version).
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The survey ID |
forceReload? | boolean | Whether to force a reload from the server |
Returns
Promise<SurveyRenderReason>
A promise that resolves to the render reason
capture()
capture(
event_name,properties?,options?):CaptureResult|undefined
Capture an event.
Parameters
| Parameter | Type | Description |
|---|---|---|
event_name | string | The name of the event |
properties? | Properties | null | A set of properties to include with the event |
options? | CaptureOptions | Additional options for the capture |
Returns
CaptureResult | undefined
The capture result
captureException()
captureException(
error,additionalProperties?):CaptureResult|undefined
Capture an exception.
Parameters
| Parameter | Type | Description |
|---|---|---|
error | unknown | The error to capture |
additionalProperties? | Properties | Additional properties to include with the event |
Returns
CaptureResult | undefined
The capture result
captureLog()
captureLog(
options):void
Capture a log entry and send it to the PostHog logs endpoint.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CaptureLogOptions | The log entry options (body, level, attributes, etc.) |
Returns
void
captureTraceFeedback()
captureTraceFeedback(
traceId,userFeedback):void
Capture written user feedback for a LLM trace.
Parameters
| Parameter | Type | Description |
|---|---|---|
traceId | string | number | The trace ID to capture feedback for |
userFeedback | string | The feedback to capture |
Returns
void
captureTraceMetric()
captureTraceMetric(
traceId,metricName,metricValue):void
Capture a metric for a LLM trace.
Parameters
| Parameter | Type | Description |
|---|---|---|
traceId | string | number | The trace ID to capture the metric for |
metricName | string | The name of the metric to capture |
metricValue | string | number | boolean | The value of the metric to capture |
Returns
void
clear_opt_in_out_capturing()
clear_opt_in_out_capturing():
void
Clear the opt-in/out status.
Returns
void
clearIdentity()
clearIdentity():
void
Clear HMAC-based identity verification, reverting to anonymous mode.
Returns
void
createPersonProfile()
createPersonProfile():
void
Create a person profile for the current user.
Returns
void
debug()
debug(
debug?):void
Enable or disable debug mode.
Parameters
| Parameter | Type | Description |
|---|---|---|
debug? | boolean | Whether to enable debug mode (defaults to true) |
Returns
void
get_distinct_id()
get_distinct_id():
string
Get the current distinct ID.
Returns
string
The current distinct ID
get_explicit_consent_status()
get_explicit_consent_status():
"pending"|"granted"|"denied"
Get the explicit consent status.
Returns
"pending" | "granted" | "denied"
The consent status
get_property()
get_property(
property_name):any
Get a property value from persistence.
Parameters
| Parameter | Type | Description |
|---|---|---|
property_name | string | The property name |
Returns
any
The property value
get_session_id()
get_session_id():
string
Get the current session ID.
Returns
string
The current session ID
get_session_replay_url()
get_session_replay_url(
options?):string
Get the URL to view the current session recording.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | { timestampLookBack?: number; withTimestamp?: boolean; } | Options for the URL |
options.timestampLookBack? | number | How many seconds to look back for the timestamp |
options.withTimestamp? | boolean | Whether to include the timestamp in the URL |
Returns
string
The session replay URL
getActiveMatchingSurveys()
getActiveMatchingSurveys(
callback,forceReload?):void
Get active surveys that match the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (surveys) => void | Callback to receive the surveys |
forceReload? | boolean | Whether to force a reload from the server |
Returns
void
getEarlyAccessFeatures()
getEarlyAccessFeatures(
callback,forceReload?,stages?):void
Get the list of early access features.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | EarlyAccessFeatureCallback | Callback to receive the features |
forceReload? | boolean | Whether to force a reload from the server |
stages? | EarlyAccessFeatureStage[] | The stages of the early access features to load |
Returns
void
getFeatureFlag()
getFeatureFlag(
key,options?):string|boolean|undefined
Get the value of a feature flag.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options? | FeatureFlagOptions | Options for the feature flag lookup |
Returns
string | boolean | undefined
The feature flag value (boolean for simple flags, string for multivariate)
getFeatureFlagPayload()
getFeatureFlagPayload(
key):JsonType
Get the payload of a feature flag.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
Returns
JsonType
The feature flag payload
Deprecated
Use getFeatureFlagResult() instead which properly tracks the feature flag call.
getFeatureFlagResult()
getFeatureFlagResult(
key,options?):FeatureFlagResult|undefined
Get a feature flag evaluation result including both the flag value and payload.
By default, this method emits the $feature_flag_called event.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options? | FeatureFlagOptions | Options for the feature flag lookup |
Returns
FeatureFlagResult | undefined
The feature flag result including key, enabled, variant, and payload, or undefined if not loaded
getGroups()
getGroups():
Record<string,any>
Get the current groups.
Returns
Record<string, any>
A record of group types to group keys
getPageViewId()
getPageViewId():
string|undefined
Get the current page view ID.
Returns
string | undefined
The current page view ID
getSessionProperty()
getSessionProperty(
property_name):any
Get a session property value.
Parameters
| Parameter | Type | Description |
|---|---|---|
property_name | string | The property name |
Returns
any
The property value
getSurveys()
getSurveys(
callback,forceReload?):void
Get the list of surveys.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (surveys) => void | Callback to receive the surveys |
forceReload? | boolean | Whether to force a reload from the server |
Returns
void
group()
group(
groupType,groupKey,groupPropertiesToSet?):void
Associate the user with a group.
Parameters
| Parameter | Type | Description |
|---|---|---|
groupType | string | The type of group (e.g., 'company', 'project') |
groupKey | string | The unique identifier for the group |
groupPropertiesToSet? | Properties | Properties to set on the group |
Returns
void
has_opted_in_capturing()
has_opted_in_capturing():
boolean
Check if the user has opted in to capturing.
Returns
boolean
Whether the user has opted in
has_opted_out_capturing()
has_opted_out_capturing():
boolean
Check if the user has opted out of capturing.
Returns
boolean
Whether the user has opted out
identify()
identify(
new_distinct_id,userPropertiesToSet?,userPropertiesToSetOnce?):void
Identify a user with a distinct ID and optionally set person properties.
Parameters
| Parameter | Type | Description |
|---|---|---|
new_distinct_id | string | A non-empty distinct ID for the user |
userPropertiesToSet? | Properties | Properties to set on the user (using $set) |
userPropertiesToSetOnce? | Properties | Properties to set once on the user (using $set_once) |
Returns
void
init()
init(
token,config?,name?):PostHog
Initializes a new instance of the PostHog capturing object.
Parameters
| Parameter | Type | Description |
|---|---|---|
token | string | Your PostHog API token |
config? | Partial<PostHogConfig> | A dictionary of config options to override |
name? | string | The name for the new posthog instance that you want created |
Returns
PostHog
The newly initialized PostHog instance
isFeatureEnabled()
Call Signature
isFeatureEnabled(
key,options):boolean
Check if a feature flag is enabled.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature flag key |
options | FeatureFlagOptions & object & object | Options for the feature flag lookup |
Returns
boolean
Whether the feature flag is enabled
Call Signature
isFeatureEnabled(
key,options?):boolean|undefined
Parameters
| Parameter | Type |
|---|---|
key | string |
options? | IsFeatureEnabledOptions |
Returns
boolean | undefined
loadToolbar()
loadToolbar(
params):boolean
Load the PostHog toolbar.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ToolbarParams | Toolbar parameters |
Returns
boolean
Whether the toolbar was loaded
on()
on(
event,cb): () =>void
Register an event listener.
Parameters
| Parameter | Type | Description |
|---|---|---|
event | "eventCaptured" | "featureFlagsReloading" | The event name to listen for |
cb | (...args) => void | The callback to call |
Returns
A function to unsubscribe
() => void
onActiveMatchingSurveysChanged()
onActiveMatchingSurveysChanged(
callback): () =>void
Observe the initial matching surveys and updates after event/action and survey lifecycle changes, definitions refreshes, captured pageviews, feature-flag updates, and reset. URL changes require a captured pageview; arbitrary DOM mutations and elapsed time are not observed. Unchanged results are suppressed. Recoverable load errors are reported through the optional context without ending the subscription.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (surveys, context?) => void | Callback to receive the active matching surveys |
Returns
A function to unsubscribe
() => void
onFeatureFlags()
onFeatureFlags(
callback): () =>void
Register a callback to be called when feature flags are loaded.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | FeatureFlagsCallback | The callback to call |
Returns
A function to unsubscribe
() => void
onSessionId()
onSessionId(
callback): () =>void
Register a callback to be called when the session ID changes.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | SessionIdChangedCallback | The callback to call |
Returns
A function to unsubscribe
() => void
opt_in_capturing()
opt_in_capturing():
void
Opt the user into capturing.
Returns
void
opt_out_capturing()
opt_out_capturing():
void
Opt the user out of capturing.
Returns
void
register()
register(
properties,days?):void
Register properties to be sent with every event.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | The properties to register |
days? | number | Number of days to persist the properties |
Returns
void
register_for_session()
register_for_session(
properties):void
Register properties for the current session only.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | The properties to register |
Returns
void
register_once()
register_once(
properties,default_value?,days?):void
Register properties to be sent with every event, but only if they haven't been set before.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | The properties to register |
default_value? | any | Default value for the property |
days? | number | Number of days to persist the properties |
Returns
void
reloadFeatureFlags()
reloadFeatureFlags():
void
Reload feature flags from the server.
Returns
void
renderSurvey()
renderSurvey(
surveyId,selector):void
Render a survey in a specific container.
Parameters
| Parameter | Type | Description |
|---|---|---|
surveyId | string | The survey ID |
selector | string | CSS selector for the container |
Returns
void
reset()
reset(
options?):void
Reset the user's identity and start a new session.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | boolean | ResetOptions | Boolean to reset the device ID (legacy), or reset options including bootstrap values. |
Returns
void
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.
resetGroupPropertiesForFlags()
resetGroupPropertiesForFlags(
group_type?):void
Reset group properties used for feature flag evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
group_type? | string | Optional group type to reset (resets all if not provided) |
Returns
void
resetGroups()
resetGroups():
void
Reset all groups for the current user.
Returns
void
resetPersonPropertiesForFlags()
resetPersonPropertiesForFlags(
reloadFeatureFlags?):void
Reset person properties used for feature flag evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
reloadFeatureFlags? | boolean | Whether to reload feature flags after resetting |
Returns
void
sessionRecordingStarted()
sessionRecordingStarted():
boolean
Check if session recording has started.
Returns
boolean
Whether session recording has started
set_config()
set_config(
config):void
Update the configuration.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | Partial<PostHogConfig> | The configuration to merge |
Returns
void
setGroupPropertiesForFlags()
setGroupPropertiesForFlags(
properties,reloadFeatureFlags?):void
Set group properties to be used for feature flag evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | {[type: string]: Properties; } | The properties to set (keyed by group type) |
reloadFeatureFlags? | boolean | Whether to reload feature flags after setting |
Returns
void
setIdentity()
setIdentity(
distinctId,hash):void
Set HMAC-based identity verification.
Parameters
| Parameter | Type | Description |
|---|---|---|
distinctId | string | The verified user distinct_id |
hash | string | HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings |
Returns
void
setInternalOrTestUser()
setInternalOrTestUser():
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.
Returns
void
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.
Example
setPersonProperties()
setPersonProperties(
userPropertiesToSet?,userPropertiesToSetOnce?):void
Set properties on the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
userPropertiesToSet? | Properties | Properties to set on the user (using $set) |
userPropertiesToSetOnce? | Properties | Properties to set once on the user (using $set_once) |
Returns
void
setPersonPropertiesForFlags()
setPersonPropertiesForFlags(
properties,reloadFeatureFlags?):void
Set person properties to be used for feature flag evaluation.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | The properties to set |
reloadFeatureFlags? | boolean | Whether to reload feature flags after setting |
Returns
void
shutdown()
shutdown(
shutdownTimeoutMs?):Promise<void>
Flush any queued events and gracefully tear down the SDK.
Parameters
| Parameter | Type | Description |
|---|---|---|
shutdownTimeoutMs? | number | Accepted for parity with the Node.js SDK; unused in the browser. |
Returns
Promise<void>
Resolves once teardown is complete.
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.
startExceptionAutocapture()
startExceptionAutocapture(
config?):void
Start automatic exception capture.
Parameters
| Parameter | Type | Description |
|---|---|---|
config? | ExceptionAutoCaptureConfig | Optional configuration for exception autocapture |
Returns
void
startSessionRecording()
startSessionRecording(
override?):void
Start session recording (if not already started).
Parameters
| Parameter | Type | Description |
|---|---|---|
override? | true | { event_trigger?: true; linked_flag?: boolean; sampling?: boolean; url_trigger?: true; } | Options to override default behavior, or true to override all controls |
Returns
void
stopExceptionAutocapture()
stopExceptionAutocapture():
void
Stop automatic exception capture.
Returns
void
stopSessionRecording()
stopSessionRecording():
void
Stop session recording.
Returns
void
unregister()
unregister(
property):void
Unregister a property so it is no longer sent with events.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The property name to unregister |
Returns
void
unregister_for_session()
unregister_for_session(
property):void
Unregister a session property.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The property name to unregister |
Returns
void
unsetPersonProperties()
unsetPersonProperties(
propertyNames):void
Remove properties from the current user.
Parameters
| Parameter | Type | Description |
|---|---|---|
propertyNames | string | string[] | The name (or names) of the person properties to remove (using $unset) |
Returns
void
updateEarlyAccessFeatureEnrollment()
updateEarlyAccessFeatureEnrollment(
key,isEnrolled,stage?):void
Update enrollment in an early access feature.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The feature key |
isEnrolled | boolean | Whether the user is enrolled |
stage? | EarlyAccessFeatureStage | The stage of the feature |
Returns
void
updateFlags()
updateFlags(
flags,payloads?,options?):void
Manually update feature flag values without making a network request.
Parameters
| Parameter | Type | Description |
|---|---|---|
flags | Record<string, boolean | string> | An object mapping flag keys to their values (boolean or string variant) |
payloads? | Record<string, JsonType> | Optional object mapping flag keys to their JSON payloads |
options? | { merge?: boolean; } | Optional settings. Use { merge: true } to merge with existing flags instead of replacing. |
options.merge? | boolean | - |
Returns
void
PostHogConfig
PostHogConfig =
Omit<PostHogConfig,"loaded"> &object
Type Declaration
| Name | Type | Description |
|---|---|---|
disableDeviceModel? | boolean | Disables capturing the $device_model super-property. When capturing is enabled (the default), PostHog resolves the hardware model once during init via navigator.userAgentData.getHighEntropyValues(['model']) and registers it as the raw OEM code (e.g. Pixel 7). This is Chromium-only and only meaningful on Android — it resolves to undefined on Safari/Firefox and to an empty string on desktop, in which cases nothing is registered. This opt-out is offered because getHighEntropyValues is still experimental and Chromium-only (not yet a cross-browser standard); set it to true to skip the call entirely. Default false |
loaded() | (posthog) => void | - |
PostHogConfig
Configuration options for the PostHog JavaScript SDK.
See
https://posthog.com/docs/libraries/js#config
Properties
| Property | Type | Description |
|---|---|---|
__add_tracing_headers? | string[] | Deprecated Use tracing_headers instead. Kept for backwards compatibility. |
__preview_capture_bot_pageviews? | boolean | PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION Enables collection of bot traffic as $bot_pageview events with detailed bot detection properties instead of dropping them entirely. Use it alongside opt_out_useragent_filter |
__preview_cookie_wins_on_conflict | boolean | Deprecated Use cookieWinsOnConflict instead. |
__preview_deferred_init_extensions | boolean | Experimental EXPERIMENTAL: Defers initialization of non-critical extensions (autocapture, session recording, etc.) to the next event loop tick using setTimeout. This reduces main thread blocking during SDK initialization for better page load performance, while keeping critical functionality (persistence, sessions, capture) available immediately. When enabled: - Persistence, sessions, and basic capture work immediately - Extensions (autocapture, recording, heatmaps, etc.) start after yielding back to the browser Default false (will be true for defaults >= '2025-11-06' in the future) @experimental |
__preview_disable_beacon? | boolean | Deprecated Use disable_beacon instead. |
__preview_disable_xhr_credentials? | boolean | Deprecated This option is a no-op. The browser SDK no longer sets XMLHttpRequest.withCredentials. |
__preview_eager_load_replay? | boolean | Deprecated This option is a no-op. Session replay is lazy-loaded by default. |
__preview_external_dependency_versioned_paths? | string | boolean | Deprecated Use strict_script_versioning and asset_host instead. When set to true, this is equivalent to strict_script_versioning: true. When set to a string, this is equivalent to strict_script_versioning: true and asset_host set to that string. |
__preview_flags_v2? | boolean | Deprecated This option is a no-op. The browser SDK already uses the /flags/?v=2 endpoint. |
__preview_lazy_load_replay? | boolean | Deprecated - does nothing was present only for PostHog testing of replay lazy loading |
__preview_replay_sync_fetch? | boolean | Private preview: invoke recorded fetch requests synchronously to preserve application error stacks. Enabled by default in new cores; set to false to retain legacy fetch ordering. An old core without this option also retains legacy ordering when it loads a new recorder. Applied when the recorder installs its network observers, not a live remote kill switch. Default true |
_onCapture | (eventName, eventData) => void | Deprecated - use before_send instead |
addTracingHeaders? | string[] | Deprecated Use tracing_headers instead. Kept for backwards compatibility. |
advanced_disable_decide? | boolean | Deprecated Use advanced_disable_flags instead. This will be removed in a future major version. One of the very first things the PostHog library does when init() is called is make a request to the /decide endpoint on PostHog's backend. This endpoint contains information on how to run the PostHog library so events are properly received in the backend. This endpoint is required to run most features of the library. However, if you're not using any of the described features, you may wish to turn off the call completely to avoid an extra request and reduce resource usage on both the client and the server. Default false |
advanced_disable_feature_flags | boolean | Will keep /flags running, but without evaluating any feature flags. Useful for when you need to load the config data associated with the flags endpoint (e.g. /flags?v=2&config=true) without evaluating any feature flags. Most folks use this to save money on feature flag evaluation (by bootstrapping feature flags on the server side). This also stops surveys from displaying. PostHog creates an internal targeting flag for almost every survey, and every flag evaluates to false while flags are disabled. If you use surveys, set advanced_only_evaluate_survey_feature_flags instead, which evaluates survey flags only. Default false |
advanced_disable_feature_flags_on_first_load | boolean | Stops from firing feature flag requests on first page load. Only requests feature flags when user identity or properties are updated, or you manually request for flags to be loaded. Default false |
advanced_disable_flags? | boolean | One of the very first things the PostHog library does when init() is called is make a request to the /flags endpoint on PostHog's backend. This endpoint contains information on how to run the PostHog library so events are properly received in the backend, and it also contains feature flag evaluation information for the current user. This endpoint is required to run most features of this library. However, if you're not using any of the described features, you may wish to turn off the call completely to avoid an extra request and reduce resource usage on both the client and the server. WARNING: Disabling this will also prevent remote configuration from loading, which could mean features like web vitals, surveys, and other features configured in PostHog settings are disabled unless explicitly enabled via client-side config. When setting this to true, make sure to explicitly configure any features you want to use (e.g., capture_performance, autocapture, etc.) in your SDK's init config. Default false |
advanced_disable_toolbar_metrics | boolean | Determines whether PostHog should disable toolbar metrics. This is our internal instrumentation for our toolbar in your website. Default false |
advanced_enable_surveys | boolean | When this is enabled, surveys will always be initialized, regardless of the /flags response or remote config settings. This is useful if you want to use surveys but disable all other flag-dependent functionality. Used internally for displaying external surveys without making a /flags request. Default false |
advanced_feature_flags_dedup_per_session | boolean | When enabled, $feature_flag_called event deduplication is scoped to the current session. By default, the SDK deduplicates $feature_flag_called events globally and only re-emits them when identify (with a new distinct ID) or reset is called. This can be problematic for experiments: if a flag is checked before an experiment starts, the event is cached and won't fire again for that user until identify/reset, meaning the experiment never sees the event. When this option is true, the deduplication cache is keyed on the session ID, so each new session will re-emit $feature_flag_called for every flag that is checked. Default false |
advanced_only_evaluate_survey_feature_flags | boolean | Determines whether PostHog should only evaluate feature flags for surveys. Useful for when you want to use this library to evaluate feature flags for surveys only but you have additional feature flags that you evaluate on the server side. Default false |
api_host | string | URL of your PostHog instance. Default 'https://us.i.posthog.com' |
api_method? | string | Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons |
api_transport? | "XHR" | "fetch" | The transport method to use for API requests. Default 'fetch' |
asset_host | string | null | Optional host override for static assets loaded by PostHog, such as recorder.js, surveys.js, or toolbar.js. Only applies to /static/* asset paths; dynamic assets like remote config continue to use the regular asset host derived from api_host. Default null |
autocapture | boolean | AutocaptureConfig | Determines whether PostHog should autocapture events. This setting does not affect capturing pageview events (see capture_pageview). by default autocapture is ignored on elements that match a ph-no-capture css class on the element or a parent Default true |
before_send? | BeforeSendFn | BeforeSendFn[] | This function or array of functions - if provided - are called immediately before sending data to the server. It allows you to edit data before it is sent, or choose not to send it all. if provided as an array the functions are called in the order they are provided any one function returning null means the event will not be sent |
bootstrap | BootstrapConfig | An object containing the distinctID, isIdentifiedID, and featureFlags keys, where distinctID is a string, and featureFlags is an object of key-value pairs. Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag. You can, therefore, fetch the feature flags in your server and pre-fill them here, allowing PostHog to know the feature flag values immediately. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones. Default {} |
capture_dead_clicks? | boolean | DeadClicksAutoCaptureConfig | Determines whether to capture dead clicks. by default dead clicks are ignored on elements that match a ph-no-capture or ph-no-deadclick css class on the element or a parent See Default undefined |
capture_exceptions? | boolean | ExceptionAutoCaptureConfig | Determines whether to capture exceptions. See Default undefined |
capture_heatmaps? | boolean | HeatmapConfig | Determines whether to capture heatmaps. See Default undefined |
capture_pageleave | boolean | "if_capture_pageview" | Determines whether PostHog should capture pageleave events. If set to true, it will capture pageleave events for all pages. If set to 'if_capture_pageview', it will only capture pageleave events if capture_pageview is enabled. Default 'if_capture_pageview' |
capture_pageview | boolean | CapturePageviewOptions | "history_change" | Determines whether PostHog should capture pageview events automatically. Can be: - true: Capture the initial pageview - false: Don't capture any pageviews - 'history_change': Capture the initial pageview and pageviews when the pathname changes - An object: Capture the initial pageview and pageviews when any selected URL component changes With the slim bundle, history-based pageviews require AnalyticsExtensions.historyAutocapture from posthog-js/extensions in __extensionClasses. Without it, only the initial pageview is captured. Default true (or 'history_change' when defaults is '2025-05-24' or later) |
capture_performance? | boolean | PerformanceCaptureConfig | Determines whether to capture performance metrics. These include Network Timing for Session Replay and Web Vitals. The network_timing option is only used by the Session Replay feature. For more session recording settings, see the session_recording and enable_recording_console_log configuration option. When undefined, fallback to the remote configuration. If false, neither network timing nor web vitals will work. If an object, that will override the remote configuration. See Default undefined |
capture_webmcp? | boolean | WebMCPCaptureConfig | Captures WebMCP tool calls as $mcp_tool_call events. Set this option to true to capture intent and model metadata. Use an object to disable either field. PostHog wraps tools registered after the SDK initializes. Tool inputs and outputs are not captured. Metadata options are applied when each tool registers. Changing them does not update registered schemas; re-register the tool to apply the new options. Default false |
consent_persistence_name | string | null | Determines the key for the cookie / local storage used to store the information about whether users are opted in/out of capturing. When null, we used a key based on your token. Default null See ConsentManager._storageKey |
conversations? | ConversationsConfig | Conversations-specific configuration options, such as the support widget theme. Default undefined |
cookie_expiration | number | Determines the number of days to store cookies for. Default 365 |
cookie_name? | string | Deprecated - Use 'persistence_name' instead |
cookie_persisted_properties? | readonly string[] | List of custom property names that should be stored in cookies (in addition to the default ones) when using 'localStorage+cookie' persistence mode. This allows these properties to be shared across subdomains when cross_subdomain_cookie is enabled. Default [] |
cookieless_mode? | "always" | "on_reject" | Enables cookieless mode. In this mode, PostHog will not set any cookies, or use session or local storage. User identity is handled by generating a privacy-preserving hash on PostHog's servers. Web Vitals (capture_performance.web_vitals) are supported: metrics are sent without client session IDs; ingestion assigns $session_id when cookieless mode is enabled for the project. - 'always' - enable cookieless mode immediately on startup, use this if you do not intend to show a cookie banner - 'on_reject' - enable cookieless mode only if the user rejects cookies, use this if you want to show a cookie banner. If the user accepts cookies, cookieless mode will not be used, and PostHog will use cookies and local storage as usual. Note that you MUST enable cookieless mode in your PostHog project's settings, otherwise all your cookieless events will be ignored. We plan to remove this requirement in the future. |
cookieWinsOnConflict | boolean | In 'localStorage+cookie' persistence mode, prefer shared cookie values over per-origin localStorage when both stores carry the same key. The SDK also checks for cookie changes before captures and persistence writes so already-open sibling subdomains adopt identity changes made by identify() or reset(). When defaults is '2026-08-29' or later, this defaults to true. Default false |
cross_subdomain_cookie | boolean | Determines if cookie should be set on the top level domain (example.com). If PostHog-js is loaded on a subdomain (test.example.com), and cross_subdomain_cookie is set to false, it'll set the cookie on the subdomain only (test.example.com). NOTE: It will be set to false if we detect that the domain is a subdomain of a platform that is excluded from cross-subdomain cookie setting. The current list of excluded platforms is herokuapp.com, vercel.app, and netlify.app. See isCrossDomainCookie Default true |
custom_blocked_useragents | string[] | Used to extend the list of user agents that are blocked by default. See from './utils/blocked-uas' - Default list of blocked user agents. Default [] |
custom_campaign_params | string[] | Used to extend the list of campaign parameters that are saved by default. See from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc. Default [] |
custom_personal_data_properties | string[] | Custom list of personal data properties to mask. E.g. if you added email to this list, then any email property in the URL will be masked. https://www.example.com/login?email=john.doe%40example.com => https://www.example.com/login?email= Default [] See - Must be enabled for this to take effect. |
debug | boolean | Determines whether PostHog should be in debug mode. You can enable this to get more detailed logging. You can also enable this on your website by appending ?__posthog_debug=true at the end of your URL You can also call posthog.debug() in your code to enable debug mode Default false |
defaults | ConfigDefaults | Configuration defaults for breaking changes. When set to a specific date, enables new default behaviors that were introduced on that date. Set to 'latest' to always use the newest defaults in the loaded SDK version. Unlike a pinned date, 'latest' opts into future default changes when the SDK is upgraded, which may include breaking changes. Explicit configuration options still take precedence. Events report the resolved date in $config_defaults when using 'latest'. - 'latest': Use all default changes available in the loaded SDK version - 'unset': Use legacy default behaviors - '2025-05-24': Use updated default behaviors (e.g. capture_pageview defaults to 'history_change') - '2025-11-30': Defaults from '2025-05-24' plus additional changes (e.g. strict minimum duration for replay and rageclick content ignore list defaults to active) - '2026-01-30': Defaults from '2025-11-30' plus external_scripts_inject_target defaults to 'head' (avoids SSR hydration errors) - '2026-05-30': Defaults from '2026-01-30' plus persistence_save_debounce_ms defaults to 250, split_storage and detect_google_search_app default to true, and rageclick defaults also exclude stepper controls and text-selection surfaces - '2026-06-25': Defaults from '2026-05-30' plus session_recording.streamNetworkBody defaults to true (streams network bodies to enforce the payload size limit) - '2026-08-29': Defaults from '2026-06-25' plus cookieWinsOnConflict defaults to true (the shared cross-subdomain cookie wins over stale per-origin localStorage) - '2026-08-30': Defaults from '2026-08-29' plus session_recording.captureJsonLd defaults to true Default 'unset' |
detect_google_search_app? | boolean | Detect the Google Search App (GSA) as its own $browser value instead of the underlying webview it embeds — Mobile Safari on iOS, Chrome on Android. Detection keys off the GSA/ marker present in the UA on every platform. Off by default for backwards-compatibility: enabling it reattributes existing GSA traffic away from Mobile Safari / Chrome, which would otherwise look like those browsers suddenly losing share. The 2026-05-30 config default opts in. Default false |
disable_beacon? | boolean | Prevents posthog-js from using the navigator.sendBeacon API to send events. Enabling this option may hurt the reliability of sending $pageleave events. |
disable_capture_url_hashes | boolean | Determines whether PostHog should strip URL fragments (#...) from automatically captured URL fields. Disabled by default for backwards compatibility, and enabled automatically when config.defaults is '2026-06-25' or later. Set to true to strip hashes from: - $current_url on automatically captured browser events, including $pageview - $initial_current_url - $session_entry_url - $elements[*].attr__href and $external_click_url for autocapture and dead-click autocapture - Next.js Pages Router $pageview $current_url - web vitals $current_url - logs url.full - conversations current_url and request_url - session replay rrweb meta/custom-event href URLs - heatmap data URLs If your SPA relies on hash-based routes for analytics, enabling this is a breaking behavior change. If you want to capture hashes selectively, leave this disabled and use before_send to remove sensitive hash values before events are sent. Default false when config.defaults is unset or earlier than '2026-06-25', otherwise true |
disable_compression | boolean | Determines whether to disable compression when sending events to the server. WARNING: Should only be used for testing. Could negatively impact performance. Default false |
disable_conversations | boolean | Determines whether PostHog should disable all conversations functionality. Default false |
disable_cookie? | boolean | Deprecated - use disable_persistence instead |
disable_external_dependency_loading | boolean | Determines whether PostHog should disable any external dependency loading. This will prevent PostHog from requesting any external scripts such as those needed for Session Replay, Surveys or Site Apps. Default false |
disable_persistence | boolean | Determines whether PostHog should disable persistence. If set to true, the library will not save any data to the browser. It will also delete any data previously saved to the browser. Default false |
disable_product_tours | boolean | Determines whether PostHog should disable all product tours functionality. Default false |
disable_scroll_properties? | boolean | Determines whether to disable scroll properties. These allow you to keep track of how far down someone scrolled in your website. Default false |
disable_session_recording | boolean | Determines whether PostHog should disable session recording. Default false |
disable_surveys | boolean | Determines whether PostHog should disable all surveys functionality. Default false |
disable_surveys_automatic_display | boolean | Determines whether PostHog should disable automatic display of surveys. If this is true, popup or widget surveys will not be shown when display conditions are met. Default false |
disable_web_experiments | boolean | Determines whether PostHog should disable web experiments. Currently disabled while we're in BETA. It will be toggled to true in a future release. Default true |
enable_heatmaps? | boolean | Deprecated Use capture_heatmaps instead. |
enable_recording_console_log? | boolean | Determines whether PostHog should enable recording console logs. This is related to the Session Recording feature. For more session recording settings, see the session_recording and capture_performance configuration option. When undefined, it falls back to the remote config setting. Default undefined |
error_tracking | ErrorTrackingOptions | Determines the error tracking options. See ErrorTrackingOptions Default {} |
evaluation_contexts? | readonly string[] | Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'web', 'checkout'] Default undefined |
evaluation_environments? | readonly string[] | Evaluation environments for feature flags. Deprecated Use evaluation_contexts instead. This property will be removed in a future version. |
external_scripts_inject_target? | "body" | "head" | Where to inject external dependency scripts (recorder, surveys, etc.) in the DOM. - 'body': Injects scripts into document.body (legacy behavior) - 'head': Injects scripts into document.head (avoids SSR hydration errors) Default 'body' (or 'head' when defaults >= '2026-01-30') |
feature_flag_cache_ttl_ms? | number | Sets the maximum age (in milliseconds) for cached feature flag values. When the cache is older than this value: - getFeatureFlag() will return undefined instead of stale cached values - $feature/ properties will not be attached to events - A background refresh will be triggered automatically This prevents stale feature flag values from being used when the /flags request fails (e.g., due to ad blockers or network issues). When not set or set to 0, cache expiration is disabled (cached values never expire). Default 0 |
feature_flag_request_max_retries | number | How many times to retry a /flags request before giving up. Only failures that are plausibly transient are retried: HTTP 502 and 504, and a request that timed out. Every other status is terminal, as is a transport failure that is not a timeout — in a browser those are usually an ad blocker, an extension or CORS, which the status-zero circuit breaker already handles, so retrying them would only add a second doomed request. Set to 0 to disable retries. Default 1 |
feature_flag_request_timeout_ms | number | Sets timeout for fetching feature flags Default 3000 |
fetch_options? | object | Used when sending data via fetch, use with care. This is intentionally meant to be used with NextJS fetch Incorrect cache usage may cause out-of-date data for feature flags, actions tracking, etc. See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options |
fetch_options.cache? | RequestCache | - |
fetch_options.next_options? | NextOptions | - |
flag_keys? | readonly string[] | List of feature flag keys to remotely evaluate for this SDK instance. When set, only these flags are evaluated by /flags; omitted flags are not remotely evaluated. Dependencies of the requested flags may still be evaluated internally by PostHog. If unset, all eligible flags are evaluated. Examples: ['checkout-redesign', 'new-onboarding'] Default undefined |
flags_api_host? | string | null | URL to use for feature flag requests specifically. If not set, feature flag requests will use the URL derived from api_host. This is useful when you want to route feature flag requests to a different endpoint than other analytic APIs. Default null |
get_current_url? | (defaultUrl) => string | Overrides the URL used for client-side URL targeting: session replay URL triggers, the session replay URL blocklist, survey URL display conditions, product tour URL conditions, web experiment URL conditions, and autocapture URL allow/ignore lists. These features match against window.location.href directly, which does not reflect any $current_url you rewrite in before_send. In environments where the browser URL is not meaningful for targeting — e.g. Electron/desktop apps served from a generated host — return the logical URL you want these features to match against. This does not change the $current_url property captured on events (use before_send for that). Default undefined (uses window.location.href) |
get_device_id | (uuid) => string | Function to get the device ID. This doesn't usually need to be set, but can be useful if you want to use a custom device ID. Default (uuid) => uuid |
identity_claims? | Record<string, { hash: string; value: string; }> | Additional server-signed identity claims. Claims are forwarded to products such as conversations only when identity_distinct_id and identity_hash are also present. Claim verification and consumption happen server-side. |
identity_distinct_id? | string | Verified distinct_id for HMAC-based identity verification. When both identity_distinct_id and identity_hash are provided, products like conversations use server-verified identity instead of anonymous session identifiers. Can be set at init time or later via posthog.setIdentity(). Example posthog.init('phc_...', { identity_distinct_id: 'user_123', identity_hash: 'a1b2c3d4e5f6...', }) |
identity_hash? | string | HMAC-SHA256 of identity_distinct_id, signed with the Secret API key from Support settings. Project secret API keys (project settings) and personal API keys are rejected. Must be provided together with identity_distinct_id. |
inapp_link_new_window? | boolean | Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons |
inapp_protocol? | string | Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons |
integrations? | Record<ExternalIntegrationKind, boolean> | Used to set-up external integrations with PostHog data - such as session replays, distinct id, etc. |
internal_or_test_user_hostname? | string | RegExp | null | A hostname pattern to match test environments. When the current hostname matches, setInternalOrTestUser() is called automatically on startup, enabling person processing and setting $internal_or_test_user: true. Can be a string (exact match) or RegExp (pattern match). Set to null to explicitly disable (useful when using defaults: '2026-01-30'). Default undefined (when defaults is before '2026-01-30') Default /^(localhost|127\.0\.0\.1)$/ (when defaults >= '2026-01-30') Example // Exact match posthog.init('token', { internal_or_test_user_hostname: 'example.com' }) // Regex pattern posthog.init('token', { internal_or_test_user_hostname: /\.local$/ }) // Disable posthog.init('token', { internal_or_test_user_hostname: null }) |
ip | boolean | Deprecated - THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. Use a custom transformation or "Discard IP data" project setting instead: See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address. |
loaded | (posthog_instance) => void | A function to be called once the PostHog scripts have loaded successfully. |
logs? | LogsConfig | Logs-specific configuration options. Default undefined |
mask_all_element_attributes | boolean | Prevent autocapture from capturing any attribute names on elements. Default false |
mask_all_text | boolean | Prevent autocapture from capturing textContent on elements. Default false |
mask_personal_data_properties | boolean | Mask personal data properties from the current URL. This will mask personal data properties such as advertising IDs (gclid, fbclid, etc.), and you can also add custom properties to mask with custom_personal_data_properties. Default false See - - Default campaign parameters that are masked by default. - - Custom list of personal data properties to mask. |
metrics? | BrowserMetricsConfig | Metrics-specific configuration options for the posthog.metrics API. Default undefined |
name | string | The name this instance will be identified by. You don't need to set this most of the time, but can be useful if you have several Posthog instances running at the same time. Default 'posthog' |
on_request_error? | (error) => void | A function that is called when a request to the PostHog API fails. |
on_xhr_error? | (failedRequest) => void | Deprecated - use on_request_error instead |
opt_in_site_apps | boolean | Determines if users should be opted in to site apps. Default false |
opt_out_capturing_by_default | boolean | Determines if users should be opted out of PostHog tracking by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing(). Default false |
opt_out_capturing_cookie_prefix | string | null | Deprecated Use consent_persistence_name instead. This will be removed in a future major version. |
opt_out_capturing_persistence_type | "localStorage" | "cookie" | Determines where we'll save the information about whether users are opted out of capturing. Default 'localStorage' |
opt_out_persistence_by_default? | boolean | Determines if users should be opted out of browser data storage by this PostHog instance by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing(). Default false |
opt_out_useragent_filter | boolean | Determines if users should be opted out of user agent filtering such as googlebot or other bots. If this is set to true, PostHog will set $browser_type to either bot or browser for all events, but will process all events as if they were from a browser. When the filter drops events, a one-time warning is written to the console (even without debug mode). The filter applies to events only; logs sent with captureLog bypass it. Set this to true behind a test flag for end-to-end tests (Playwright, Puppeteer). Default false |
override_display_language? | string | null | Display language override for Product Tours. Must be a valid BCP 47 language code. In the future this will be used for Surveys and other products that deliver in-app experiences to end-users. |
persistence | "localStorage" | "cookie" | "memory" | "localStorage+cookie" | "sessionStorage" | Determines how PostHog stores information about the user. See persistence for details. Default 'localStorage+cookie' |
persistence_name | string | The name for the super properties persistent store Default '' |
persistence_save_debounce_ms? | number | Coalesce rapid Persistence.save() calls into a single write. Set to a positive number (milliseconds) to debounce writes to localStorage / cookie by that window. The in-memory props object is always updated synchronously so within-tab reads see the latest values immediately. Cross-tab storage events (which carry the full persistence value as a payload) are reduced proportionally to the debounce window. Pending writes are flushed on beforeunload and pagehide so no state is lost on tab close. The cross-tab visibility delay is bounded by the configured window. Defaults to 0 (no debouncing, write synchronously) for backwards compatibility. On pages that capture many events per second, 250 is a reasonable starting point to reduce localStorage write pressure and cross-tab IPC traffic. The 2026-05-30 config default opts into 250 automatically. Default 0 |
person_profiles? | "always" | "never" | "identified_only" | You can control whether events from PostHog-js have person processing enabled with the person_profiles config setting. There are three options: - person_profiles: 'always' - we will process persons data for all events - person_profiles: 'never' - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including $identify) will be sent with $process_person_profile: False. - person_profiles: 'identified_only' (default) - we will only process persons when you call posthog.identify, posthog.alias, posthog.setPersonProperties, posthog.unsetPersonProperties, posthog.group, posthog.setPersonPropertiesForFlags or posthog.setGroupPropertiesForFlags Anonymous users won't get person profiles. Default 'identified_only' |
prepare_external_dependency_script? | (script) => HTMLScriptElement | null | A function to be called when a script is being loaded. This can be used to modify the script before it is loaded. This is useful for adding a nonce to the script, for example. |
prepare_external_dependency_stylesheet? | (stylesheet) => HTMLStyleElement | null | A function to be called when a stylesheet is being loaded. This can be used to modify the stylesheet before it is loaded. This is useful for adding a nonce to the stylesheet, for example. |
process_person? | "always" | "never" | "identified_only" | Deprecated - use person_profiles instead |
properties_string_max_length | number | Determines the maximum length of the properties string that can be sent with capture calls. Default 65535 |
property_blacklist? | string[] | Deprecated - use property_denylist instead |
property_denylist | string[] | A list of properties that should never be sent with capture calls. Default [] |
rageclick | boolean | RageclickConfig | Determines whether PostHog should capture rage clicks. By default, rage clicks are ignored on elements that match a ph-no-capture or ph-no-rageclick CSS class on the element or a parent. When defaults is '2025-11-30' or later, the default is { content_ignorelist: true }, which also ignores repeat-click controls such as pagination arrows and pagers (see content_ignorelist). When defaults is '2026-05-30' or later, the default also excludes stepper controls (+, -, −, –) and text-selection surfaces. Default true |
rate_limiting? | object | Client side rate limiting. A token bucket, per browser, that stops a runaway loop on your site from flooding capture. When it drains, further capture calls are dropped and a one-off $$client_ingestion_warning is sent reporting how many events were dropped and the page and session that tripped it - usually the fastest way to find the loop. Raise these limits if you legitimately capture in bursts; a warning under the defaults is more often a bug on the page than a limit set too low. |
rate_limiting.events_burst_limit? | number | How many events can be captured in a burst. This defaults to 10 times the events_per_second count Default 10 * events_per_second |
rate_limiting.events_per_second? | number | The average number of events per second that should be permitted Default 10 |
remote_config_refresh_interval_ms? | number | Controls how often feature flags are automatically refreshed in long-running sessions. The default interval is 5 minutes (300000ms) to pick up server-side flag changes without requiring a page reload. This is useful for SPAs and long-running tabs. An explicitly set positive interval stays fixed, even when the page gets no user interaction. Each refresh is a billable feature flag request. A page that stays open all day makes up to 288 requests per day on the default interval, and every open tab and every named instance refreshes on its own timer, so they add up. Set this option to 0 to stop the background refreshes if that cost is not useful to you. Tradeoffs: - Shorter intervals: Feature flag changes propagate faster, but increases network requests, cost, and server load. - Longer intervals: Reduces network traffic (better for mobile/battery) and cost, but flag changes take longer to propagate. - Disabled (0 or any negative value): No background refreshes. Flags only update on page load or manual reloadFeatureFlags() calls. Use this if you control flag updates manually or have infrequent flag changes. Hidden pages skip scheduled refreshes and reload due flags when they become visible. When this option is omitted, a visible page that gets no user interaction (such as a dashboard, a page being read, a video player, or a kiosk) doubles the interval after every refresh, up to one hour. Automatic refreshes continue at that interval; they do not stop. The next click, key press, wheel, touch, or return to visibility restores the five-minute default. Scrolling driven by a script, such as an auto-playing carousel, does not count as an interaction. Set this option explicitly to keep a fixed cadence, or to 0 to stop background refreshes completely. This option does not reload remote config. Default 300000 (5 minutes) |
request_batching | boolean | Determines whether PostHog should batch requests to the PostHog API. Default true |
request_headers | object | A list of headers that should be sent with requests to the PostHog API. Default {} |
request_queue_config? | RequestQueueConfig | Used to change the behavior of the request queue. This is an advanced feature and should be used with caution. |
respect_dnt | boolean | Determines whether PostHog should respect the Do Not Track header when computing consent in ConsentManager. See ConsentManager Default false |
reuseAnonymousId? | boolean | When true, identify() omits $anon_distinct_id from the $identify event and the follow-up feature flag request, so PostHog does not merge the previous anonymous identity into the identified person. Default false |
rewriteRequestPath? | (url) => URL | Rewrites the URL used for PostHog API, feature flag, and asset requests. This is intended for customers who use a reverse proxy and need custom paths. The proxy must map the rewritten paths back to the canonical PostHog paths. UI links are not rewritten. Example posthog.init('phc_...', { api_host: 'https://a.example.com', rewriteRequestPath: (url) => { if (url.pathname === '/e/') { url.pathname = '/my-events/' } else if (url.pathname === '/s/') { url.pathname = '/my-replay/' } else if (url.pathname === '/flags/') { url.pathname = '/my-flags/' } return url }, }) |
sanitize_properties | ((properties, event_name) => Properties) | null | Deprecated - use before_send instead |
save_campaign_params | boolean | Determines whether PostHog should save marketing parameters. These are utm_* paramaters and friends. See from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc. Default true |
save_referrer | boolean | Determines whether PostHog should save referrer information. Default true |
scroll_root_selector? | string | string[] | Let the pageview scroll stats use a custom css selector for the root element, e.g. main It will use window.document.documentElement if not specified. |
secure_cookie | boolean | Determines whether PostHog should use secure cookies. If this is true, PostHog cookies will be marked as secure, meaning they will only be transmitted over HTTPS. Default window.location.protocol === 'https:' |
segment? | SegmentIntegrationConfig | SegmentAnalytics | The Segment analytics object, or integration configuration. Example segment: { analytics: window.analytics, filterProperties: (properties) => { for (const key in properties) { if (key.startsWith('$sdk_debug_')) { delete properties[key] } } return properties } } See https://posthog.com/docs/libraries/segment |
session_idle_timeout_seconds | number | Determines the session idle timeout in seconds. If no events are captured for this many seconds, the next event starts a new session with a new $session_id (and $window_id). The SDK may also proactively reset the stored session after the timeout while the page is idle, so the next event creates a new session. Session recording has a separate idle threshold: session_recording.session_idle_threshold_ms. That setting only controls when the user is considered idle, it does not rotate $session_id. Must be between 60 seconds and 10 hours. Values outside this range are clamped. Default 30 * 60 -- 30 minutes |
session_recording | SessionRecordingOptions | Determines the session recording options. For more session recording settings, see the enable_recording_console_log and capture_performance configuration option. When defaults is '2025-11-30' or later, strictMinimumDuration defaults to true. See SessionRecordingOptions Default {} |
split_storage? | boolean | Store the feature-flag config cluster and survey config in their own localStorage entries (<name>__flags, <name>__surveys) instead of the single main persistence blob. These payloads are large and change rarely, so keeping them out of the main blob stops them riding on every high-frequency main-blob write and broadcasting cross-tab storage events. Only applies when persistence resolves to localStorage / localStorage+cookie (the split is pointless for memory / sessionStorage and impossible for cookie). On load the old main-blob location is read once and migrated forward, so upgrades never miss a cached flag. The 2026-05-30 config default opts in. Default false |
store_google? | boolean | Deprecated - Use save_campaign_params instead |
strict_script_versioning | boolean | "fallback" | Determines whether PostHog should load external dependency scripts from semver-qualified asset paths such as /static/1.370.0/recorder.js instead of the legacy /static/recorder.js?v=1.370.0 form. Set to true to use only versioned paths, false to use only legacy paths, or 'fallback' to try the versioned path first and retry with the legacy path if it fails. Default 'fallback' |
surveys? | SurveyConfig | Survey-specific configuration options. Default undefined |
surveys_request_timeout_ms | number | Sets timeout for fetching surveys Default 10000 |
token | string | The token for your PostHog project. It should NOT be provided manually in the config, but rather passed as the first parameter to posthog.init(). |
trace_propagation_targets? | string[] | Hosts that should receive a W3C Trace Context traceparent header on fetch and XMLHttpRequest requests, so your backend can continue the trace started in the browser. Each request gets a new trace id and span id, with the sampled flag set (00-<trace-id>-<span-id>-01). The browser does not record a span of its own, so the span id in the header is the parent of your server's root span. Matching is exact and nothing is sent to unlisted hosts: - an entry with a scheme (https://api.example.com, http://localhost:8000) matches that origin only - any other entry (api.example.com) matches that hostname on any scheme or port Only list hosts that accept the header. A cross-origin request with a traceparent header triggers a CORS preflight, and fails if the server's Access-Control-Allow-Headers doesn't include traceparent. A traceparent header already set by your app or by OpenTelemetry's instrumentation is never overwritten or duplicated. If OpenTelemetry's XHR instrumentation also propagates to a cross-origin host (its propagateTraceHeaderCorsUrls), list that host in only one of the two. Example posthog.init('<token>', { trace_propagation_targets: ['https://api.example.com', 'internal.example.com'] }) |
tracing_headers? | string[] | A list of hostnames for which to inject PostHog tracing headers to all requests (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID, X-POSTHOG-WINDOW-ID). Used to link frontend sessions to backend traces (see https://posthog.com/docs/llm-analytics/link-session-replay). |
ui_host | string | null | If using a reverse proxy for api_host then this should be the actual PostHog app URL (e.g. https://us.posthog.com). This ensures that links to PostHog point to the correct host. Default null |
upgrade | boolean | Determines whether PostHog should upgrade old cookies. If set to true, the library will check for a cookie from our old js library and import super properties from it, then the old cookie is deleted. This option only works in the initialization, so make sure you set it when you create the library. Default false |
verbose? | boolean | Deprecated Use debug instead |
xhr_headers? | object | Deprecated - use request_headers instead |
PostHogFeatureFlags
Legacy constructor and configuration mapping for the shared flags extension.
Extends
PostHogFeatureFlags
Constructors
Constructor
new PostHogFeatureFlags(
instance):PostHogFeatureFlags
Parameters
| Parameter | Type |
|---|---|
instance | PostHog |
Returns
PostHogFeatureFlags
Properties
Accessors
hasLoadedFlags
Get Signature
get hasLoadedFlags():
boolean
Returns
boolean
Methods
_callFlagsEndpoint()
_callFlagsEndpoint(
options?):void
Parameters
| Parameter | Type |
|---|---|
options? | { disableFlags?: boolean; } |
options.disableFlags? | boolean |
Returns
void
_fireFeatureFlagsCallbacks()
_fireFeatureFlagsCallbacks(
errorsLoading?):void
Parameters
| Parameter | Type |
|---|---|
errorsLoading? | boolean |
Returns
void
_prepareFeatureFlagsForCallbacks()
_prepareFeatureFlagsForCallbacks():
object
Returns
object
| Name | Type |
|---|---|
flags | string[] |
flagVariants | Record<string, string | boolean> |
addFeatureFlagsHandler()
addFeatureFlagsHandler(
handler):void
Parameters
| Parameter | Type |
|---|---|
handler | FeatureFlagsCallback |
Returns
void
destroy()
destroy():
void
Returns
void
dispose()
dispose():
void
Release final resources synchronously. Feature-level start/stop remains extension-owned.
Returns
void
ensureFlagsLoaded()
ensureFlagsLoaded():
void
Returns
void
getAllFeatureFlags()
getAllFeatureFlags():
FeatureFlagResult[]
Returns
FeatureFlagResult[]
getEarlyAccessFeatures()
getEarlyAccessFeatures(
callback,force_reload?,stages?):void
Parameters
| Parameter | Type |
|---|---|
callback | EarlyAccessFeatureCallback |
force_reload? | boolean |
stages? | EarlyAccessFeatureStage[] |
Returns
void
getFeatureFlag()
getFeatureFlag(
key,options?):string|boolean|undefined
Get feature flag's value for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
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.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | Optional settings. |
Returns
string | boolean | undefined
The flag value, or undefined if no current evaluation is available.
getFeatureFlagDetails()
getFeatureFlagDetails(
key):FeatureFlagDetail|undefined
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
FeatureFlagDetail | undefined
getFeatureFlagPayload()
getFeatureFlagPayload(
key):JsonType
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
JsonType
Deprecated
Use getFeatureFlagResult() instead which properly tracks the feature flag call.
getFeatureFlagPayload() does not emit the $feature_flag_called event which may result in
missing analytics. This method will be removed in a future version.
getFeatureFlagResult()
getFeatureFlagResult(
key,options?):FeatureFlagResult|undefined
Get a feature flag result including both the flag value and payload, while properly tracking the call.
This method emits the $feature_flag_called event by default.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
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.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | Options for the feature flag lookup. |
Returns
FeatureFlagResult | undefined
The feature flag result including key, enabled, variant, and payload.
getFlagPayloads()
getFlagPayloads():
Record<string,JsonType>
Returns
Record<string, JsonType>
getFlags()
getFlags():
string[]
Returns
string[]
getFlagsWithDetails()
getFlagsWithDetails():
Record<string,FeatureFlagDetail>
Returns
Record<string, FeatureFlagDetail>
getFlagVariants()
getFlagVariants():
Record<string,string|boolean>
Returns
Record<string, string | boolean>
getRemoteConfigPayload()
getRemoteConfigPayload(
key,callback):void
Parameters
| Parameter | Type |
|---|---|
key | string |
callback | RemoteConfigFeatureFlagCallback |
Returns
void
initialize()
initialize():
void
Returns
void
isFeatureEnabled()
Call Signature
isFeatureEnabled(
key,options?):boolean
See if feature flag is enabled for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
A false result means the flag value evaluated off; it does not mean the SDK observed the
flag's global active setting. When no current evaluation is available, this method returns
options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted
from the remote /flags response and therefore have no value.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions & object & object | Optional settings. |
Returns
boolean
Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
Call Signature
isFeatureEnabled(
key,options?):boolean|undefined
See if feature flag is enabled for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
A false result means the flag value evaluated off; it does not mean the SDK observed the
flag's global active setting. When no current evaluation is available, this method returns
options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted
from the remote /flags response and therefore have no value.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | IsFeatureEnabledOptions | Optional settings. |
Returns
boolean | undefined
Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
onFeatureFlags()
onFeatureFlags(
callback): () =>void
Parameters
| Parameter | Type |
|---|---|
callback | FeatureFlagsCallback |
Returns
() => void
onReloading()
onReloading(
handler): () =>void
Parameters
| Parameter | Type |
|---|---|
handler | () => void |
Returns
() => void
override()
override(
flags,suppressWarning?):void
Parameters
| Parameter | Type |
|---|---|
flags | boolean | string[] | Record<string, string | boolean> |
suppressWarning? | boolean |
Returns
void
Deprecated
Use overrideFeatureFlags instead. This will be removed in a future version.
overrideFeatureFlags()
overrideFeatureFlags(
overrideOptions):void
Override feature flags on the client-side. Useful for setting non-persistent feature flags, or for testing/debugging feature flags in the PostHog app.
Usage:
Parameters
| Parameter | Type |
|---|---|
overrideOptions | OverrideFeatureFlagsOptions |
Returns
void
receivedFeatureFlags()
receivedFeatureFlags(
response,errorsLoading?,options?):void
Parameters
| Parameter | Type |
|---|---|
response | Partial<FlagsResponse> |
errorsLoading? | boolean |
options? | { partialResponse?: boolean; } |
options.partialResponse? | boolean |
Returns
void
reloadFeatureFlags()
reloadFeatureFlags():
void
Reloads feature flags asynchronously.
Constraints:
- Avoid parallel requests
- Delay a few milliseconds after each reloadFeatureFlags call to batch subsequent changes together
Returns
void
reloadFeatureFlagsAsync()
reloadFeatureFlagsAsync():
Promise<FeatureFlagsReloadResult>
Await the next requested evaluation, rather than cached or locally injected flag changes.
Returns
Promise<FeatureFlagsReloadResult>
removeFeatureFlagsHandler()
removeFeatureFlagsHandler(
handler):void
Parameters
| Parameter | Type |
|---|---|
handler | FeatureFlagsCallback |
Returns
void
reset()
reset():
void
Returns
void
resetFlagCallReported()
resetFlagCallReported():
void
Returns
void
resetGroupPropertiesForFlags()
resetGroupPropertiesForFlags(
group_type?):void
Parameters
| Parameter | Type |
|---|---|
group_type? | string |
Returns
void
resetPersonPropertiesForFlags()
resetPersonPropertiesForFlags(
reloadFeatureFlags?):void
Parameters
| Parameter | Type |
|---|---|
reloadFeatureFlags? | boolean |
Returns
void
sendFlagCallsPendingCapture()
sendFlagCallsPendingCapture():
void
Sends $feature_flag_called for the flags read while capture was off, once the client can capture.
Returns
void
setAnonymousDistinctId()
setAnonymousDistinctId(
anon_distinct_id):void
Parameters
| Parameter | Type |
|---|---|
anon_distinct_id | string | undefined |
Returns
void
setGroupPropertiesForFlags()
setGroupPropertiesForFlags(
properties,reloadFeatureFlags?):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. For example: setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })
Parameters
| Parameter | Type |
|---|---|
properties | {[type: string]: Properties; } |
reloadFeatureFlags? | boolean |
Returns
void
setPersonPropertiesForFlags()
setPersonPropertiesForFlags(
properties,reloadFeatureFlags?):void
Set override person properties for feature flags. This is used when dealing with new persons / where you don't want to wait for ingestion to update user properties.
Parameters
| Parameter | Type |
|---|---|
properties | Properties |
reloadFeatureFlags? | boolean |
Returns
void
setReloadingPaused()
setReloadingPaused(
isPaused):void
Parameters
| Parameter | Type |
|---|---|
isPaused | boolean |
Returns
void
setup()
setup(
client):void|Promise<void>
Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.
Parameters
| Parameter | Type |
|---|---|
client | Client |
Returns
void | Promise<void>
unsetPersonPropertiesForFlags()
unsetPersonPropertiesForFlags(
propertyNames,reloadFeatureFlags?):void
Remove override person properties used for feature flags. This is the counterpart to setPersonPropertiesForFlags, used when person properties are unset so flags re-evaluate without the removed values.
Parameters
| Parameter | Type |
|---|---|
propertyNames | string[] |
reloadFeatureFlags? | boolean |
Returns
void
updateConfig()
updateConfig(
config,remoteRequestsDisabled):void
Parameters
| Parameter | Type |
|---|---|
config | PostHogConfig |
remoteRequestsDisabled | boolean |
Returns
void
updateEarlyAccessFeatureEnrollment()
updateEarlyAccessFeatureEnrollment(
key,isEnrolled,stage?):void
Parameters
| Parameter | Type |
|---|---|
key | string |
isEnrolled | boolean |
stage? | string |
Returns
void
updateFlags()
updateFlags(
flags,payloads?,options?):void
Parameters
| Parameter | Type |
|---|---|
flags | Record<string, boolean | string> |
payloads? | Record<string, JsonType> |
options? | { merge?: boolean; } |
options.merge? | boolean |
Returns
void
PostHogFeatureFlags
A shared browser extension. The client calls setup(client) once to start it
and optional dispose() once for final best-effort resource cleanup.
Everything an extension consumes flows through its host, Client by default.
setup may be async so an extension can read async KV state or remote config
before it is ready. Async extensions must guard work after each await so
cleanup cannot be followed by late listener, timer, or patch installation.
The disposables an extension creates in setup are its own to release.
An extension that exposes app-facing controls extends Extension with named
methods that share its state, e.g.:
Extended by
PostHogFeatureFlags
Implements
Extension
Constructors
Constructor
new PostHogFeatureFlags(
configSource):PostHogFeatureFlags
Parameters
| Parameter | Type |
|---|---|
configSource | FeatureFlagsConfigSource |
Returns
PostHogFeatureFlags
Properties
Accessors
hasLoadedFlags
Get Signature
get hasLoadedFlags():
boolean
Returns
boolean
Methods
_callFlagsEndpoint()
_callFlagsEndpoint(
options?):void
Parameters
| Parameter | Type |
|---|---|
options? | { disableFlags?: boolean; } |
options.disableFlags? | boolean |
Returns
void
_fireFeatureFlagsCallbacks()
_fireFeatureFlagsCallbacks(
errorsLoading?):void
Parameters
| Parameter | Type |
|---|---|
errorsLoading? | boolean |
Returns
void
_prepareFeatureFlagsForCallbacks()
_prepareFeatureFlagsForCallbacks():
object
Returns
object
| Name | Type |
|---|---|
flags | string[] |
flagVariants | Record<string, string | boolean> |
addFeatureFlagsHandler()
addFeatureFlagsHandler(
handler):void
Parameters
| Parameter | Type |
|---|---|
handler | FeatureFlagsCallback |
Returns
void
destroy()
destroy():
void
Returns
void
dispose()
dispose():
void
Release final resources synchronously. Feature-level start/stop remains extension-owned.
Returns
void
ensureFlagsLoaded()
ensureFlagsLoaded():
void
Returns
void
getAllFeatureFlags()
getAllFeatureFlags():
FeatureFlagResult[]
Returns
FeatureFlagResult[]
getEarlyAccessFeatures()
getEarlyAccessFeatures(
callback,force_reload?,stages?):void
Parameters
| Parameter | Type |
|---|---|
callback | EarlyAccessFeatureCallback |
force_reload? | boolean |
stages? | EarlyAccessFeatureStage[] |
Returns
void
getFeatureFlag()
getFeatureFlag(
key,options?):string|boolean|undefined
Get feature flag's value for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
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.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | Optional settings. |
Returns
string | boolean | undefined
The flag value, or undefined if no current evaluation is available.
getFeatureFlagDetails()
getFeatureFlagDetails(
key):FeatureFlagDetail|undefined
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
FeatureFlagDetail | undefined
getFeatureFlagPayload()
getFeatureFlagPayload(
key):JsonType
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
JsonType
Deprecated
Use getFeatureFlagResult() instead which properly tracks the feature flag call.
getFeatureFlagPayload() does not emit the $feature_flag_called event which may result in
missing analytics. This method will be removed in a future version.
getFeatureFlagResult()
getFeatureFlagResult(
key,options?):FeatureFlagResult|undefined
Get a feature flag result including both the flag value and payload, while properly tracking the call.
This method emits the $feature_flag_called event by default.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
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.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions | Options for the feature flag lookup. |
Returns
FeatureFlagResult | undefined
The feature flag result including key, enabled, variant, and payload.
getFlagPayloads()
getFlagPayloads():
Record<string,JsonType>
Returns
Record<string, JsonType>
getFlags()
getFlags():
string[]
Returns
string[]
getFlagsWithDetails()
getFlagsWithDetails():
Record<string,FeatureFlagDetail>
Returns
Record<string, FeatureFlagDetail>
getFlagVariants()
getFlagVariants():
Record<string,string|boolean>
Returns
Record<string, string | boolean>
getRemoteConfigPayload()
getRemoteConfigPayload(
key,callback):void
Parameters
| Parameter | Type |
|---|---|
key | string |
callback | RemoteConfigFeatureFlagCallback |
Returns
void
initialize()
initialize():
void
Returns
void
isFeatureEnabled()
Call Signature
isFeatureEnabled(
key,options?):boolean
See if feature flag is enabled for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
A false result means the flag value evaluated off; it does not mean the SDK observed the
flag's global active setting. When no current evaluation is available, this method returns
options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted
from the remote /flags response and therefore have no value.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | FeatureFlagOptions & object & object | Optional settings. |
Returns
boolean
Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
Call Signature
isFeatureEnabled(
key,options?):boolean|undefined
See if feature flag is enabled for user.
By default, this method may return cached values from localStorage if the /flags endpoint
hasn't responded yet. This reduces flicker but means you might briefly see stale values
(e.g., a flag that was made globally inactive on the server).
A false result means the flag value evaluated off; it does not mean the SDK observed the
flag's global active setting. When no current evaluation is available, this method returns
options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted
from the remote /flags response and therefore have no value.
Usage:
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Key of the feature flag. |
options? | IsFeatureEnabledOptions | Optional settings. |
Returns
boolean | undefined
Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
onFeatureFlags()
onFeatureFlags(
callback): () =>void
Parameters
| Parameter | Type |
|---|---|
callback | FeatureFlagsCallback |
Returns
() => void
onReloading()
onReloading(
handler): () =>void
Parameters
| Parameter | Type |
|---|---|
handler | () => void |
Returns
() => void
override()
override(
flags,suppressWarning?):void
Parameters
| Parameter | Type |
|---|---|
flags | boolean | string[] | Record<string, string | boolean> |
suppressWarning? | boolean |
Returns
void
Deprecated
Use overrideFeatureFlags instead. This will be removed in a future version.
overrideFeatureFlags()
overrideFeatureFlags(
overrideOptions):void
Override feature flags on the client-side. Useful for setting non-persistent feature flags, or for testing/debugging feature flags in the PostHog app.
Usage:
Parameters
| Parameter | Type |
|---|---|
overrideOptions | OverrideFeatureFlagsOptions |
Returns
void
receivedFeatureFlags()
receivedFeatureFlags(
response,errorsLoading?,options?):void
Parameters
| Parameter | Type |
|---|---|
response | Partial<FlagsResponse> |
errorsLoading? | boolean |
options? | { partialResponse?: boolean; } |
options.partialResponse? | boolean |
Returns
void
reloadFeatureFlags()
reloadFeatureFlags():
void
Reloads feature flags asynchronously.
Constraints:
- Avoid parallel requests
- Delay a few milliseconds after each reloadFeatureFlags call to batch subsequent changes together
Returns
void
reloadFeatureFlagsAsync()
reloadFeatureFlagsAsync():
Promise<FeatureFlagsReloadResult>
Await the next requested evaluation, rather than cached or locally injected flag changes.
Returns
Promise<FeatureFlagsReloadResult>
removeFeatureFlagsHandler()
removeFeatureFlagsHandler(
handler):void
Parameters
| Parameter | Type |
|---|---|
handler | FeatureFlagsCallback |
Returns
void
reset()
reset():
void
Returns
void
resetFlagCallReported()
resetFlagCallReported():
void
Returns
void
resetGroupPropertiesForFlags()
resetGroupPropertiesForFlags(
group_type?):void
Parameters
| Parameter | Type |
|---|---|
group_type? | string |
Returns
void
resetPersonPropertiesForFlags()
resetPersonPropertiesForFlags(
reloadFeatureFlags?):void
Parameters
| Parameter | Type |
|---|---|
reloadFeatureFlags? | boolean |
Returns
void
sendFlagCallsPendingCapture()
sendFlagCallsPendingCapture():
void
Sends $feature_flag_called for the flags read while capture was off, once the client can capture.
Returns
void
setAnonymousDistinctId()
setAnonymousDistinctId(
anon_distinct_id):void
Parameters
| Parameter | Type |
|---|---|
anon_distinct_id | string | undefined |
Returns
void
setGroupPropertiesForFlags()
setGroupPropertiesForFlags(
properties,reloadFeatureFlags?):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. For example: setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })
Parameters
| Parameter | Type |
|---|---|
properties | {[type: string]: Properties; } |
reloadFeatureFlags? | boolean |
Returns
void
setPersonPropertiesForFlags()
setPersonPropertiesForFlags(
properties,reloadFeatureFlags?):void
Set override person properties for feature flags. This is used when dealing with new persons / where you don't want to wait for ingestion to update user properties.
Parameters
| Parameter | Type |
|---|---|
properties | Properties |
reloadFeatureFlags? | boolean |
Returns
void
setReloadingPaused()
setReloadingPaused(
isPaused):void
Parameters
| Parameter | Type |
|---|---|
isPaused | boolean |
Returns
void
setup()
setup(
client):void|Promise<void>
Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.
Parameters
| Parameter | Type |
|---|---|
client | Client |
Returns
void | Promise<void>
unsetPersonPropertiesForFlags()
unsetPersonPropertiesForFlags(
propertyNames,reloadFeatureFlags?):void
Remove override person properties used for feature flags. This is the counterpart to setPersonPropertiesForFlags, used when person properties are unset so flags re-evaluate without the removed values.
Parameters
| Parameter | Type |
|---|---|
propertyNames | string[] |
reloadFeatureFlags? | boolean |
Returns
void
updateEarlyAccessFeatureEnrollment()
updateEarlyAccessFeatureEnrollment(
key,isEnrolled,stage?):void
Parameters
| Parameter | Type |
|---|---|
key | string |
isEnrolled | boolean |
stage? | string |
Returns
void
updateFlags()
updateFlags(
flags,payloads?,options?):void
Parameters
| Parameter | Type |
|---|---|
flags | Record<string, boolean | string> |
payloads? | Record<string, JsonType> |
options? | { merge?: boolean; } |
options.merge? | boolean |
Returns
void
PostHogInterface
PostHogInterface =
Omit<PostHog,"config"|"init"|"set_config"> &object
Type Declaration
| Name | Type |
|---|---|
config | PostHogConfig |
set_config() | (config) => void |
ProductTour
ProductTourAppearance
ProductTourBannerConfig
ProductTourButtonAction
ProductTourButtonAction =
"dismiss"|"link"|"next_step"|"previous_step"|"trigger_tour"
Button actions available on modal steps
ProductTourCallback
ProductTourCallback = (
tours,context?) =>void
Parameters
| Parameter | Type |
|---|---|
tours | ProductTour[] |
context? | { error?: string; isLoaded: boolean; } |
context.error? | string |
context.isLoaded | boolean |
Returns
void
ProductTourConditions
ProductTourDismissReason
ProductTourDismissReason =
"user_clicked_skip"|"user_clicked_outside"|"escape_key"|"element_unavailable"|"container_unavailable"
ProductTourDisplayFrequency
ProductTourDisplayFrequency =
"show_once"|"until_interacted"|"always"
ProductTourEventName
ProductTourEventName = typeof
ProductTourEventName[keyof typeofProductTourEventName]
ProductTourEventProperties
ProductTourEventProperties = typeof
ProductTourEventProperties[keyof typeofProductTourEventProperties]
ProductTourRenderReason
ProductTourRenderReason =
"auto"|"api"|"trigger"|"event"
ProductTourSelectorError
ProductTourSelectorError =
"not_found"|"multiple_matches"|"not_visible"
ProductTourStep
ProductTourStepButton
ProductTourStepButtons
ProductTourStepTranslation
all translatable content for a given tour step
Properties
ProductTourStepType
ProductTourStepType =
"element"|"modal"|"survey"|"banner"
ProductTourSurveyQuestion
ProductTourSurveyQuestionType
ProductTourSurveyQuestionType =
"open"|"rating"
ProductTourType
ProductTourType =
"tour"|"announcement"|"banner"
maps to main repo EffectiveProductTourType
ProductTourWaitPeriod
Properties
Properties =
Record<string,Property>
Property
Property =
any
Common types shared across PostHog SDKs
PropertyFilters
PropertyFilters =
Record<string, {operator:PropertyOperator;values:string[]; }>
PropertyMatchType
PropertyMatchType =
SurveyMatchType
PropertyOperator
PropertyOperator =
PropertyMatchType|"gt"|"lt"
QueuedRequestWithOptions
RequestWithOptions
Extended by
RetriableRequestWithOptions
Properties
RageclickConfig
RatingSurveyQuestion
SurveyQuestionBase
Properties
RemoteConfig
Remote configuration for a PostHog browser client.
These settings can be configured in PostHog. Configuration set directly on the client takes precedence over values from the server.
Extended by
FlagsResponse
Properties
RemoteConfigFeatureFlagCallback
RemoteConfigFeatureFlagCallback = (
payload) =>void
Parameters
| Parameter | Type |
|---|---|
payload | JsonType |
Returns
void
RequestCallback
RequestCallback = (
response) =>void
Parameters
| Parameter | Type |
|---|---|
response | RequestResponse |
Returns
void
RequestQueueConfig
RequestResponse
RequestRestoreLinkPayload
Payload for requesting a self-service restore link email
Properties
RequestRestoreLinkResponse
Response from self-service restore link request
Properties
RequestTarget
RequestTarget =
"api"|"flags"|"assets"
Configured host used to resolve a relative request path.
RequestTransport
RequestTransport =
"XHR"|"fetch"|"sendBeacon"
Browser transport requested for a send.
RequestWithOptions
QueuedRequestWithOptions
Properties
ResetOptions
ResponseBasedBranching
RestoreFromTokenPayload
Payload for restoring ticket access from a one-time token
Properties
RestoreFromTokenResponse
Response from restore token exchange endpoint
Properties
RestoreFromTokenStatus
RestoreFromTokenStatus =
"success"|"expired"|"invalid"|"used"
RetriableRequestWithOptions
QueuedRequestWithOptions
Properties
SegmentAnalytics
SegmentAnalytics =
object
Segment analytics object used for integration with PostHog
Properties
SegmentAnalyticsUser
SegmentAnalyticsUser =
object
Methods
anonymousId()
anonymousId():
string|null|undefined
Returns
string | null | undefined
id()
id():
string|null|undefined
Returns
string | null | undefined
SegmentEnrichmentFilterFn
SegmentEnrichmentFilterFn = (
properties) =>Properties|null
Filters non-colliding properties generated by PostHog before they are added to a Segment event.
Original Segment properties are excluded. Returning null skips PostHog enrichment for that event.
Parameters
| Parameter | Type |
|---|---|
properties | Properties |
Returns
Properties | null
SegmentIntegrationConfig
SegmentIntegrationConfig =
object
Configuration for the PostHog Segment integration.
Properties
SendMessagePayload
Payload for sending a message via the conversations API
Properties
SendMessageResponse
Response from sending a message
Properties
SendRequestInit
Options for sending a request through Client.sendRequest.
Properties
SessionContext
Session context captured when creating a new ticket
Properties
SessionContext
The current session, stamped on events to tie them to a session and a browser tab.
Properties
SessionIdChangedCallback
SessionIdChangedCallback = (
sessionId,windowId,changeReason?) =>void
Parameters
| Parameter | Type | Description |
|---|---|---|
sessionId | string | - |
windowId | string | null | undefined | - |
changeReason? | { activityTimeout: boolean; crossTabAdoption?: boolean; noSessionId: boolean; sessionPastMaximumLength: boolean; } | - |
changeReason.activityTimeout | boolean | - |
changeReason.crossTabAdoption? | boolean | This tab picked up a session rotation another tab had already written to storage, instead of minting its own. |
changeReason.noSessionId | boolean | - |
changeReason.sessionPastMaximumLength | boolean | - |
Returns
void
SessionRecordingCanvasOptions
SessionRecordingCanvasOptions =
object
Properties
SessionRecordingEventTrigger
V2 event trigger - always an object with name, optionally with property filters. The server normalizes bare event name strings to this shape before sending.
Properties
SessionRecordingOptions
| Property | Type | Description |
|---|---|---|
__mutationBytesBucketSize? | number | ADVANCED: enables the mutation byte budget by setting its burst allowance, in bytes. Also the largest single mutation event that will be recorded. Unset (the default), the byte budget is off. 1048576 (1MB) is a sensible starting point. Normally only altered alongside posthog support guidance. Default undefined |
__mutationBytesRefillRate? | number | ADVANCED: the sustained mutation byte budget, in bytes per second. Mutation events beyond the budget are dropped and the recording resyncs with a full snapshot. Only takes effect when __mutationBytesBucketSize is set. Normally only altered alongside posthog support guidance. Default 25600 |
__mutationThrottlerBucketSize? | number | ADVANCED: alters the bucket size for the token bucket mutation throttling Normally only altered alongside posthog support guidance. Accepts values between 0 and 100 Default 100 |
__mutationThrottlerRefillRate? | number | ADVANCED: alters the refill rate for the token bucket mutation throttling Normally only altered alongside posthog support guidance. Accepts values between 0 and 100 Default 10 |
attributeFilter? | string[] | ADVANCED: limit which DOM attributes are observed for mutations, by passing the list to the native MutationObserver attributeFilter. Mutations to unlisted attributes never reach the recorder at all, so they cost no recording CPU - useful to exclude high-frequency inline style mutations from JS-driven animations on animation-heavy pages. Attributes left off the list are invisible to replay, so only set this when that loss of fidelity is acceptable. When unset (the default) or set to an empty array, all attributes are observed. A list without id also stops captureJsonLd from keeping @id fragments. Normally only altered alongside posthog support guidance. |
blockClass? | string | RegExp | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-no-capture' |
blockSelector? | string | null | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default null |
canvasCapture? | object | Tune how canvas frames are captured for replay. Only has any effect when canvas recording is enabled. - resolutionScale: capture canvas frames at a fraction of their display resolution. A number in (0, 1]; 1 is full-resolution capture (the default) and, e.g., 0.6 captures at 60%. Out-of-range or non-finite values are clamped into (0, 1]. Aspect ratio is preserved and replay upscales the frame back to the original display size, so playback dimensions are unchanged, just softer. Resolution is the highest-leverage lever for canvas byte size, since bytes scale with pixel area. - maskRegionsFn: mask regions of a recorded canvas — see its doc comment. |
canvasCapture.maskRegionsFn? | ((canvas) => CanvasMaskRegion[] | null | undefined) | null | If set, called once per canvas per captured frame; the returned regions (CSS pixels, relative to the canvas element) are painted black before the frame is encoded. Lets apps that render into canvas (e.g. Flutter web) mask content that DOM-based masking cannot see. Re-read from config on every frame, so the real provider can be swapped in after recording has started. Return [] for a frame with nothing to mask (recorded as is), or null if regions could not be computed — that frame is skipped rather than recorded unmasked. Anything other than an array — null, a thrown error, or an implicit undefined from an untyped caller — skips that frame. Not setting this at all records the canvas unmasked. The provider is called for every canvas on the page, including canvases inside shadow DOM. For a canvas it does not manage, return [] ("nothing to mask") — returning null skips that canvas's frames entirely. Called synchronously on the main thread for every captured frame (canvas FPS is 4 by default, 12 max), so keep it cheap — avoid forcing layout, and return few regions. Setting this also changes DOM full snapshots (taken at recording start and at each full_snapshot_interval_millis): they normally serialize canvas pixels on a separate path (rr_dataURL) that never sees these regions, so when this option is set that serialization is skipped entirely. Whether to skip is re-evaluated at each snapshot, so a provider installed via set_config after recording started is honored at the next snapshot without a recorder restart. A canvas appears blank in a snapshot until the next canvas frame paints it — ~250ms at the default 4 fps while its pixels are changing, and at most 30s otherwise, because every canvas the provider answers (with regions or []) re-sends an unchanged frame as a keyframe every 30s; a canvas whose frames are skipped (null) stays blank. Without this option, snapshot behavior is unchanged. An app whose real provider only exists once its runtime has booted picks what happens in between by what it declares in posthog.init: a function covering the whole canvas blacks those frames out, () => null skips them, and declaring nothing records them. Client-side only, cannot be set via remote configuration. Default undefined |
canvasCapture.resolutionScale? | number | - |
captureCanvas? | SessionRecordingCanvasOptions | Allows local config to override remote canvas recording settings from the flags response. To mask content inside a recorded canvas, see canvasCapture.maskRegionsFn. |
captureJsonLd? | boolean | Captures sanitized Schema.org JSON-LD as session replay custom events. JSON-LD inside a text mask or blocked element is never captured. The recorder keeps properties on its universal safe list at every depth. This list includes @type values shaped like a Schema.org term, which means letters and digits only. It drops property branches that are not on the allowlist. Retained strings starting with http://, https://, //, /, ./, or ../ use replay URL masking, including query parameter and hash settings. This applies to nested entities and scalar arrays, but not to the fixed @context, normalized @type, or captured DOM IDs. Other strings, including bare relative paths and URLs embedded in text, are unchanged. A URL rejected by the masking callback is omitted. If the callback throws, the script is not captured. It keeps an @id as a fragment only when replay also captures a DOM element with the same id value. It drops every @id when maskAllElementAttributes, maskAttributeFn, or an attributeFilter without id can hide id attributes from replay. It also keeps the containing entity tree, even when it redacts all other fields. The event tag is $json_ld. The payload is a JSON-LD object or array. The event includes the current page URL in data.href, subject to replay URL masking and hash capture settings. The URL is omitted when the masking callback rejects it or throws. The recorder removes all script nodes from snapshots when this option is enabled. The JSON-LD observer starts only when this option is true at recording start. See https://github.com/PostHog/posthog-js/blob/main/packages/browser/src/extensions/replay/external/json-ld.ts Default false before the 2026-08-30 defaults, otherwise true |
collectFonts? | boolean | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false |
compress_events? | boolean | ADVANCED: whether to partially compress rrweb events before sending them to the server, defaults to true, can be set to false to disable partial compression NB requests are still compressed when sent to the server regardless of this setting Default true |
full_snapshot_interval_millis? | number | ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable Default 1000 * 60 * 5 (5 minutes) |
ignoreClass? | string | RegExp | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-ignore-input' |
inlineStylesheet? | boolean | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default true |
inlineStylesheetBudgetRules? | number | Max CSSRules inlined synchronously per full snapshot. Sheets past the budget keep their rel/href and are inlined across idle callbacks instead of blocking the snapshot; the queue is flushed synchronously (bounded) when recording stops and on pagehide. The residual risk: replay falls back to loading a sheet from its original href (which may be purged, auth-gated, or renamed by replay time) only if the tab dies without pagehide firing, the teardown flush hits its safety cap, or stringifying the sheet fails. The default is applied by posthog-js when it starts the recorder; the recorder itself is unbounded without it. Set 0 to inline everything up front (the pre-budget behaviour). Default 10000 |
maskAllElementAttributes? | boolean | Derived from rrweb.record options. Masks every string-valued source DOM attribute, including rendering attributes such as class, id, style, src, href, and synthesized form values. Only rrweb-generated layout metadata is retained, so this option intentionally reduces replay fidelity. Mutually exclusive with maskAttributeFn: when both are set this option wins and the callback is ignored. See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false |
maskAllInputs? | boolean | Derived from rrweb.record options. When true (the default) session replay masks the value of every input, except file inputs, whose values are recorded unmasked — block those with ph-no-capture or blockSelector if they hold sensitive data. Set it to false to record input values, which is not recommended for apps that handle sensitive data. A session_recording masking option set in posthog.init takes precedence over the project "Privacy and masking" setting; the SDK warns once when the two differ. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy Default true |
maskAttributeFn? | ((name, value, element?) => string) | null | Derived from rrweb.record options. Called with (name, value, element) for every non-empty string-valued attribute in the final serialized representation so you can mask specific attributes. Returning the original value leaves it visible. Mutually exclusive with maskAllElementAttributes: when both are set that option wins and this callback is ignored, so a callback cannot accidentally unmask what the coarse option hides. See https://github.com/rrweb-io/rrweb/blob/master/guide.md |
maskCapturedNetworkRequestFn? | ((data) => CapturedNetworkRequest | null | undefined) | null | Modify the network request before it is captured. Returning null or undefined stops it being captured. Initial navigation and performance-timing entries are also passed to this function. They have isInitial === true, can have method === undefined, and contain the page URL in name. If the function returns null or undefined for an initial entry, PostHog retains the replay-required timing metadata but omits its URL, headers, and body. Return a modified entry to retain a redacted URL. |
maskInputFn? | ((text, element?) => string) | null | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md |
maskInputOptions? | Partial<MaskInputOptions> | Derived from rrweb.record options. Selects which input types to mask by input attribute, for use when maskAllInputs is false. Password inputs are always masked by default: the SDK adds password: true to a partial override, so set password: false explicitly if you must record password fields. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy |
maskNetworkRequestFn? | ((data) => NetworkRequest | null | undefined) | null | Deprecated - use maskCapturedNetworkRequestFn instead |
maskTextClass? | string | RegExp | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-mask' |
maskTextFn? | ((text, element?) => string) | null | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md |
maskTextSelector? | string | null | Derived from rrweb.record options. A CSS selector for non-input text to mask in session replay. Session replay masks input values by default (see maskAllInputs), but it does not mask other DOM text or images. This selector and the ph-mask class mask text content only — for example a rendered card number — and do not hide an image, whose src is still recorded. To redact a rendered image such as a scanned document, block the image or a container element with ph-no-capture (see blockClass/blockSelector), which replaces it with a placeholder and stops recording its subtree. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy |
recordBody? | boolean | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false |
recordCrossOriginIframes? | boolean | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false |
recordHeaders? | boolean | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false |
sampleRate? | number | The sample rate for session recordings, a number between 0 and 1. For example, 0.5 means roughly 50% of sessions will be recorded. When undefined, falls back to the remote config setting. When set, takes precedence over the remote config. Default undefined |
sampling? | SessionRecordingSamplingConfig | Derived from rrweb.record options. Controls how often certain event types are captured within an already-recorded session, e.g. { mousemove: false } stops recording mouse movement. Not to be confused with sampleRate below, which controls whether a session is recorded at all, or with posthog.startSessionRecording({ sampling: true }), which overrides that session-level sample rate. NB disabled event types no longer count as user activity for replay idle detection (session_idle_threshold_ms). For example, with mousemove: false pure mouse movement no longer keeps a session active, while clicks, scrolls, and inputs still do. See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default undefined |
session_idle_threshold_ms? | number | ADVANCED: Controls when session recording considers the user idle. If no replay user interaction occurs for this many milliseconds, the recorder marks the recording idle, emits a sessionIdle replay marker, flushes buffered replay events, and drops most subsequent replay events until user activity resumes. If activity resumes before session_idle_timeout_seconds, recording continues under the same $session_id. This does not control $session_id rotation. Session rotation is controlled by session_idle_timeout_seconds, so this value should be lower than session_idle_timeout_seconds * 1000. Default 1000 * 60 * 5 (5 minutes) |
slimDOMOptions? | true | Partial<SlimDOMOptions> | "all" | Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default {} |
streamNetworkBody? | boolean | When recording network bodies, read them through a streaming reader that stops at the payload size limit instead of buffering the whole body and then discarding it. Bounds the memory and pre-request latency of capturing a very large body. Reads only a clone of the body, never the stream the page consumes. Default false |
strictMinimumDuration? | boolean | When true, minimum duration is checked against the actual buffer data (first to last timestamp) rather than session duration. This ensures recordings are not sent until they contain the minimum duration of actual data, even across page navigations. Default false |
trigger_pending_buffer_interval_millis? | number | ADVANCED: controls how much recent replay data is kept in memory while session recording waits for a conditional trigger. The recorder periodically takes a full snapshot and discards older buffered events, so increasing this interval retains more pre-trigger history but can increase memory usage and CPU usage. Performance impacts on your site can start to be visible to users with larger values. Values must be between 1,000 ms and 3,600,000 ms (1 hour, inclusive); values outside this range, or non-finite values, are ignored. Default 1000 * 60 (1 minute) |
SessionRecordingPersistedConfig
SessionRecordingPersistedConfig =
Omit<SessionRecordingRemoteConfig,"recordCanvas"|"canvasFps"|"canvasQuality"|"networkPayloadCapture"|"sampleRate"|"minimumDurationMilliseconds"> &object
the config stored in persistence when session recording remote config is received
Type Declaration
| Name | Type | Description |
|---|---|---|
cache_timestamp? | number | Used to determine if the persisted config is still valid or we need to wait for a new one only accepts undefined since older versions of the library didn't set this. |
canvasRecording | object | - |
canvasRecording.enabled | SessionRecordingRemoteConfig["recordCanvas"] | - |
canvasRecording.fps | SessionRecordingRemoteConfig["canvasFps"] | - |
canvasRecording.quality | SessionRecordingRemoteConfig["canvasQuality"] | - |
enabled | boolean | - |
minimumDurationMilliseconds | number | null | undefined | - |
networkPayloadCapture | SessionRecordingRemoteConfig["networkPayloadCapture"] & object | - |
sampleRate | number | null | - |
SessionRecordingRemoteConfig
SessionRecordingRemoteConfig =
SessionRecordingCanvasOptions&object
Type Declaration
| Name | Type | Description |
|---|---|---|
consoleLogRecordingEnabled? | boolean | - |
endpoint? | string | - |
eventTriggers? | string[] | - |
linkedFlag? | string | FlagVariant | null | - |
masking? | Pick<SessionRecordingOptions, "maskAllInputs" | "maskTextSelector" | "blockSelector" | "maskAllElementAttributes"> | - |
minimumDurationMilliseconds? | number | - |
networkPayloadCapture? | Pick<NetworkRecordOptions, "recordBody" | "recordHeaders"> | - |
sampleRate? | string | null | - |
scriptConfig? | object | - |
scriptConfig.script? | string | - |
triggerGroups? | SessionRecordingTriggerGroup[] | V2 Trigger Groups - multiple named trigger groups with their own conditions and sample rates. Only used when version === 2. |
triggerMatchType? | "any" | "all" | Controls how event, URL, sampling, and linked flag triggers are combined. any means that if any of the triggers match, the session will be recorded. all means that all the triggers must match for the session to be recorded. |
urlBlocklist? | SessionRecordingUrlTrigger[] | - |
urlTriggers? | SessionRecordingUrlTrigger[] | - |
version? | 1 | 2 | Config version - defaults to 1 (legacy). When version is 2, triggerGroups is used instead of individual trigger fields. |
SessionRecordingSamplingConfig
Sampling options for session recording, a subset of rrweb's sampling strategy
Properties
SessionRecordingTriggerGroup
V2 Trigger Group - represents a single trigger group with its own conditions and sample rate
Properties
SessionRecordingTriggerPropertyFilter
SessionRecordingUrlTrigger
SessionStartReason
SessionStartReason =
"sampling_overridden"|"recording_initialized"|"linked_flag_matched"|"linked_flag_overridden"| typeofSAMPLED|"session_id_changed"|"url_trigger_matched"|"event_trigger_matched"
SeverityLevel
SeverityLevel =
"fatal"|"error"|"warning"|"log"|"info"|"debug"
ShowTourOptions
SiteApp
SiteApp =
object
Properties
SiteAppGlobals
SiteAppGlobals =
object
Properties
SiteAppLoader
SiteAppLoader =
object
Properties
SlimDOMOptions
Slim DOM options for session recording
Properties
SnippetArrayItem
SnippetArrayItem = [
method:string,args:any[]]
SpecificQuestionBranching
SupportedWebVitalsMetrics
SupportedWebVitalsMetrics =
"LCP"|"CLS"|"FCP"|"INP"
Survey
A survey definition returned as part of browser remote config.
Properties
SurveyActionType
SurveyAppearance
Browser survey appearance, including browser-only placement and rendering options.
Extends
Omit<SurveyAppearance,"position"|"widgetType">
Properties
SurveyAppearance
SurveyAppearance =
object
Properties
SurveyCallback
SurveyCallback = (
surveys,context?) =>void
Parameters
| Parameter | Type |
|---|---|
surveys | Survey[] |
context? | { error?: string; isLoaded: boolean; } |
context.error? | string |
context.isLoaded | boolean |
Returns
void
SurveyConfig
SurveyConfig
Survey configuration options
Properties
SurveyElement
SurveyEventName
SurveyEventName = typeof
SurveyEventName[keyof typeofSurveyEventName]
SurveyEventProperties
SurveyEventProperties = typeof
SurveyEventProperties[keyof typeofSurveyEventProperties]
SurveyEventType
SurveyEventType = typeof
SurveyEventType[keyof typeofSurveyEventType]
SurveyEventWithFilters
SurveyMatchType
SurveyMatchType = typeof
SurveyMatchType[keyof typeofSurveyMatchType]
SurveyPosition
SurveyPosition = typeof
SurveyPosition[keyof typeofSurveyPosition]
SurveyPosition
SurveyPosition = typeof
SurveyPosition[keyof typeofSurveyPosition]
SurveyQuestion
SurveyQuestion =
BasicSurveyQuestion|LinkSurveyQuestion|RatingSurveyQuestion|MultipleSurveyQuestion
SurveyQuestionBase
BasicSurveyQuestionLinkSurveyQuestionRatingSurveyQuestionMultipleSurveyQuestion
Properties
SurveyQuestionBranchingType
SurveyQuestionBranchingType = typeof
SurveyQuestionBranchingType[keyof typeofSurveyQuestionBranchingType]
SurveyQuestionDescriptionContentType
SurveyQuestionDescriptionContentType =
"html"|"text"
SurveyQuestionDescriptionContentType
SurveyQuestionDescriptionContentType = typeof
SurveyQuestionDescriptionContentType[keyof typeofSurveyQuestionDescriptionContentType]
SurveyQuestionTranslation
SurveyQuestionType
SurveyQuestionType = typeof
SurveyQuestionType[keyof typeofSurveyQuestionType]
SurveyRenderReason
Represents the result of checking if a survey can be rendered.
Properties
SurveyResponseValue
SurveyResponseValue =
SurveyResponseValue
SurveyResponseValue
SurveyResponseValue =
string|number|string[] |null
SurveySchedule
SurveySchedule = typeof
SurveySchedule[keyof typeofSurveySchedule]
SurveyTabPosition
SurveyTabPosition = typeof
SurveyTabPosition[keyof typeofSurveyTabPosition]
SurveyTranslation
SurveyType
SurveyType = typeof
SurveyType[keyof typeofSurveyType]
SurveyValidationRule
SurveyValidationType
SurveyValidationType = typeof
SurveyValidationType[keyof typeofSurveyValidationType]
SurveyWidgetType
SurveyWidgetType = typeof
SurveyWidgetType[keyof typeofSurveyWidgetType]
SurveyWidgetType
SurveyWidgetType = typeof
SurveyWidgetType[keyof typeofSurveyWidgetType]
SurveyWithTypeAndAppearance
SurveyWithTypeAndAppearance =
Pick<Survey,"id"|"type"|"appearance">
Ticket
A support ticket in the conversations system
Properties
TicketStatus
TicketStatus =
"new"|"open"|"pending"|"on_hold"|"resolved"
Status of a support ticket
TipTapDoc
TipTap document - the root node of rich content
Properties
TipTapMark
TipTap mark types for inline formatting
Properties
TipTapNode
TipTap node representing content in the document tree
Properties
ToolbarParams
Parameters for loading the PostHog toolbar
Properties
ToolbarSource
ToolbarSource =
"url"|"localstorage"
ToolbarUserIntent
ToolbarUserIntent =
"add-action"|"edit-action"
Toolbar types
ToolbarVersion
ToolbarVersion =
"toolbar"
TreeShakeable
TreeShakeable<
T> ="optional"extends keyofTreeShakeableConfig?T|undefined:T
For the full bundle (default), resolves to T (extensions guaranteed present). For the slim bundle (augmented with { optional: true }), resolves to T | undefined.
Type Parameters
UserProvidedTraits
User-provided identification data (collected via the widget form)
Properties
WebMCPCaptureConfig
Selects the WebMCP metadata that PostHog captures. Options are applied when a tool registers. Re-register a tool after changing these options.
Properties
WidgetPosition
WidgetPosition =
"bottom_left"|"bottom_right"|"top_left"|"top_right"
Position of the conversations widget on the screen.
Writable
Writable<
T> ={ -readonly [P in keyof T]: T[P] }





