PostHog JavaScript Web SDK 1.x
Getting started
The JavaScript Web SDK runs in the browser.
To send your first event, run the AI wizard, add the HTML snippet, or install posthog-js and call posthog.init once. The snippet and npm install need 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 AI wizard
Run the AI wizard in your project directory to detect your framework, install PostHog, and configure your project:
Install with the HTML snippet
Paste the snippet inside your site's <head> tags so PostHog loads on every page. Replace the project token and host with your own.
The snippet loads the latest SDK and calls init, so you can skip the package install and initialize steps below.
Install with a package manager
Initialize
See Configuration, Security, and Persistence for setup guides.
Capture an event
Identify a user
Pass this to your agent
Pass the link to the markdown version of this page to your agent as additional reference when you work.
Setup
posthog.init
Initialize a PostHog SDK instance with your project token and configuration options.
Parameters
| Parameter | Type | Description |
|---|---|---|
token | string | Your PostHog project token |
config? | Partial<PostHogConfig> | Configuration options overriding defaults |
name? | string | Optional name when running multiple PostHog instances |
Returns
PostHog
The initialized PostHog instance
Remarks
Call posthog.init() once on page load. If your app already knows the signed-in user at startup,
call posthog.identify() inside the loaded callback.
When you initialize extra named instances via the third name parameter, each instance is attached
to posthog[name] and returned directly. Disable autocapture: false on secondary instances so clicks
and pageviews aren't captured twice. See configuration options.
Examples
posthog.set_config
Updates the configuration of the PostHog instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | Partial<PostHogConfig> | A dictionary of new configuration values to update |
posthog.debug
Enables or disables debug mode for detailed logging.
Parameters
| Parameter | Type | Description |
|---|---|---|
debug? | boolean | If true, will enable debug mode. |
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
posthog.shutdown
Flushes any queued events and resolves once teardown is complete.
Returns
Promise<void>
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
posthog
The default PostHog JavaScript Web SDK singleton instance.
new 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
Events and properties
posthog.capture
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
To send a critical event right before page navigation or reload, pass { transport: 'sendBeacon', send_instantly: true }.
Passing transport: 'sendBeacon' alone chooses the transport without bypassing the batch queue, so add send_instantly: true when you cannot wait for the flush interval.
Examples
posthog.register
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 |
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_once
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 |
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
posthog.register_for_session
Registers super properties for the current session only.
Parameters
| Parameter | Type | Description |
|---|---|---|
properties | Properties | An associative array of properties to store about the user |
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.unregister
Removes a super property from persistent storage.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The name of the super property to remove |
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
Removes a session super property from the current session.
Parameters
| Parameter | Type | Description |
|---|---|---|
property | string | The name of the session super property to remove |
Remarks
This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.
Example
posthog.get_property
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
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.logger
Logger with convenience methods for each severity level.
Example
Returns
Logger
posthog.captureLog
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 |
Example
posthog.captureTraceFeedback
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. |
posthog.captureTraceMetric
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. |
Identity and groups
posthog.identify
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. |
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).
Under person_profiles: 'identified_only' (the default), calling identify, alias, group,
setPersonProperties, or createPersonProfile creates a person profile for the user.
Calling setPersonPropertiesForFlags or setGroupPropertiesForFlags does not create a person profile.
Examples
posthog.reset
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. |
Examples
posthog.setPersonProperties
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. |
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
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. |
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
posthog.createPersonProfile
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
Example
posthog.get_distinct_id
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
posthog.alias
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
posthog.group
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 |
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.getGroups
Returns the current groups.
Returns
Record<string, any>
The current groups
posthog.resetGroups
Resets only the group properties of the user currently logged in. Learn more about groups
Example
posthog.setInternalOrTestUser
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 excluding internal or test users from analytics. See how to filter internal users and create a cohort with $internal_or_test_user set.
Example
posthog.setIdentity
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 |
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
posthog.clearIdentity
Clear HMAC-based identity verification, reverting to anonymous mode.
Example
Feature flags
posthog.isFeatureEnabled
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, or the $experiment_exposure event of a config version 2 experiment split. 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
posthog.getFeatureFlag
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, or the $experiment_exposure event of a config version 2 experiment split. 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
posthog.getFeatureFlagResult
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, and also $experiment_exposure when a
config version 2 experiment split supplies the value.
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
posthog.getAllFeatureFlags
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.
posthog.onFeatureFlags
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
posthog.reloadFeatureFlags
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
Example
posthog.setPersonPropertiesForFlags
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. |
Examples
posthog.resetPersonPropertiesForFlags
Resets the person properties for feature flags.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
reloadFeatureFlags? | boolean | true | Whether to reload feature flags. |
Examples
posthog.setGroupPropertiesForFlags
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. |
Examples
posthog.resetGroupPropertiesForFlags
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. |
Example
posthog.updateFlags
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 | - |
Example
Session replay
posthog.startSessionRecording
Turns session recording on and sets 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 } |
Examples
posthog.stopSessionRecording
Turns session recording off and sets disable_session_recording to true.
Example
posthog.sessionRecordingStarted
Returns whether session recording is currently running.
Returns
boolean
Whether session recording is currently running.
Example
posthog.get_session_replay_url
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.get_session_id
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
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 | Called once a session ID is present or when it or the window ID changes. |
Returns
Unsubscribe function.
() => void
Example
Error tracking
posthog.captureException
Captures 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
Turns exception autocapture on and updates the capture_exceptions config option.
Parameters
| Parameter | Type | Description |
|---|---|---|
config? | ExceptionAutoCaptureConfig | optional configuration option to control the exception autocapture behavior |
Examples
posthog.stopExceptionAutocapture
Turns exception autocapture off by setting capture_exceptions to false.
Example
posthog.addExceptionStep
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. |
Example
Surveys
posthog.displaySurvey
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. |
Examples
posthog.getActiveMatchingSurveys
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. |
Example
posthog.getSurveys
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. |
Example
posthog.onSurveysLoaded
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.onActiveMatchingSurveysChanged
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.canRenderSurveyAsync
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.cancelPendingSurvey
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. |
Privacy and consent
posthog.opt_in_capturing
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. |
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
Opts the user out of data capturing and persistence.
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
posthog.has_opted_in_capturing
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
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
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 SDK is capturing events.
Remarks
Controlled by cookieless_mode, opt_out_persistence_by_default, and respect_dnt.
posthog.get_explicit_consent_status
Returns the explicit consent status of the user.
Returns
"granted" | "denied" | "pending"
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
posthog.clear_opt_in_out_capturing
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
SDK utils
sampleByDistinctId
Return a before_send hook that samples by distinct ID.
A given ID sends either all its events or none. A rate of 0.5 keeps roughly
half of distinct IDs, not half of each ID's events.
Import it from posthog-js/customizations and pass it to before_send.
Parameters
| Parameter | Type | Description |
|---|---|---|
percent | number | Fraction of IDs to keep, from 0 (none) to 1 (all). |
Returns
BeforeSendFn
Example
sampleBySessionId
Return a before_send hook that samples by session ID.
A given session sends either all its events or none. A rate of 0.5 keeps
roughly half of sessions, not half of each session's events.
Import it from posthog-js/customizations and pass it to before_send.
Parameters
| Parameter | Type | Description |
|---|---|---|
percent | number | Fraction of sessions to keep, from 0 (none) to 1 (all). |
Returns
BeforeSendFn
Example
sampleByEvent
Return a before_send hook that samples events with the listed names.
Other events are kept. Sampling applies to individual events.
Import it from posthog-js/customizations and pass it to before_send.
Parameters
| Parameter | Type | Description |
|---|---|---|
eventNames | string[] | Event names to sample. |
percent | number | Fraction of matching events to keep, from 0 (none) to 1 (all). |
Returns
BeforeSendFn
posthog.on
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: any[]) => 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.getEarlyAccessFeatures
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. |
Example
posthog.updateEarlyAccessFeatureEnrollment
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. |
Example
posthog.loadToolbar
Returns whether the toolbar loaded.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ToolbarParams | Toolbar parameters. |
Returns
boolean
Whether the toolbar loaded.
posthog.getPageViewId
Returns the current page view ID.
Returns
string | undefined
The current page view ID, or undefined if no page view has been captured.
posthog.flagsEndpointWasHit
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.version
The library version.
Configuration
PostHogConfig
Configuration options for the PostHog JavaScript SDK. https://posthog.com/docs/libraries/js/config
Properties
| Property | Type | Description |
|---|---|---|
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 The project setting can also turn autocapture off. Events are autocaptured only when both allow it. 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. When set, this overrides the project setting. When unset, the project setting applies. See Default undefined |
capture_heatmaps? | boolean | HeatmapConfig | Determines whether to capture heatmaps. When set, this overrides the project setting. When unset, the project setting applies. When the project limits heatmap capture to a list of URLs, heatmap data is only sent for matching URLs, even when this is set to true. Heatmap data is held until the project's setting is known. 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. Cookies hold about 4KB, so large values can cause 431 Request Header Fields Too Large errors. 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(). Synchronization happens on the tab's next PostHog activity, not immediately. A persistence write can adopt an identity without immediately reloading feature flags. When the SDK next processes that identity, such as before a capture, it clears identity-bound flag state and starts a reload. onFeatureFlags runs after that reload. If the session ID changes, onSessionId runs when the tab next checks its session. A synchronized reset() also clears event and session properties of the previous identity. When defaults is '2026-08-29' or later, this defaults to true. Requires posthog-js 1.418.0 or later. 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[] | Extends the list of user-agent substrings that PostHog blocks from capturing (case-insensitive). posthog-js already blocks Chrome-Lighthouse, but third-party SEO crawlers built on Lighthouse (such as Ahrefs or Semrush) often send an ordinary browser user agent. Add a substring unique to that tool rather than a full browser user-agent string so real visitors aren't blocked. Default [] |
custom_campaign_params | string[] | Used to extend the list of campaign parameters that are saved by default (such as utm_source and utm_medium). 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. Recording starts only when this option and the project setting both allow it. 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 |
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 |
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) => 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) => 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: PostHog) => 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 URL parameters that are masked, including other spellings of them such as Snapchat's ScCid. - - 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: RequestResponse) => void | A function that is called when a request to the PostHog API fails. |
on_xhr_error? | (failedRequest: XMLHttpRequest) => 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. PostHog stores the distinct ID, session ID, device ID, feature flags, super properties, and some config in the browser. - 'localStorage+cookie' stores essential state, such as the distinct ID, device ID and session ID, in a cookie, and other data in localStorage. cookie_persisted_properties adds custom properties to the cookie. - 'cookie' stores everything in a cookie. Cookies hold about 4KB, so many feature flags can cause 431 Request Header Fields Too Large errors. - 'localStorage' stores everything in localStorage. - 'sessionStorage' stores everything in sessionStorage. - 'memory' stores everything in page memory, so it lasts for one pageview. Call set_config to change the mode after init, for example when a user accepts cookies. 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) => 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) => 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. |
require_subresource_integrity? | boolean | Requires Subresource Integrity (SRI) for every extension script the SDK loads, such as recorder.js, surveys.js or web-vitals.js. When enabled, each extension loads only from the exact-version path /static/<sdk version>/<name>.js with integrity and crossOrigin = 'anonymous' set, using the SHA-384 hashes built into this SDK bundle. A missing hash, an integrity failure or a prepare_external_dependency_script hook that changes integrity or crossOrigin disables only that feature. The SDK never retries through the mutable legacy path, whatever strict_script_versioning says. The asset host, or a reverse proxy in front of it, must serve the scripts with CORS headers (Access-Control-Allow-Origin). This mode also disables site apps, overriding opt_in_site_apps, including site app code preloaded by the token-specific /array/<token>/array.js. It refuses the toolbar and the executable /array/<token>/config.js remote config, which is then fetched as JSON. The guarantee covers the extension scripts this SDK instance inserts, anchored in the SDK code you already trust: an npm build, or an array.js you pin yourself. Because the extension hashes are part of array.js, pinning it with data-core-integrity on an exact-version loader.js that itself has an integrity attribute pins every extension too. The token-specific /array/<token>/array.js changes with project configuration, so it cannot be pinned: use /static/<sdk version>/array.js, the loader or npm instead. The guarantee does not cover an unpinned initial loader, third-party widgets such as Intercom or Crisp, or a malicious release with valid hashes. Extensions share page globals, so if another PostHog instance or any other code on the page already ran unverified extension code, this instance reuses it and the guarantee does not hold. Default false |
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) => 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: Properties, event_name: string) => 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 |
AutocaptureCompatibleElement
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
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: 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 |
BeforeSendFn
Parameters
| Parameter | Type |
|---|---|
cr | CaptureResult |
Returns
CaptureResult | null
BeforeSendLogFn
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
BootstrapConfig
| Property | Type | Description |
|---|---|---|
distinctID? | string | null | Distinct ID to use before the SDK has loaded persisted identity. |
featureFlagPayloads? | Record<string, JsonType> | null | Feature flag payloads to use together with bootstrapped featureFlags. |
featureFlags? | Record<string, string | boolean> | null | Feature flag values to use immediately until the SDK fetches fresh values. |
isIdentifiedID? | boolean | null | Whether distinctID already identifies a known person profile. |
sessionID? | string | null | Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be: - unique to this user - a valid UUID v7 - the timestamp part must be <= the timestamp of the first event in the session - the timestamp of the last event in the session must be < the timestamp part + 24 hours |
CanvasMaskRegion
A rectangle to paint over a recorded canvas frame, in CSS pixels relative to the canvas element.
Properties
| Property | Type |
|---|---|
height | number |
width | number |
x | number |
y | number |
CapturedNetworkRequest
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
| Property | Type | Description |
|---|---|---|
attributes? | LogAttributes | Per-log attributes (request-specific context like order_id, duration_ms) |
body | string | The log message body (required) |
level? | LogSeverityLevel | Log severity level (default: 'info') |
span_id? | string | Span ID for correlation — 16 hex chars |
trace_flags? | number | W3C trace flags (default: 0) |
trace_id? | string | Trace ID for correlation — 32 hex chars |
CapturePageviewOptions
Selects which same-page URL changes automatically capture a $pageview.
Each option defaults to false when omitted.
Properties
| Property | Type | Description |
|---|---|---|
hash? | boolean | Capture a pageview when location.hash changes, unless disable_capture_url_hashes is enabled. |
path? | boolean | Capture a pageview when location.pathname changes. |
search? | boolean | Capture a pageview when location.search changes. |
CaptureResult
| Property | Type |
|---|---|
$set? | Properties |
$set_once? | Properties |
$unset? | string[] |
event | EventName |
properties | Properties |
timestamp? | Date |
uuid | string |
ConfigDefaults
Configuration defaults snapshot used by PostHogConfig.defaults.
Later dates include all earlier default changes. latest includes all changes in the loaded SDK version.
DeadClicksAutoCaptureConfig
Type Declaration
| Name | Type | Description |
|---|---|---|
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 |
DomAutocaptureEvents
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
| Property | Type | Description | Inherited from |
|---|---|---|---|
captureExtensionExceptions? | boolean | Decide whether exceptions thrown by browser extensions or by scripts injected by the browser itself (for example Firefox for iOS and Chrome for iOS user scripts) should be captured. When false, both categories are dropped before capture. Default false | - |
exception_steps? | ExceptionStepsConfig | Controls buffering and payload limits for exception steps added via addExceptionStep. | - |
exceptionRateLimiterBucketSize? | number | ADVANCED: alters the bucket size for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 10 | ExceptionRateLimiterConfig.exceptionRateLimiterBucketSize |
exceptionRateLimiterRefillRate? | number | ADVANCED: alters the refill rate for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 1 | ExceptionRateLimiterConfig.exceptionRateLimiterRefillRate |
release? | | { build?: undefined; id: string; name?: undefined; version?: undefined; } | { build?: string; id?: undefined; name: string; version: string; } | Release identity for manual and automatically captured exceptions only. Supply either a PostHog release id, or the name and version of a release that already exists in the project, as given to hog error-tracking through --release-name, --release-version, and optional --build. A Git commit SHA can be used as the version. This option does not create releases. Create the release first, for example with hog error-tracking release. Explicit event, session, or super-property release identity takes precedence over this option, which takes precedence over a build-injected release id. Name/version configuration sends $app_namespace, $app_version, and optional $app_build instead of $release_id. Blank or incomplete configuration is ignored. Values are trimmed. Example error_tracking: { release: { name: 'my-app', version: gitSha } } Default undefined | - |
EventName
ExceptionAutoCaptureConfig
Properties
| Property | Type | Description |
|---|---|---|
capture_console_errors? | boolean | Determines whether PostHog should capture console errors. Default false |
capture_unhandled_errors? | boolean | Determines whether PostHog should capture unhandled errors. Default true |
capture_unhandled_rejections? | boolean | Determines whether PostHog should capture unhandled promise rejections. Default true |
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
| Property | Type | Description |
|---|---|---|
exceptionRateLimiterBucketSize? | number | ADVANCED: alters the bucket size for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 10 |
exceptionRateLimiterRefillRate? | number | ADVANCED: alters the refill rate for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 1 |
ExceptionStepsConfig
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
| Property | Type | Description |
|---|---|---|
enabled? | boolean | Determines whether PostHog should collect exception steps and attach them to the next captured exception. Default true |
max_bytes? | number | The maximum UTF-8 byte budget for exception steps buffered in memory. Oldest steps are evicted when the budget is exceeded. Default 32768 (~32KB) |
ExternalIntegrationKind
Headers
Request-related types
HeatmapConfig
| Property | Type | Description |
|---|---|---|
flush_interval_milliseconds | number | How often to send batched data in $heatmap_data events If set to 0 or not set, sends using the default interval of 1 second Default 1000 |
HeatmapsRemoteConfig
| Property | Type |
|---|---|
captureMode? | "all" | "url_allowlist" |
urlAllowlist? | string[] |
urlAllowlistEnforced? | boolean |
InitiatorType
JsonRecord
Index Signature
JsonType
KnownEventName
These are known PostHog events that can be processed by the before_send hook.
PostHog does not rely on receiving 100% of these events for core calculations,
so it is safe to sample them to reduce volume.
KnownUnsafeEditableEvent
Known events that require extra care when editing in before_send because core PostHog features depend on them.
LogAttributes
LogAttributeValue
LogCaptureOptions
Options for the captureLog API and posthog.logger convenience methods.
Extended by
LogsConfigBrowserLogsConfig
Properties
| Property | Type | Description |
|---|---|---|
beforeSend? | BeforeSendLogFn | BeforeSendLogFn[] | Pre-send filter for log records, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a record (return null to drop) before it enters the rate cap or the buffer. |
environment? | string | The deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. |
flushIntervalMs? | number | Flush interval in milliseconds for batched log records. Default 3000 |
maxBufferSize? | number | Maximum number of log records to buffer before forcing a flush. The queue may grow beyond this while a flush is in flight (e.g. during a synchronous burst) and is bounded separately by the per-interval rate cap. Default 100 |
maxLogsPerInterval? | number | Maximum number of log records accepted per flush interval. Subsequent calls within the same window are dropped with a single warning, protecting against runaway loggers flooding the network. Also sizes the in-memory buffer's eviction backstop, so a window's worth of records is held while a flush is in flight; raising it raises the worst-case in-memory footprint. Default 1000 |
resourceAttributes? | LogAttributes | Additional resource attributes applied to all log records. These describe the service/deployment, not individual log entries. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. Example { 'host.name': 'web-01', 'cloud.region': 'us-east-1' } |
serviceName? | string | The service name for log records. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service' |
serviceVersion? | string | The service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. |
LogsConfig
Logs configuration options
Extends
LogCaptureOptions
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
beforeSend? | BeforeSendLogFn | BeforeSendLogFn[] | Pre-send filter for log records, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a record (return null to drop) before it enters the rate cap or the buffer. | LogCaptureOptions.beforeSend |
captureConsoleLogs? | boolean | Automatically capture console.* calls as structured log records. Review console output before enabling, as messages can include sensitive values written by your code or by third-party libraries. The project setting can also turn this on. Console logs are captured when either one enables them. Default undefined | - |
environment? | string | The deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. | LogCaptureOptions.environment |
flushIntervalMs? | number | Flush interval in milliseconds for batched log records. Default 3000 | LogCaptureOptions.flushIntervalMs |
maxBufferSize? | number | Maximum number of log records to buffer before forcing a flush. The queue may grow beyond this while a flush is in flight (e.g. during a synchronous burst) and is bounded separately by the per-interval rate cap. Default 100 | LogCaptureOptions.maxBufferSize |
maxLogsPerInterval? | number | Maximum number of log records accepted per flush interval. Subsequent calls within the same window are dropped with a single warning, protecting against runaway loggers flooding the network. Also sizes the in-memory buffer's eviction backstop, so a window's worth of records is held while a flush is in flight; raising it raises the worst-case in-memory footprint. Default 1000 | LogCaptureOptions.maxLogsPerInterval |
resourceAttributes? | LogAttributes | Additional resource attributes applied to all log records. These describe the service/deployment, not individual log entries. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. Example { 'host.name': 'web-01', 'cloud.region': 'us-east-1' } | LogCaptureOptions.resourceAttributes |
serviceName? | string | The service name for log records. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service' | LogCaptureOptions.serviceName |
serviceVersion? | string | The service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. | LogCaptureOptions.serviceVersion |
LogSeverityLevel
Log capture types
MaskInputOptions
Mask input options for session recording
Properties
| Property | Type |
|---|---|
color? | boolean |
date? | boolean |
datetime-local? | boolean |
email? | boolean |
hidden? | boolean |
month? | boolean |
number? | boolean |
password? | boolean |
range? | boolean |
search? | boolean |
select? | boolean |
tel? | boolean |
text? | boolean |
textarea? | boolean |
time? | boolean |
url? | boolean |
week? | boolean |
PerformanceCaptureConfig
| Property | Type | Description |
|---|---|---|
network_timing? | boolean | Works with session replay to use the browser's native performance observer to capture performance metrics |
web_vitals? | boolean | Use chrome's web vitals library to wrap fetch and capture web vitals When cookieless_mode is active, there is no client-side SessionIdManager; vitals are still captured. Nested $web_vitals_*_event payloads omit $session_id / $window_id; PostHog ingestion assigns $session_id server-side for cookieless traffic when project cookieless settings are enabled (same as other events). A boolean here overrides the project setting. When unset, the project setting applies. |
web_vitals_allowed_metrics? | SupportedWebVitalsMetrics[] | By default all 4 metrics are captured You can set this config to restrict which metrics are captured e.g. ['CLS', 'FCP'] to only capture those two metrics NB setting this does not override whether the capture is enabled Default ['LCP', 'CLS', 'FCP', 'INP'] |
web_vitals_attribution? | boolean | SupportedWebVitalsMetrics[] | Which web vitals metrics include attribution data. Attribution names the cause of a metric, such as the slow interaction target for INP or the load-phase breakdown for LCP, which is what makes a slow number diagnosable. Pass true to attribute all metrics, false for none, or an array to name them. The default attributes INP and LCP only. CLS is excluded by default because its attribution holds detached DOM nodes and can leak memory in single-page apps. Default ['INP', 'LCP'] |
web_vitals_delayed_flush_ms? | number | We delay flushing web vitals metrics to reduce the number of events we send This is the maximum time we will wait before sending the metrics Default 5000 |
Properties
Property
Common types shared across PostHog SDKs
RageclickConfig
| Property | Type | Description |
|---|---|---|
click_count? | number | Number of consecutive clicks within the timeout to qualify as a rage click. Default 3 |
content_ignorelist? | boolean | string[] | Controls automatic exclusion of elements by text content from rageclick detection. Useful for pagination buttons and other repeatedly-clicked UI elements. - true: Use the default keywords, which cover next/previous/prev wording and arrow glyphs such as '>', '<', '→', '←', '»', '«' - false: Disable content-based exclusion - string[]: Use custom keywords (max 29 items, otherwise use css_selector_ignorelist) Checks the text and aria-label of the clicked control (the nearest button, link or other interactive ancestor) against the keywords, case-insensitive. The label of a surrounding region is not checked, so a labelled wrapper does not suppress the controls inside it. The built-in word keywords (next/previous/prev/etc.) match whole words wherever they appear, even inside a list you pass yourself, so 'prev' doesn't suppress "Preview". Any other word keyword you add matches as a substring. Symbol-only keywords (e.g. '+', '-', '>') always match exactly, so they don't suppress text like "sign-up", "5 > 3", or "C++". Below the '2025-11-30' defaults, and in any set_config call, a rageclick object you pass replaces the default instead of merging with it, so set this property explicitly there to keep content filtering. Default undefined (true when defaults is '2025-11-30' or later; the default keywords plus the '+', '-', '−', '–' steppers when defaults is '2026-05-30' or later) |
css_selector_ignorelist? | string[] | List of CSS selectors to ignore rageclicks on e.g. ['.my-calendar-button'] 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 rageclick 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-rageclick If an element has .ph-no-capture, it will always be ignored by rageclick and autocapture |
ignore_text_selection? | boolean | Excludes text-editing surfaces (textarea, text-like inputs, and contenteditable elements) from rageclick detection, since rapid repeated clicks there are double/triple-click text selection rather than rage. Enabled by default from the 2026-05-30 config defaults onwards. Default false |
threshold_px? | number | Maximum pixel distance between clicks to still be considered a rage click. Default 30 |
timeout_ms? | number | Maximum time window (in milliseconds) between the first and last click. Default 1000 |
RequestQueueConfig
| Property | Type | Description |
|---|---|---|
flush_interval_ms? | number | ADVANCED - alters the frequency which PostHog sends events to the server. generally speaking this is only set when apps have automatic page refreshes, or very short visits. Defaults to 3 seconds when not set Allowed values between 250 and 5000 |
RequestResponse
| Property | Type |
|---|---|
error? | unknown |
json? | any |
statusCode | number |
text? | string |
SegmentEnrichmentFilterFn
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
Configuration for the PostHog Segment integration.
Properties
| Property | Type | Description |
|---|---|---|
analytics | SegmentAnalytics | The Segment analytics object. |
filterProperties? | SegmentEnrichmentFilterFn | SegmentEnrichmentFilterFn[] | A function or array of functions called with the properties generated by PostHog before they are added to a Segment event. Return the properties to add, or null to leave the original Segment event unenriched. Original Segment properties are not passed to these functions. They are merged afterward and take precedence over properties returned by this hook. If a function throws, the original Segment event is left unchanged. |
SessionRecordingCanvasOptions
Properties
| Property | Type | Description |
|---|---|---|
canvasFps? | number | null | If set, records the canvas at the given FPS Can be set in the remote configuration Limited between 0 and 12 When canvas recording is enabled, if this is not set locally, then remote config sets this as 4 Default null-ish |
canvasQuality? | string | null | If set, records the canvas at the given quality Can be set in the remote configuration Must be a string that is a valid decimal between 0 and 1 When canvas recording is enabled, if this is not set locally, then remote config sets this as "0.4" Default null-ish |
recordCanvas? | boolean | null | If set, records the canvas Default false |
SessionRecordingOptions
| Property | Type | Description |
|---|---|---|
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: HTMLCanvasElement) => 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: string, value: string, element?: 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) => 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: string, element?: HTMLElement) => 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) => 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: string, element?: HTMLElement) => 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 |
selectMaskingFn? | (element: HTMLSelectElement) => "masked" | "unmasked" | Opt in to explicit select selection masking, overriding the select category setting. Masked selects use maskInputFn for replacement text but omit selection identity metadata. Returning original text from maskInputFn still records that text, even when this policy returns 'masked'. The callback is responsible for sanitizing its output. Unmasked selects retain their choices, including duplicate-valued options. Masked native <selectedcontent> clones are omitted. Static option labels remain visible. Pointer events are not covered: clicks on options in listbox-style selects (multiple, size > 1 or a customizable picker) still record the clicked option and position. Block selects whose choices must stay private, for example with ph-no-capture. Omit this option to preserve legacy maskInputFn behavior. Use a pure policy. It is evaluated for input events, select subtree mutations and snapshots; changes to external state take effect at the next such capture. Keep the callback reference stable. Replacing it restarts recording and discards queued old-policy data; changing its return value does not require a restart. Pending buffers are not carried across page loads with this option, because callback compatibility cannot be verified across pages. Invalid return values and exceptions resolve to masked. Recording does not start if the loaded recorder or driver does not support this option. Policy transitions also require a matching replay player. |
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) |
SessionRecordingSamplingConfig
Sampling options for session recording, a subset of rrweb's sampling strategy
Properties
| Property | Type | Description |
|---|---|---|
mouseInteraction? | boolean | When false, disables capture of mouse interaction events (click, mouse up/down, hover, and touch start/end). NB replays will not show clicks when this is disabled. Default undefined |
mousemove? | number | boolean | Controls capture of mouse movement within a recorded session. false disables capture entirely; NB this also disables touchmove and drag capture. A number throttles capture so that positions are captured at most once every N milliseconds. When undefined (or true), rrweb's default applies: capture throttled to every 50ms. Default undefined |
SlimDOMOptions
Slim DOM options for session recording
Properties
| Property | Type |
|---|---|
comment? | boolean |
headFavicon? | boolean |
headMetaAuthorship? | boolean |
headMetaDescKeywords? | boolean |
headMetaHttpEquiv? | boolean |
headMetaRobots? | boolean |
headMetaSocial? | boolean |
headMetaVerification? | boolean |
headTitleMutations? | boolean |
headWhitespace? | boolean |
script? | boolean |
SupportedWebVitalsMetrics
SurveyConfig
| Property | Type | Description |
|---|---|---|
autoSubmitDelay? | number | Deprecated No longer used. Pre-filled responses are now sent immediately when partial responses are enabled, or all required questions have been pre-filled. |
autoSubmitIfComplete? | boolean | Deprecated No longer used. Surveys will automatically advance past prefilled questions with skipSubmitButton enabled. If partial response collection is enabled, partial responses for pre-filled questions will be submitted automatically on page load. |
prefillFromUrl? | boolean | Prefill survey responses from matching URL parameters. Default undefined |
WebMCPCaptureConfig
Selects the WebMCP metadata that PostHog captures. Options are applied when a tool registers. Re-register a tool after changing these options.
Properties
| Property | Type | Description |
|---|---|---|
intent? | boolean | Captures the agent's reason for the tool call. Enabled by default. |
model? | boolean | Captures the model identifier that the agent reports. Enabled by default. |
Types
ActionStepStringMatching
ActionStepType
| Property | Type | Description |
|---|---|---|
event? | string | null | - |
href? | string | null | - |
href_matching? | ActionStepStringMatching | null | Default StringMatching.Exact |
properties? | object[] | Property filters for action step matching. |
selector? | string | null | - |
selector_regex? | string | null | Pre-compiled regex pattern for matching selector against $elements_chain. |
tag_name? | string | Deprecated Only selector should be used now. |
text? | string | null | - |
text_matching? | ActionStepStringMatching | null | Default StringMatching.Exact |
url? | string | null | - |
url_matching? | ActionStepStringMatching | null | Default StringMatching.Contains |
BasicSurveyQuestion
SurveyQuestionBase
Properties
| Property | Type | Inherited from |
|---|---|---|
branching? | | NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching | SurveyQuestionBase.branching |
buttonText? | string | SurveyQuestionBase.buttonText |
description? | string | null | SurveyQuestionBase.description |
descriptionContentType? | SurveyQuestionDescriptionContentType | SurveyQuestionBase.descriptionContentType |
id? | string | SurveyQuestionBase.id |
optional? | boolean | SurveyQuestionBase.optional |
question | string | SurveyQuestionBase.question |
translations? | Record<string, SurveyQuestionTranslation> | SurveyQuestionBase.translations |
type | "open" | - |
validation? | SurveyValidationRule[] | SurveyQuestionBase.validation |
CaptureOptions
| Property | Type | Description |
|---|---|---|
$set? | Properties | Used when $identify is called Will set person properties overriding previous values |
$set_once? | Properties | Used when $identify is called Will set person properties but only once, it will NOT override previous values |
$unset? | string[] | Used to unset person properties |
send_instantly? | boolean | If set, sends the event immediately instead of adding it to the batched queue. The batched queue drains with sendBeacon when the page hides, and an immediate send does not use that queue. On an active page, the SDK keeps its normal transport so failed requests can be retried. By default this is fetch, which keeps small requests alive across a navigation, or XHR when fetch is unavailable. Once PostHog's own pagehide handler (or unload fallback) marks the page as unloading, the SDK prefers sendBeacon, unless an explicit transport, a required response, or request_headers prevent it. Captures from beforeunload or pagehide listeners that run before PostHog's handler still use their normal transport. This is best effort, not a guarantee: XHR and requests too large for fetch keepalive can be cancelled by navigation. To always use a beacon, set { transport: 'sendBeacon' }, but note that accepted beacons cannot report server failures to the SDK for retries. |
skip_client_rate_limiting? | boolean | If set, skips the client side rate limiting |
timestamp? | Date | If set, overrides the current timestamp. UTC is preferred; non-UTC input is converted to UTC. |
transport? | "XHR" | "fetch" | "sendBeacon" | If set, overrides the desired transport method |
uuid? | string | If set, overrides the auto-generated event uuid. The value must be a valid UUID; invalid values are ignored and a new UUID is generated. Useful for cross-source idempotency (e.g. a server webhook and a browser success page both firing for the same business transaction): emit both events with the same deterministic uuid so storage can eventually deduplicate them. Capture itself does not deduplicate resent events, and PostHog does not guarantee strict immediate deduplication. |
Compression
DisplaySurveyInlineOptions
DisplaySurveyOptionsBase
Properties
| Property | Type | Description | Overrides | Inherited from |
|---|---|---|---|---|
displayType | "inline" | How the survey should be displayed. Default DisplaySurveyType.Popover | DisplaySurveyOptionsBase.displayType | - |
ignoreConditions | boolean | Whether to bypass the survey's targeting and display conditions. Default false | - | DisplaySurveyOptionsBase.ignoreConditions |
ignoreDelay | boolean | Whether to bypass the survey's configured popup delay. Default false | - | DisplaySurveyOptionsBase.ignoreDelay |
initialResponses? | Record<number, SurveyResponseValue> | Pre-filled responses by question index (0-based). Only supported for popover surveys. | - | DisplaySurveyOptionsBase.initialResponses |
properties? | Properties | Additional properties to include in all survey events (shown, sent, dismissed). | - | DisplaySurveyOptionsBase.properties |
selector | string | CSS selector for the element where the inline survey should render. | - | - |
DisplaySurveyOptions
Options for posthog.displaySurvey().
DisplaySurveyOptionsBase
DisplaySurveyPopoverOptionsDisplaySurveyInlineOptions
Properties
| Property | Type | Description |
|---|---|---|
displayType | DisplaySurveyType | How the survey should be displayed. Default DisplaySurveyType.Popover |
ignoreConditions | boolean | Whether to bypass the survey's targeting and display conditions. Default false |
ignoreDelay | boolean | Whether to bypass the survey's configured popup delay. Default false |
initialResponses? | Record<number, SurveyResponseValue> | Pre-filled responses by question index (0-based). Only supported for popover surveys. |
properties? | Properties | Additional properties to include in all survey events (shown, sent, dismissed). |
DisplaySurveyPopoverOptions
Options for displaying a survey as a popover.
Extends
DisplaySurveyOptionsBase
Properties
| Property | Type | Description | Overrides | Inherited from |
|---|---|---|---|---|
displayType | "popover" | How the survey should be displayed. Default DisplaySurveyType.Popover | DisplaySurveyOptionsBase.displayType | - |
ignoreConditions | boolean | Whether to bypass the survey's targeting and display conditions. Default false | - | DisplaySurveyOptionsBase.ignoreConditions |
ignoreDelay | boolean | Whether to bypass the survey's configured popup delay. Default false | - | DisplaySurveyOptionsBase.ignoreDelay |
initialResponses? | Record<number, SurveyResponseValue> | Pre-filled responses by question index (0-based). Only supported for popover surveys. | - | DisplaySurveyOptionsBase.initialResponses |
position? | SurveyPosition | Override the survey's configured position. | - | - |
properties? | Properties | Additional properties to include in all survey events (shown, sent, dismissed). | - | DisplaySurveyOptionsBase.properties |
selector? | string | CSS selector for the element to position the survey next to (when position is NextToTrigger). | - | - |
skipShownEvent? | boolean | When true, survey shown events will not be emitted automatically. | - | - |
DisplaySurveyType
EarlyAccessFeature
A feature that isn't publicly available yet.
Properties
| Property | Type | Description |
|---|---|---|
description | string | - |
documentationUrl | string | null | - |
flagKey | string | null | - |
imageUrl? | string | null | URL of an image that shows the feature, such as a screenshot. Empty when the feature has no image. |
name | string | - |
payload | JsonType | - |
stage | "concept" | "alpha" | "beta" | - |
EarlyAccessFeatureCallback
Parameters
| Parameter | Type |
|---|---|
earlyAccessFeatures | EarlyAccessFeature[] |
EarlyAccessFeatureResponse
| Property | Type |
|---|---|
earlyAccessFeatures | EarlyAccessFeature[] |
EarlyAccessFeatureStage
EndBranching
| Property | Type |
|---|---|
type | "end" |
ErrorEventArgs
ErrorTrackingSuppressionRule
| Property | Type |
|---|---|
type | "AND" | "OR" |
values | ErrorTrackingSuppressionRuleValue[] |
ErrorTrackingSuppressionRuleValue
| Property | Type |
|---|---|
key | "$exception_types" | "$exception_values" |
operator | SurveyMatchType |
type | string |
value | string | string[] |
EvaluationReason
Properties
| Property | Type |
|---|---|
code | string |
condition_index | number | undefined |
description | string | undefined |
EventHandler
Parameters
| Parameter | Type |
|---|---|
event | Event |
Returns
boolean | void
FeatureFlagDetail
Properties
| Property | Type |
|---|---|
enabled | boolean |
failed? | boolean |
key | string |
metadata | FeatureFlagMetadata | undefined |
original_enabled? | boolean |
original_variant? | string |
reason | EvaluationReason | undefined |
variant | string | undefined |
FeatureFlagMetadata
Properties
| Property | Type | Description |
|---|---|---|
description | string | undefined | - |
has_experiment? | boolean | Whether the flag is linked to an experiment. Absent when the server does not report it. |
id | number | - |
original_payload? | JsonType | - |
payload | JsonType | undefined | - |
version | number | undefined | - |
FeatureFlagOptions
Options for feature flag lookup methods (getFeatureFlag, isFeatureEnabled, getFeatureFlagResult).
Properties
| Property | Type | Description |
|---|---|---|
fresh? | boolean | If true, only return values loaded from the server, not cached localStorage values. Returns undefined if flags haven't been loaded from the server yet. Defaults to false. |
send_event? | boolean | Whether to send a $feature_flag_called event. Defaults to true. |
FeatureFlagOverrideOptions
Properties
| Property | Type |
|---|---|
flags? | boolean | string[] | FeatureFlagOverrides |
payloads? | FeatureFlagPayloadOverrides |
suppressWarning? | boolean |
FeatureFlagOverrides
Index Signature
FeatureFlagPayloadOverrides
Index Signature
FeatureFlagResult
Result of evaluating a feature flag, including both the flag value and its payload.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
enabled | readonly | boolean | Whether the returned feature flag evaluation is enabled. false is a conclusive off result. |
key | readonly | string | The key of the feature flag |
payload | readonly | JsonType | undefined | The JSON payload associated with this flag, if any |
variant | readonly | string | undefined | The variant key if this is a multivariate flag, undefined for boolean flags |
FeatureFlagsCallback
Parameters
| Parameter | Type |
|---|---|
flags | string[] |
variants | Record<string, string | boolean> |
context? | { errorsLoading?: boolean; } |
context.errorsLoading? | boolean |
FlagVariant
Properties
| Property | Type |
|---|---|
flag | string |
variant | string |
IsFeatureEnabledOptions
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. |
LinkSurveyQuestion
SurveyQuestionBase
Properties
| Property | Type | Inherited from |
|---|---|---|
branching? | | NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching | SurveyQuestionBase.branching |
buttonText? | string | SurveyQuestionBase.buttonText |
description? | string | null | SurveyQuestionBase.description |
descriptionContentType? | SurveyQuestionDescriptionContentType | SurveyQuestionBase.descriptionContentType |
id? | string | SurveyQuestionBase.id |
link? | string | null | - |
optional? | boolean | SurveyQuestionBase.optional |
question | string | SurveyQuestionBase.question |
translations? | Record<string, SurveyQuestionTranslation> | SurveyQuestionBase.translations |
type | "link" | - |
validation? | SurveyValidationRule[] | SurveyQuestionBase.validation |
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-level detail. Verbose, only useful while diagnosing.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
error()
Error. Operation failed; the app may continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
fatal()
Fatal. Operation failed; the app likely cannot continue.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
info()
Informational. Normal app events worth recording.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
trace()
Lowest severity. Trace-level diagnostic detail.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
warn()
Warning. Something unexpected but non-fatal.
Parameters
| Parameter | Type |
|---|---|
body | string |
attributes? | LogAttributes |
MultipleSurveyQuestion
SurveyQuestionBase
Properties
| Property | Type | Inherited from |
|---|---|---|
branching? | | NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching | SurveyQuestionBase.branching |
buttonText? | string | SurveyQuestionBase.buttonText |
choices | string[] | - |
description? | string | null | SurveyQuestionBase.description |
descriptionContentType? | SurveyQuestionDescriptionContentType | SurveyQuestionBase.descriptionContentType |
hasOpenChoice? | boolean | - |
id? | string | SurveyQuestionBase.id |
optional? | boolean | SurveyQuestionBase.optional |
question | string | SurveyQuestionBase.question |
shuffleOptions? | boolean | - |
skipSubmitButton? | boolean | - |
translations? | Record<string, SurveyQuestionTranslation> | SurveyQuestionBase.translations |
type | "multiple_choice" | "single_choice" | - |
validation? | SurveyValidationRule[] | SurveyQuestionBase.validation |
NetworkRecordOptions
Properties
| Property | Type | Description |
|---|---|---|
initiatorTypes? | InitiatorType[] | - |
maskRequestFn? | (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined | - |
payloadHostDenyList? | string[] | some domains we should never record the payload for example other companies session replay ingestion payloads aren't super useful but are gigantic if this isn't provided we use a default list if this is provided - we add the provided list to the default list i.e. we never record the payloads on the default deny list |
payloadSizeLimitBytes | number | the maximum size of the request/response body to record NB this will be at most 1MB even if set larger |
performanceEntryTypeToObserve | string[] | the PerformanceObserver will only observe these entry types |
recordBody? | | boolean | string[] | { request: boolean | string[]; response: boolean | string[]; } | - |
recordHeaders? | | boolean | { request: boolean; response: boolean; } | - |
recordInitialRequests? | boolean | - |
recordPerformance? | boolean | whether to record PerformanceEntry events for network requests |
streamNetworkBody? | boolean | when true, read bodies through a streaming reader that stops at payloadSizeLimitBytes instead of buffering the whole body and then enforcing the limit. Reads only a clone of the body, so it never consumes the stream the page itself reads. Default false |
NextQuestionBranching
| Property | Type |
|---|---|
type | "next_question" |
OverrideFeatureFlagsOptions
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
PropertyFilters
PropertyMatchType
PropertyOperator
RatingSurveyQuestion
SurveyQuestionBase
Properties
| Property | Type | Inherited from |
|---|---|---|
branching? | | NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching | SurveyQuestionBase.branching |
buttonText? | string | SurveyQuestionBase.buttonText |
description? | string | null | SurveyQuestionBase.description |
descriptionContentType? | SurveyQuestionDescriptionContentType | SurveyQuestionBase.descriptionContentType |
display | "number" | "emoji" | - |
id? | string | SurveyQuestionBase.id |
lowerBoundLabel | string | - |
optional? | boolean | SurveyQuestionBase.optional |
question | string | SurveyQuestionBase.question |
scale | 2 | 3 | 5 | 7 | 10 | - |
skipSubmitButton? | boolean | - |
translations? | Record<string, SurveyQuestionTranslation> | SurveyQuestionBase.translations |
type | "rating" | - |
upperBoundLabel | string | - |
validation? | SurveyValidationRule[] | SurveyQuestionBase.validation |
RemoteConfigFeatureFlagCallback
Parameters
| Parameter | Type |
|---|---|
payload | JsonType |
RequestCallback
Parameters
| Parameter | Type |
|---|---|
response | RequestResponse |
ResetOptions
| Property | Type | Description |
|---|---|---|
bootstrap? | BootstrapConfig | Identity, feature flag, and session values to apply after resetting. |
resetDeviceID? | boolean | Whether to generate a new device ID as well as a new distinct ID. Default false |
ResponseBasedBranching
| Property | Type |
|---|---|
responseValues | Record<string, any> |
type | "response_based" |
SessionIdChangedCallback
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 | - |
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
| Property | Type |
|---|---|
name | string |
properties? | SessionRecordingTriggerPropertyFilter[] |
SessionRecordingTriggerGroup
V2 Trigger Group - represents a single trigger group with its own conditions and sample rate
Properties
| Property | Type |
|---|---|
conditions | object |
conditions.events? | SessionRecordingEventTrigger[] |
conditions.flag? | string | FlagVariant |
conditions.matchType | "all" | "any" |
conditions.properties? | SessionRecordingTriggerPropertyFilter[] |
conditions.urls? | SessionRecordingUrlTrigger[] |
id | string |
minDurationMs? | number |
name | string |
sampleRate | number |
SessionRecordingTriggerPropertyFilter
| Property | Type |
|---|---|
key | string |
operator? | | "regex" | "not_regex" | "exact" | "is_not" | "icontains" | "not_icontains" | "gt" | "lt" |
type | "event" | "person" |
value? | string | number | boolean | string[] |
SessionRecordingUrlTrigger
| Property | Type |
|---|---|
matching | "regex" |
url | string |
SessionStartReason
Why session recording started for the current session.
SeverityLevel
SpecificQuestionBranching
| Property | Type |
|---|---|
index | number |
type | "specific_question" |
Survey
A survey definition returned as part of browser remote config.
Properties
| Property | Type |
|---|---|
appearance | SurveyAppearance | null |
conditions | | { actions: | { values: SurveyActionType[]; } | null; cancelEvents: | { values: SurveyEventWithFilters[]; } | null; deviceTypes?: string[]; deviceTypesMatchType?: SurveyMatchType; events: | { repeatedActivation?: boolean; values: SurveyEventWithFilters[]; } | null; linkedFlagVariant?: string; seenSurveyWaitPeriodInDays?: number; selector?: string; url?: string; urlMatchType?: SurveyMatchType; } | null |
current_iteration | number | null |
current_iteration_start_date | string | null |
description? | string |
enable_partial_responses? | boolean | null |
end_date | string | null |
feature_flag_keys | object[] | null |
id | string |
internal_targeting_flag_key | string | null |
linked_flag_key | string | null |
name | string |
questions | SurveyQuestion[] |
schedule? | SurveySchedule | null |
start_date | string | null |
targeting_flag_key | string | null |
translations? | Record<string, SurveyTranslation> |
type | SurveyType |
SurveyActionType
| Property | Type |
|---|---|
id | number |
name | string | null |
steps? | ActionStepType[] |
SurveyAppearance
Browser survey appearance, including browser-only placement and rendering options.
Extends
Omit<SurveyAppearance,"position"|"widgetType">
Properties
| Property | Type | Description | Overrides | Inherited from |
|---|---|---|---|---|
allowGoBack? | boolean | - | - | Omit.allowGoBack |
autoDisappear? | boolean | - | - | Omit.autoDisappear |
backButtonText? | string | - | - | Omit.backButtonText |
backgroundColor? | string | - | - | Omit.backgroundColor |
borderColor? | string | - | - | Omit.borderColor |
boxPadding? | string | - | - | - |
descriptionTextColor? | string | Deprecated Not currently used. | - | - |
disableAutofocus? | boolean | - | - | - |
disabledButtonOpacity? | string | - | - | - |
displayIntroScreen? | boolean | - | - | Omit.displayIntroScreen |
displayThankYouMessage? | boolean | - | - | Omit.displayThankYouMessage |
fontFamily? | string | - | Omit.fontFamily | - |
hideCancelButton? | boolean | - | - | - |
inputBackground? | string | - | - | Omit.inputBackground |
inputBackgroundColor? | string | Deprecated Use inputBackground instead. | - | - |
inputTextColor? | string | - | - | Omit.inputTextColor |
introScreenButtonText? | string | - | - | Omit.introScreenButtonText |
introScreenDescription? | string | - | - | Omit.introScreenDescription |
introScreenDescriptionContentType? | SurveyQuestionDescriptionContentType | - | - | Omit.introScreenDescriptionContentType |
introScreenHeader? | string | - | - | Omit.introScreenHeader |
maxWidth? | string | - | - | - |
placeholder? | string | - | - | Omit.placeholder |
position? | SurveyPosition | - | - | - |
ratingButtonActiveColor? | string | - | - | Omit.ratingButtonActiveColor |
ratingButtonColor? | string | - | - | Omit.ratingButtonColor |
ratingButtonHoverColor? | string | - | - | - |
shuffleQuestions? | boolean | - | - | Omit.shuffleQuestions |
submitButtonColor? | string | - | - | Omit.submitButtonColor |
submitButtonText? | string | - | - | Omit.submitButtonText |
submitButtonTextColor? | string | - | - | Omit.submitButtonTextColor |
surveyPopupDelaySeconds? | number | - | - | Omit.surveyPopupDelaySeconds |
tabPosition? | SurveyTabPosition | - | - | - |
textColor? | string | - | - | Omit.textColor |
thankYouMessageCloseButtonText? | string | - | - | Omit.thankYouMessageCloseButtonText |
thankYouMessageDescription? | string | - | - | Omit.thankYouMessageDescription |
thankYouMessageDescriptionContentType? | SurveyQuestionDescriptionContentType | - | - | Omit.thankYouMessageDescriptionContentType |
thankYouMessageHeader? | string | - | - | Omit.thankYouMessageHeader |
whiteLabel? | boolean | - | - | - |
widgetColor? | string | - | - | Omit.widgetColor |
widgetLabel? | string | - | - | Omit.widgetLabel |
widgetSelector? | string | - | - | Omit.widgetSelector |
widgetType? | SurveyWidgetType | - | - | - |
zIndex? | string | - | - | - |
SurveyCallback
Parameters
| Parameter | Type |
|---|---|
surveys | Survey[] |
context? | { error?: string; isLoaded: boolean; } |
context.error? | string |
context.isLoaded | boolean |
SurveyElement
| Property | Type |
|---|---|
$el_text? | string |
attr_class? | string[] |
attr_id? | string |
attributes? | Record<string, any> |
event_id? | number |
group_id? | number |
href? | string |
nth_child? | number |
nth_of_type? | number |
order? | number |
tag_name? | string |
text? | string |
SurveyEventName
SurveyEventProperties
SurveyEventType
SurveyEventWithFilters
| Property | Type |
|---|---|
name | string |
propertyFilters? | PropertyFilters |
SurveyMatchType
SurveyPosition
SurveyQuestion
SurveyQuestionBase
BasicSurveyQuestionLinkSurveyQuestionRatingSurveyQuestionMultipleSurveyQuestion
Properties
| Property | Type |
|---|---|
branching? | | NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching |
buttonText? | string |
description? | string | null |
descriptionContentType? | SurveyQuestionDescriptionContentType |
id? | string |
optional? | boolean |
question | string |
translations? | Record<string, SurveyQuestionTranslation> |
validation? | SurveyValidationRule[] |
SurveyQuestionBranchingType
SurveyQuestionDescriptionContentType
SurveyQuestionTranslation
| Property | Type |
|---|---|
buttonText? | string |
choices? | string[] |
description? | string | null |
link? | string | null |
lowerBoundLabel? | string |
question? | string |
upperBoundLabel? | string |
SurveyQuestionType
SurveyRenderReason
Represents the result of checking if a survey can be rendered.
Properties
| Property | Type | Description |
|---|---|---|
disabledReason? | string | The reason why the survey cannot be rendered, if applicable |
visible | boolean | Whether the survey is visible/can be rendered |
SurveyResponseValue
SurveySchedule
SurveyTabPosition
SurveyTranslation
| Property | Type |
|---|---|
backButtonText? | string |
introScreenButtonText? | string |
introScreenDescription? | string |
introScreenHeader? | string |
name? | string |
submitButtonText? | string |
thankYouMessageCloseButtonText? | string |
thankYouMessageDescription? | string |
thankYouMessageHeader? | string |
SurveyType
SurveyValidationRule
| Property | Type |
|---|---|
errorMessage? | string |
type | SurveyValidationType |
value? | number |
SurveyValidationType
SurveyWidgetType
SurveyWithTypeAndAppearance
ToolbarParams
Parameters for loading the PostHog toolbar
Properties
| Property | Type | Description |
|---|---|---|
actionId? | number | Action ID to edit |
dataAttributes? | string[] | Data attributes to capture |
distinctId? | string | Distinct ID of the user |
featureFlags? | Record<string, string | boolean> | Feature flags |
instrument? | boolean | Whether to instrument |
source? | ToolbarSource | Source of the toolbar params |
temporaryToken? | string | Private temporary user token |
token? | string | Public posthog-js token |
toolbarVersion? | "toolbar" | Toolbar version |
userEmail? | string | Email of the user |
userIntent? | ToolbarUserIntent | User intent for the toolbar |
ToolbarSource
ToolbarUserIntent
Toolbar types





