Contents

Getting started

The JavaScript Web SDK runs in the browser.

To send your first event, add the HTML snippet to your site, or install posthog-js and call posthog.init once. Both take your project token and host from your project settings.

After init, PostHog captures pageviews and clicks by itself, so loading a page sends your first event to the Activity page in PostHog. Use capture for your own events.

For server-side JavaScript, use the Node.js SDK.

Install with the HTML snippet

The snippet is the quickest way to add PostHog to a website. Paste it inside your site's <head> tags, just before </head>, so PostHog loads on every page. Replace the project token and host with your own.

The snippet loads the latest SDK from PostHog and calls init, so you can skip the next two steps.

 1<script>
 2    !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
 3    posthog.init('<ph_project_api_key>', {
 4        api_host: 'https://us.i.posthog.com',
 5    })
 6</script>

Install with a package manager

 1npm install posthog-js

Initialize

 1import posthog from 'posthog-js'
 2
 3posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })

Capture an event

 1posthog.capture('signed_up', { plan: 'pro' })

Identify a user

 1posthog.identify('user_123', { email: 'user@example.com' })

Pin the snippet version

To pin the snippet, change /static/array.js to a major path such as /static/1/array.js or an exact path such as /static/1.380.0/array.js. Minor paths such as /static/1.380/array.js are not supported. Exact version paths never change, so your CDN or proxy can cache them for a long time. Keep cache times short for /static/array.js and /static/1/array.js.

Verify the SDK with Subresource Integrity

From posthog-js 1.445.0, each release publishes a manifest of SHA-384 hashes at /static/<SDK_VERSION>/integrity.json. The npm package includes the same manifest at dist/integrity.json.

 1curl --fail --silent --show-error --location \
 2  "https://us-assets.i.posthog.com/static/<SDK_VERSION>/integrity.json" \
 3  --output posthog-integrity.json

The files object in the manifest maps each asset to its hash. Store the hashes in your source code. Don't fetch them at page load. Then replace the inline snippet with the static loader. Set integrity to files["loader.js"] and data-core-integrity to files["array.js"].

 1<script
 2    src="https://us-assets.i.posthog.com/static/<SDK_VERSION>/loader.js"
 3    integrity="sha384-<LOADER_SHA384_BASE64_DIGEST>"
 4    data-core-integrity="sha384-<ARRAY_SHA384_BASE64_DIGEST>"
 5    data-project-token="<ph_project_api_key>"
 6    crossorigin="anonymous"
 7></script>

The loader reads its options from these attributes:

  • data-api-host sets your ingestion URL when you use a reverse proxy.
  • data-config takes your other init options as JSON.
  • data-defer-init="true" skips the automatic init, so you can call posthog.init yourself with function options.

A cross-origin asset proxy must preserve the CORS response headers from PostHog's asset host and serve the same approved script bytes. When upgrading, update the pinned version and both hashes together. A hash mismatch blocks execution. Don't retry without integrity.

The hashes cover only loader.js and array.js. They don't cover the recorder, surveys, toolbar, or config.js scripts. Use the manifest from the regional asset host you serve, because toolbar assets differ between regions.

Prevent runtime script downloads

Use a no-external build and set disable_external_dependency_loading: true on the first initialization of every SDK instance. See browser extension setup for no-external imports and feature trade-offs. The default posthog-js npm import can still download dependencies.

Don't combine this setup with the snippet, a tag-manager installation, or another permissively configured SDK copy. A no-external build doesn't remove shared loaders or renderers registered by another bundle.

With external loading disabled, the standard loader doesn't fetch executable config.js. Without preloaded configuration, the SDK requests configuration as JSON instead. Configuration, flags and events still use the network. Preventing script downloads doesn't sanitize remote HTML or disable bundled renderers.

Use samplers with the HTML snippet

Load the customization script before the snippet calls posthog.init. Adjust the host for your region or proxy:

 1<script src="https://us.i.posthog.com/static/customizations.full.js"></script>

Set the snippet's before_send option to posthogCustomizations.sampleByDistinctId(0.4) to keep about 40% of distinct IDs, or posthogCustomizations.sampleBySessionId(0.25) to keep about 25% of sessions. A given distinct ID or session sends either all its events or none.

Cookies in iframes

In an iframe on another site, browsers treat PostHog cookies as third-party cookies and can block them. Pass an ID from the parent page and call identify inside the iframe.

Enriched flag analytics

To add view and interaction charts to a flag's Usage tab, capture $feature_view when a user sees the feature and $feature_interaction when they use it.

 1posthog.capture('$feature_view', { feature_flag: flag })
 2
 3posthog.capture('$feature_interaction', {
 4    feature_flag: flag,
 5    $set: { [`$feature_interaction/${flag}`]: true },
 6})

Block Lighthouse traffic

posthog-js already skips browsers whose user agent contains Chrome-Lighthouse, ignoring case. Some tools built on Lighthouse, such as Ahrefs and Semrush, send an ordinary browser user agent instead, so PostHog can't tell them apart from real visitors. If one of them inflates your numbers, add a string that only its user agent contains to custom_blocked_useragents. The SDK sends nothing from a browser whose user agent contains one of these strings, ignoring case, so never add a full browser user agent: that also blocks real visitors on the same browser and platform.

 1posthog.init('<ph_project_api_key>', {
 2    custom_blocked_useragents: ['example-crawler'],
 3})

Use posthog in the browser console

Bundled apps often don't expose window.posthog. To reach the instance in Chrome or Firefox, set debug: true, find the [PostHog.js] Starting in debug mode log, expand the logged object, right-click this, and select Store as global variable. The instance is then available as temp1 in Chrome or temp0 in Firefox.

Setup

new PostHog(...)

new PostHog(): PostHog

Creates an uninitialized PostHog instance.

Returns

PostHog

Remarks

Most browser applications should use the default exported singleton and call posthog.init(). Construct a new instance only when you need to manage a separate SDK instance manually.

Example

 1const instance = new PostHog()
 2instance.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })

PostHog.init

init(token, config?, name?): PostHog

Initializes a new instance of the PostHog capturing object.

Parameters

Parameter Type Description
token string Your PostHog API token
config? Partial<PostHogConfig> A dictionary of config options to override
name? string The name for the new posthog instance that you want created

Returns

PostHog

The newly initialized PostHog instance

Remarks

All new instances are added to the main posthog object as sub properties (such as posthog.library_name) and also returned by this function. Learn more about configuration options

Examples

 1// basic initialization
 2posthog.init('<ph_project_api_key>', {
 3    api_host: '<ph_client_api_host>'
 4})
 1// multiple instances
 2posthog.init('<ph_project_api_key>', {}, 'project1')
 3posthog.init('<ph_project_api_key>', {}, 'project2')

PostHog.set_config

set_config(config): void

Updates the configuration of the PostHog instance.

Parameters

Parameter Type Description
config Partial<PostHogConfig> A dictionary of new configuration values to update

Returns

void

posthog

const posthog: PostHog

The default PostHog JavaScript Web SDK singleton instance.

Capture

PostHog.capture

capture(event_name, properties?, options?): CaptureResult | undefined

Captures an event with optional properties and configuration.

Parameters

Parameter Type Description
event_name EventName The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase')
properties? Properties | null Properties to include with the event describing the user or event details
options? CaptureOptions Optional configuration for the capture request

Returns

CaptureResult | undefined

The capture result containing event data, or undefined if capture failed

Remarks

You can capture arbitrary object-like values as events. Learn about capture best practices

Example

 1// basic event capture
 2posthog.capture('cta-button-clicked', {
 3    button_name: 'Get Started',
 4    page: 'homepage'
 5})

Identify

PostHog.clearIdentity

clearIdentity(): void

Clear HMAC-based identity verification, reverting to anonymous mode.

Returns

void

Example

 1posthog.clearIdentity()

PostHog.identify

identify(new_distinct_id?, userPropertiesToSet?, userPropertiesToSetOnce?): void

Associates a user with a unique identifier instead of an auto-generated ID. Learn more about identifying users

Parameters

Parameter Type Description
new_distinct_id? string A non-empty string that uniquely identifies a user.
userPropertiesToSet? Properties Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet.
userPropertiesToSetOnce? Properties Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.

Returns

void

Remarks

By default, PostHog assigns each user a randomly generated distinct_id. Use this method to replace that ID with your own unique identifier (like a user ID from your database).

Examples

 1// basic identification
 2posthog.identify('user_12345')
 1// identify with user properties
 2posthog.identify('user_12345', {
 3    email: 'user@example.com',
 4    plan: 'premium'
 5})
 1// identify with set and set_once properties
 2posthog.identify('user_12345',
 3    { last_login: new Date() },  // updates every time
 4    { signup_date: new Date() }  // sets only once
 5)

PostHog.setIdentity

setIdentity(distinctId, hash): void

Set HMAC-based identity verification.

Parameters

Parameter Type Description
distinctId string The verified user distinct_id
hash string HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings

Returns

void

Remarks

When set, products like conversations use server-verified identity (distinct_id + HMAC hash) instead of anonymous session identifiers. The hash should be computed server-side as HMAC-SHA256 of the distinct_id, signed with the Secret API key from Support settings. Project secret API keys (project settings) and personal API keys are rejected. Any additional signed identity claims are cleared because they are bound to the previously configured distinct_id.

Example

 1posthog.setIdentity('user_123', 'a1b2c3d4e5f6...')

Logs

PostHog.logger

get logger(): Logger

Logger with convenience methods for each severity level.

Example
 1posthog.logger.info('checkout completed', { order_id: 'ord_789' })
 2posthog.logger.error('payment failed', { error_code: 'E001' })
Returns

Logger

PostHog.captureLog

captureLog(options): void

Capture a log entry and send it to the PostHog logs endpoint.

Note: logs are not subject to the user agent (bot) filter that drops events, so they are still sent from sessions whose events are dropped.

Parameters

Parameter Type Description
options CaptureLogOptions The log entry options

Returns

void

Example

 1posthog.captureLog({
 2  body: 'checkout completed',
 3  level: 'info',
 4  attributes: { order_id: 'ord_789', amount_cents: 4999 },
 5})

Alias

PostHog.alias

alias(alias, original?): number | void | CaptureResult

Creates an alias linking two distinct user identifiers. Learn more about identifying users

Parameters

Parameter Type Description
alias string A unique identifier that you want to use for this user in the future.
original? string The current identifier being used for this user.

Returns

number | void | CaptureResult

The $create_alias capture result, -1 if alias matches the current distinct ID, -2 if aliasing would duplicate a People user, or void if person processing is disabled.

Remarks

PostHog will use this to link two distinct_ids going forward (not retroactively). Call this when a user signs up to connect their anonymous session with their account.

Examples

 1// link anonymous user to account on signup
 2posthog.alias('user_12345')
 1// explicit alias with original ID
 2posthog.alias('user_12345', 'anonymous_abc123')

Capture AI

PostHog.captureTraceFeedback

captureTraceFeedback(traceId, userFeedback): void

Capture written user feedback for a LLM trace. Numeric values are converted to strings.

Parameters

Parameter Type Description
traceId string | number The trace ID to capture feedback for.
userFeedback string The feedback to capture.

Returns

void

PostHog.captureTraceMetric

captureTraceMetric(traceId, metricName, metricValue): void

Capture a metric for a LLM trace. Numeric values are converted to strings.

Parameters

Parameter Type Description
traceId string | number The trace ID to capture the metric for.
metricName string The name of the metric to capture.
metricValue string | number | boolean The value of the metric to capture.

Returns

void

Capture exception

PostHog.captureException

captureException(error, additionalProperties?): CaptureResult | undefined

Capture a caught exception manually

Parameters

Parameter Type Description
error unknown The error or exception-like value to capture.
additionalProperties? Properties Any additional properties to add to the error event.

Returns

CaptureResult | undefined

The result of the capture, or undefined if exception capture is unavailable.

Examples

 1// Capture a caught exception
 2try {
 3  // something that might throw
 4} catch (error) {
 5  posthog.captureException(error)
 6}
 1// With additional properties
 2posthog.captureException(error, {
 3  customProperty: 'value',
 4  anotherProperty: ['I', 'can be a list'],
 5  ...
 6})

PostHog.startExceptionAutocapture

startExceptionAutocapture(config?): void

turns exception autocapture on, and updates the config option capture_exceptions to the provided config (or true)

Parameters

Parameter Type Description
config? ExceptionAutoCaptureConfig optional configuration option to control the exception autocapture behavior

Returns

void

Examples

 1// Start with default exception autocapture rules. No-op if already enabled
 2posthog.startExceptionAutocapture()
 1// Start and override controls
 2posthog.startExceptionAutocapture({
 3  // you don't have to send all of these (unincluded values will use the default)
 4  capture_unhandled_errors: true || false,
 5  capture_unhandled_rejections: true || false,
 6  capture_console_errors: true || false
 7})

PostHog.stopExceptionAutocapture

stopExceptionAutocapture(): void

turns exception autocapture off by updating the config option capture_exceptions to false

Returns

void

Example

 1// Stop capturing exceptions automatically
 2posthog.stopExceptionAutocapture()

Create person profile

PostHog.createPersonProfile

createPersonProfile(): void

Creates a person profile for the current user, if they don't already have one and config.person_profiles is set to 'identified_only'. Produces a warning and does not create a profile if config.person_profiles is set to 'never'. Learn more about person profiles

Returns

void

Example

 1posthog.createPersonProfile()

Debug

PostHog.debug

debug(debug?): void

Enables or disables debug mode for detailed logging.

Parameters

Parameter Type Description
debug? boolean If true, will enable debug mode.

Returns

void

Remarks

Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding ?__posthog_debug=true to the URL.

Examples

 1// enable debug mode
 2posthog.debug(true)
 1// disable debug mode
 2posthog.debug(false)

Exception steps

PostHog.addExceptionStep

addExceptionStep(message, properties?): void

Add a breadcrumb-like step that will be attached to the next captured exception.

Parameters

Parameter Type Description
message string The step message.
properties? Properties Additional context for this step.

Returns

void

Example

 1posthog.addExceptionStep('Checkout button clicked', {
 2  checkout_id: 'ch_123',
 3})

Get distinct ID

PostHog.get_distinct_id

get_distinct_id(): string

Returns the current distinct ID for the user.

Returns

string

The current distinct ID

Remarks

This is either the auto-generated ID or the ID set via identify(). The distinct ID is used to associate events with users in PostHog.

Examples

 1// get the current user ID
 2const userId = posthog.get_distinct_id()
 3console.log('Current user:', userId)
 1// use in loaded callback
 2posthog.init('token', {
 3    loaded: (posthog) => {
 4        const id = posthog.get_distinct_id()
 5        // use the ID
 6    }
 7})

Get feature flag

PostHog.getFeatureFlag

getFeatureFlag(key, options?): string | boolean | undefined

Gets the value of a feature flag for the current user.

Parameters

Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Optional lookup settings. If { send_event: false }, we won't send a $feature_flag_called event to PostHog. If { fresh: true }, we won't return cached values from localStorage - only values loaded from the server.

Returns

string | boolean | undefined

The feature flag value, or undefined if the flag is unavailable.

Remarks

Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values. An evaluated boolean flag returns true or false; undefined means no current evaluation is available for the key. Globally inactive flags are omitted from the remote /flags response, so after that response loads they are unavailable rather than represented by a false result.

Examples

 1// check boolean flag
 2if (posthog.getFeatureFlag('new-feature')) {
 3    // show new feature
 4}
 1// check multivariate flag
 2const variant = posthog.getFeatureFlag('button-color')
 3if (variant === 'red') {
 4    // show red button
 5}

Get feature flag payload

PostHog.getFeatureFlagPayload

getFeatureFlagPayload(key): JsonType

Get feature flag payload value matching key for user (supports multivariate flags).

Parameters

Parameter Type Description
key string Key of the feature flag.

Returns

JsonType

The feature flag payload.

Example

 1const betaFeature = posthog.getFeatureFlagResult('beta-feature')
 2if (betaFeature?.variant === 'some-value') {
 3     const someValue = betaFeature?.payload
 4     // do something
 5}

Deprecated

Use getFeatureFlagResult() instead

Get feature flag result

PostHog.getFeatureFlagResult

getFeatureFlagResult(key, options?): FeatureFlagResult | undefined

Get a feature flag evaluation result including both the flag value and payload.

A result with enabled: false is a conclusive off evaluation. undefined means no current evaluation is available for the key. This includes globally inactive flags, which are omitted from the remote /flags response.

By default, this method emits the $feature_flag_called event.

Parameters

Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Options for the feature flag lookup.

Returns

FeatureFlagResult | undefined

The feature flag result including key, enabled, variant, and payload.

Examples

 1const result = posthog.getFeatureFlagResult('my-flag')
 2if (result?.enabled) {
 3    console.log('Flag is enabled with payload:', result.payload)
 4}
 1// multivariate flag
 2const result = posthog.getFeatureFlagResult('button-color')
 3if (result?.variant === 'red') {
 4    showRedButton(result.payload)
 5}

Get feature flags

PostHog.getAllFeatureFlags

getAllFeatureFlags(): FeatureFlagResult[]

Returns all currently cached feature flags as FeatureFlagResults. This is a synchronous read of the flags from the last load (no network request); call reloadFeatureFlags() first to refresh. Conclusive off evaluations are included with enabled: false; keys omitted from the response, including globally inactive flags, are absent. Unlike getFeatureFlag(), this method does not send a $feature_flag_called event.

Returns

FeatureFlagResult[]

All loaded flags, or an empty array if none are loaded.

Get session ID

PostHog.get_session_id

get_session_id(): string

Returns the current session_id.

Returns

string

The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.

Remarks

This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.

PostHog.onSessionId

onSessionId(callback?): () => void

Register an event listener that runs whenever the session id or window id change. If there is already a session id, the listener is called immediately in addition to being called on future changes.

Can be used, for example, to sync the PostHog session id with a backend session.

Parameters

Parameter Type Description
callback? SessionIdChangedCallback The callback function will be called once a session id is present or when it or the window id are updated.

Returns

A function that can be called to unsubscribe the listener. E.g. Used by useEffect when the component unmounts.

() => void

Example

 1posthog.onSessionId(function(sessionId, windowId) { // do something })

Group

PostHog.getGroups

getGroups(): Record<string, any>

Returns the current groups.

Returns

Record<string, any>

The current groups

PostHog.group

group(groupType, groupKey, groupPropertiesToSet?): void

Associates the user with a group for group-based analytics. Learn more about groups

Parameters

Parameter Type Description
groupType string Group type (example: 'organization')
groupKey string Group key (example: 'org::5')
groupPropertiesToSet? Properties Optional properties to set for group

Returns

void

Remarks

Groups allow you to analyze users collectively (e.g., by organization, team, or account). This sets the group association for all subsequent events and reloads feature flags.

Examples

 1// associate user with an organization
 2posthog.group('organization', 'org_12345', {
 3    name: 'Acme Corp',
 4    plan: 'enterprise'
 5})
 1// associate with multiple group types
 2posthog.group('organization', 'org_12345')
 3posthog.group('team', 'team_67890')

PostHog.resetGroups

resetGroups(): void

Resets only the group properties of the user currently logged in. Learn more about groups

Returns

void

Example

 1posthog.resetGroups()

Is feature enabled

PostHog.isFeatureEnabled

isFeatureEnabled(key, options?): boolean

Checks if a feature flag is enabled for the current user.

Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions & object & object Optional lookup settings. If { send_event: false }, we won't send a $feature_flag_called event to PostHog. If { fresh: true }, we won't return cached values from localStorage - only values loaded from the server. If { defaultValue: false }, we return that value instead of undefined when the flag has no value.
Returns

boolean

Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

Remarks

Returns true or false when the flag has an evaluation value. A false result means the value evaluated off; it does not mean the SDK observed the flag's global active setting. Returns undefined when no current evaluation is available, unless defaultValue is given. Globally inactive flags are omitted from the remote /flags response and therefore have no value. This is a convenience method that treats any truthy value as enabled.

Examples
 1// simple feature flag check
 2if (posthog.isFeatureEnabled('new-checkout')) {
 3    showNewCheckout()
 4}
 1// disable event tracking
 2if (posthog.isFeatureEnabled('feature', { send_event: false })) {
 3    // flag checked without sending $feature_flag_called event
 4}

Call Signature

isFeatureEnabled(key, options?): boolean | undefined

Checks if a feature flag is enabled for the current user.

Parameters
Parameter Type Description
key string Key of the feature flag.
options? IsFeatureEnabledOptions Optional lookup settings. If { send_event: false }, we won't send a $feature_flag_called event to PostHog. If { fresh: true }, we won't return cached values from localStorage - only values loaded from the server. If { defaultValue: false }, we return that value instead of undefined when the flag has no value.
Returns

boolean | undefined

Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

Remarks

Returns true or false when the flag has an evaluation value. A false result means the value evaluated off; it does not mean the SDK observed the flag's global active setting. Returns undefined when no current evaluation is available, unless defaultValue is given. Globally inactive flags are omitted from the remote /flags response and therefore have no value. This is a convenience method that treats any truthy value as enabled.

Examples
 1// simple feature flag check
 2if (posthog.isFeatureEnabled('new-checkout')) {
 3    showNewCheckout()
 4}
 1// disable event tracking
 2if (posthog.isFeatureEnabled('feature', { send_event: false })) {
 3    // flag checked without sending $feature_flag_called event
 4}

Is opt out

PostHog.has_opted_in_capturing

has_opted_in_capturing(): boolean

Checks if the user has opted into data capturing.

Returns

boolean

current opt-in status

Remarks

Returns the current consent status for event tracking and data persistence.

Example

 1if (posthog.has_opted_in_capturing()) {
 2    // show analytics features
 3}

PostHog.has_opted_out_capturing

has_opted_out_capturing(): boolean

Checks if the user has opted out of data capturing.

Returns

boolean

current opt-out status

Remarks

Returns the current consent status for event tracking and data persistence.

In cookieless 'always' mode this returns true, because the SDK does not store data for the user. Events are still captured in this mode. To check if the SDK captures events, use is_capturing().

Example

 1if (posthog.has_opted_out_capturing()) {
 2    // disable analytics features
 3}

PostHog.is_capturing

is_capturing(): boolean

Checks whether the PostHog library is currently capturing events.

Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by some config options.

Additionally, if the cookieless_mode is set to 'on_reject', we will capture events in cookieless mode if the user has opted out or been defaulted to opt-out.

Returns

boolean

whether the posthog library is capturing events

See

Is session replay active

PostHog.sessionRecordingStarted

sessionRecordingStarted(): boolean

returns a boolean indicating whether session recording is currently running

Returns

boolean

Whether session recording is currently running.

Example

 1// Stop session recording if it's running
 2if (posthog.sessionRecordingStarted()) {
 3  posthog.stopSessionRecording()
 4}

On feature flags

PostHog.onFeatureFlags

onFeatureFlags(callback): () => void

Register an event listener that runs when feature flags become available or when they change. If there are flags, the listener is called immediately in addition to being called on future changes. Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser, including when another open tab of your site stores new flags. Do not call reloadFeatureFlags() inside this callback: each reload in one tab triggers the callback in the other tabs, which can send flag requests in a loop.

Parameters

Parameter Type Description
callback FeatureFlagsCallback The callback function will be called once the feature flags are ready or when they are updated. It'll return a list of feature flags enabled for the user, the variants, and also a context object indicating whether we succeeded to fetch the flags or not.

Returns

A function that can be called to unsubscribe the listener. Used by useEffect when the component unmounts.

() => void

Example

 1posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
 2    // do something
 3})

Opt in

PostHog.clear_opt_in_out_capturing

clear_opt_in_out_capturing(): void

Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance

Returns

void

PostHog.opt_in_capturing

opt_in_capturing(options?): void

Opts the user into data capturing and persistence.

Parameters

Parameter Type Description
options? { captureEventName?: false | EventName | null; captureProperties?: Properties; } A dictionary of opt-in options.
options.captureEventName? false | EventName | null Event name to use for capturing the opt-in action. Set to null or false to skip capturing the opt-in event. Defaults to $opt_in.
options.captureProperties? Properties Set of properties to capture along with the opt-in action.

Returns

void

Remarks

Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an $opt_in event unless disabled. The event is only captured when the user was not already opted in, so calling this on every page load (for example from a consent tool callback that re-applies stored consent) sends it once per user rather than once per page.

Examples

 1// simple opt-in
 2posthog.opt_in_capturing()
 1// opt-in with custom event and properties
 2posthog.opt_in_capturing({
 3    captureEventName: 'Privacy Accepted',
 4    captureProperties: { source: 'banner' }
 5})
 1// opt-in without capturing event
 2posthog.opt_in_capturing({
 3    captureEventName: false
 4})

PostHog.opt_out_capturing

opt_out_capturing(): void

Opts the user out of data capturing and persistence.

Returns

void

Remarks

Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance. If opt_out_persistence_by_default is true, SDK persistence will also be disabled.

Example

 1// opt user out (e.g., on privacy settings page)
 2posthog.opt_out_capturing()

Register

PostHog.get_property

get_property(property_name): any

Returns the value of a super property. Returns undefined if the property doesn't exist.

Parameters

Parameter Type Description
property_name string The name of the super property you want to retrieve

Returns

any

The stored property value, or undefined if it is not set.

Remarks

get_property() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.

Example

 1// grab value for '$user_id' after the posthog library has loaded
 2posthog.init('<YOUR PROJECT TOKEN>', {
 3    loaded: function(posthog) {
 4        user_id = posthog.get_property('$user_id');
 5    }
 6});

PostHog.getSessionProperty

getSessionProperty(property_name): any

Returns the value of the session super property named property_name. If no such property is set, getSessionProperty() will return the undefined value.

Parameters

Parameter Type Description
property_name string The name of the session super property you want to retrieve

Returns

any

The stored session property value, or undefined if it is not set.

Remarks

This is based on browser-level sessionStorage, NOT the PostHog session. getSessionProperty() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.

Example

 1// grab value for 'user_id' after the posthog library has loaded
 2posthog.init('YOUR PROJECT TOKEN', {
 3    loaded: function(posthog) {
 4        user_id = posthog.getSessionProperty('user_id');
 5    }
 6});

PostHog.register

register(properties, days?): void

Registers super properties that are included with all events.

Parameters

Parameter Type Description
properties Properties properties to store about the user
days? number How many days since the user's last visit to store the super properties

Returns

void

Remarks

Super properties are stored in persistence and automatically added to every event you capture. These values will overwrite any existing super properties with the same keys.

Examples

 1// register a single property
 2posthog.register({ plan: 'premium' })
 1// register multiple properties
 2posthog.register({
 3    email: 'user@example.com',
 4    account_type: 'business',
 5    signup_date: '2023-01-15'
 6})
 1// register with custom expiration
 2posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 days

PostHog.register_for_session

register_for_session(properties): void

Registers super properties for the current session only.

Parameters

Parameter Type Description
properties Properties An associative array of properties to store about the user

Returns

void

Remarks

Session super properties are automatically added to all events during the current browser session. Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage.

Examples

 1// register session-specific properties
 2posthog.register_for_session({
 3    current_page_type: 'checkout',
 4    ab_test_variant: 'control'
 5})
 1// register properties for user flow tracking
 2posthog.register_for_session({
 3    selected_plan: 'pro',
 4    completed_steps: 3,
 5    flow_id: 'signup_flow_v2'
 6})

PostHog.register_once

register_once(properties, default_value?, days?): void

Registers super properties only if they haven't been set before.

Parameters

Parameter Type Description
properties Properties An associative array of properties to store about the user
default_value? any Value to override if already set in super properties (ex: 'False') Default: 'None'
days? number How many days since the users last visit to store the super properties

Returns

void

Remarks

Unlike register(), this method will not overwrite existing super properties. Use this for properties that should only be set once, like signup date or initial referrer.

Examples

 1// register once-only properties
 2posthog.register_once({
 3    first_login_date: new Date().toISOString(),
 4    initial_referrer: document.referrer
 5})
 1// override existing value if it matches default
 2posthog.register_once(
 3    { user_type: 'premium' },
 4    'unknown'  // overwrite if current value is 'unknown'
 5)

Reload feature flags

PostHog.reloadFeatureFlags

reloadFeatureFlags(): void

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.

Returns

void

Example

 1posthog.reloadFeatureFlags()

Reset

PostHog.reset

reset(options?): void

Resets all user data and starts a fresh session.

⚠️ Warning: Only call this when a user logs out. Calling at the wrong time can cause split sessions.

This clears:

  • Session ID and super properties
  • User identification (sets new random distinct_id)
  • Cached data and consent settings

⚠️ Warning: because consent is cleared, reset() returns the instance to the default consent state. With opt_out_capturing_by_default that default is opted out, so calling reset() after opt_in_capturing() silently stops capturing. Always reset() first, then opt in.

Parameters

Parameter Type Description
options? boolean | ResetOptions Boolean to reset the device ID (legacy), or reset options including bootstrap values.

Returns

void

Examples

 1// reset on user logout
 2function logout() {
 3    posthog.reset()
 4    // redirect to login page
 5}
 1// reset and generate new device ID
 2posthog.reset(true)  // also resets device_id
 1// reset with a custom anonymous ID and bootstrapped feature flags
 2posthog.reset({
 3    bootstrap: {
 4        distinctID: myAnonymousID,
 5        isIdentifiedID: false,
 6        featureFlags: { 'my-flag': true },
 7    }
 8})
 1// with opt_out_capturing_by_default, reset() before opting in, never after
 2posthog.reset()
 3posthog.opt_in_capturing()

Reset group properties for flags

PostHog.resetGroupPropertiesForFlags

resetGroupPropertiesForFlags(group_type?): void

Resets the group properties for feature flags.

Parameters

Parameter Type Description
group_type? string Optional group type to reset. If omitted, all group properties are reset.

Returns

void

Example

 1posthog.resetGroupPropertiesForFlags()

Reset person properties for flags

PostHog.resetPersonPropertiesForFlags

resetPersonPropertiesForFlags(reloadFeatureFlags?): void

Resets the person properties for feature flags.

Parameters

Parameter Type Default value Description
reloadFeatureFlags? boolean true Whether to reload feature flags.

Returns

void

Examples

 1posthog.resetPersonPropertiesForFlags()
 1// Reset properties without reloading
 2posthog.resetPersonPropertiesForFlags(false)

Set group properties for flags

PostHog.setGroupPropertiesForFlags

setGroupPropertiesForFlags(properties, reloadFeatureFlags?): void

Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type.

Parameters

Parameter Type Default value Description
properties {[type: string]: Properties; } undefined The properties to override, the key of which is the group type.
reloadFeatureFlags? boolean true Whether to reload feature flags.

Returns

void

Examples

 1// Set properties with reload
 2posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })
 1// Set properties without reload
 2posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false)

Set person properties

PostHog.setInternalOrTestUser

setInternalOrTestUser(): void

Marks the current user as a test user by setting the $internal_or_test_user person property to true. This also enables person processing for the current user.

This is useful for using in a cohort your internal/test filters for your posthog org.

Returns

void

See

https://posthog.com/tutorials/filter-internal-users Create a cohort with $internal_or_test_user IS SET, and set your internal test filters to be NOT IN that cohort.

Example

 1// Manually mark as test user
 2posthog.setInternalOrTestUser()
 3
 4// Or use internal_or_test_user_hostname config for automatic detection
 5posthog.init('token', { internal_or_test_user_hostname: 'localhost' })

PostHog.setPersonProperties

setPersonProperties(userPropertiesToSet?, userPropertiesToSetOnce?): void

Sets properties on the person profile associated with the current distinct_id. Learn more about identifying users

Parameters

Parameter Type Description
userPropertiesToSet? Properties Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet.
userPropertiesToSetOnce? Properties Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.

Returns

void

Remarks

Updates user properties that are stored with the person profile in PostHog. If person_profiles is set to identified_only and no profile exists, this will create one.

Examples

 1// set user properties
 2posthog.setPersonProperties({
 3    email: 'user@example.com',
 4    plan: 'premium'
 5})
 1// set properties
 2posthog.setPersonProperties(
 3    { name: 'Max Hedgehog' },  // $set properties
 4    { initial_url: '/blog' }   // $set_once properties
 5)

PostHog.unsetPersonProperties

unsetPersonProperties(propertyNames): void

Removes properties from the person profile associated with the current distinct_id. Learn more about identifying users

Parameters

Parameter Type Description
propertyNames string | string[] The name (or names) of the person properties to remove.

Returns

void

Remarks

Deletes the given person properties from the person profile in PostHog. This is the counterpart to setPersonProperties — instead of hand-passing $unset inside a capture() call, you can remove properties with a dedicated method. If person_profiles is set to never, this call is ignored.

$fbc and $fbp read by the SDK are unset for this call only. save_campaign_params: false stops the reads.

Examples

 1// remove a single property
 2posthog.unsetPersonProperties('plan')
 1// remove multiple properties
 2posthog.unsetPersonProperties(['plan', 'email'])

Set person properties for flags

PostHog.setPersonPropertiesForFlags

setPersonPropertiesForFlags(properties, reloadFeatureFlags?): void

Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:

Parameters

Parameter Type Default value Description
properties Properties undefined The properties to override.
reloadFeatureFlags? boolean true Whether to reload feature flags.

Returns

void

Examples

 1// Set properties
 2posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})
 1// Set properties without reloading
 2posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

Shutdown

PostHog.shutdown

shutdown(_shutdownTimeoutMs?): Promise<void>

Flushes any queued events and resolves once teardown is complete.

Parameters

Parameter Type Description
_shutdownTimeoutMs? number Retained for parity with the Node.js SDK; ignored in browsers.

Returns

Promise<void>

A promise that resolves once best-effort cleanup and queue flushing complete.

Remarks

This exists primarily for parity with the server-side Node.js SDK, whose shutdown() you call once before a process exits. In the browser there is no process to exit, so this method performs synchronous best-effort extension cleanup, flushes the request queues, and always resolves.

It is safe to call in isomorphic teardown code (for example a Nuxt/Next module that calls shutdown() on both the server and the client) so the same symmetric cleanup works in either environment without throwing.

Example

 1// symmetric teardown that runs on both server and client
 2await posthog.shutdown()

Start session recording

PostHog.startSessionRecording

startSessionRecording(override?): void

turns session recording on, and updates the config option disable_session_recording to false

Parameters

Parameter Type Description
override? true | { event_trigger?: true; linked_flag?: boolean; sampling?: boolean; url_trigger?: true; } optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config. true is shorthand for { sampling: true, linked_flag: true }

Returns

void

Examples

 1// Start and ignore controls
 2posthog.startSessionRecording(true)
 1// Start and override controls
 2posthog.startSessionRecording({
 3  // you don't have to send all of these
 4  sampling: true || false,
 5  linked_flag: true || false,
 6  url_trigger: true || false,
 7  event_trigger: true || false
 8})

Stop session recording

PostHog.stopSessionRecording

stopSessionRecording(): void

turns session recording off, and updates the config option disable_session_recording to true

Returns

void

Example

 1// Stop session recording
 2posthog.stopSessionRecording()

Unregister

PostHog.unregister

unregister(property): void

Removes a super property from persistent storage.

Parameters

Parameter Type Description
property string The name of the super property to remove

Returns

void

Remarks

This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile.

Example

 1// remove a super property
 2posthog.unregister('plan_type')

PostHog.unregister_for_session

unregister_for_session(property): void

Removes a session super property from the current session.

Parameters

Parameter Type Description
property string The name of the session super property to remove

Returns

void

Remarks

This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.

Example

 1// remove a session property
 2posthog.unregister_for_session('current_flow')

get_explicit_consent_status(): "pending" | "granted" | "denied"

Returns the explicit consent status of the user.

Returns

"pending" | "granted" | "denied"

The current explicit consent status.

Remarks

This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not take the default config options into account, only whether the user has made an explicit choice, so this can be used to determine whether to show an initial cookie banner or not.

Example

 1const consentStatus = posthog.get_explicit_consent_status()
 2if (consentStatus === "granted") {
 3    // user has explicitly opted in
 4} else if (consentStatus === "denied") {
 5    // user has explicitly opted out
 6} else if (consentStatus === "pending"){
 7    // user has not made a choice, show consent banner
 8}

Surveys

PostHog.cancelPendingSurvey

cancelPendingSurvey(surveyId): void

Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).

Parameters

Parameter Type Description
surveyId string The survey ID whose pending display should be cancelled.

Returns

void

PostHog.canRenderSurvey

canRenderSurvey(surveyId): SurveyRenderReason | null

Checks the feature flags associated with this Survey to see if the survey can be rendered. This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded. Use canRenderSurveyAsync instead.

Parameters

Parameter Type Description
surveyId string The ID of the survey to check.

Returns

SurveyRenderReason | null

A SurveyRenderReason object indicating if the survey can be rendered.

Deprecated

PostHog.canRenderSurveyAsync

canRenderSurveyAsync(surveyId, forceReload?): Promise<SurveyRenderReason>

Checks the feature flags associated with this Survey to see if the survey can be rendered.

Parameters

Parameter Type Default value Description
surveyId string undefined The ID of the survey to check.
forceReload? boolean false If true, the survey will be reloaded from the server, Default: false

Returns

Promise<SurveyRenderReason>

A SurveyRenderReason object indicating if the survey can be rendered.

Example

 1posthog.canRenderSurveyAsync(surveyId).then((result) => {
 2    if (result.visible) {
 3        // Survey can be rendered
 4        console.log('Survey can be rendered')
 5    } else {
 6        // Survey cannot be rendered
 7        console.log('Survey cannot be rendered:', result.disabledReason)
 8    }
 9})

PostHog.displaySurvey

displaySurvey(surveyId, options?): void

Display a survey programmatically as either a popover or inline element.

Parameters

Parameter Type Default value Description
surveyId string undefined The survey ID to display.
options? DisplaySurveyOptions DEFAULT_DISPLAY_SURVEY_OPTIONS Display configuration. Defaults to a popover that respects dashboard conditions and delays.

Returns

void

Examples

 1// Display as popover (respects all conditions defined in the dashboard)
 2posthog.displaySurvey('survey-id-123')
 1// Display inline in a specific element
 2posthog.displaySurvey('survey-id-123', {
 3  displayType: DisplaySurveyType.Inline,
 4  ignoreConditions: false,
 5  ignoreDelay: false,
 6  selector: '#survey-container'
 7})
 1// Force display ignoring conditions and delays
 2posthog.displaySurvey('survey-id-123', {
 3  displayType: DisplaySurveyType.Popover,
 4  ignoreConditions: true,
 5  ignoreDelay: true
 6})

PostHog.getActiveMatchingSurveys

getActiveMatchingSurveys(callback, forceReload?): void

Get surveys that should be enabled for the current user. See fetching surveys documentation for more details.

Parameters

Parameter Type Default value Description
callback SurveyCallback undefined The callback function will be called when the surveys are loaded or updated.
forceReload? boolean false Whether to force a reload of the surveys.

Returns

void

Example

 1posthog.getActiveMatchingSurveys((surveys) => {
 2     // do something
 3})

PostHog.getSurveys

getSurveys(callback, forceReload?): void

Get list of all surveys.

Parameters

Parameter Type Default value Description
callback SurveyCallback undefined Function that receives the array of surveys.
forceReload? boolean false Optional boolean to force an API call for updated surveys.

Returns

void

Example

 1function callback(surveys, context) {
 2  // do something
 3}
 4
 5posthog.getSurveys(callback, false)

PostHog.onActiveMatchingSurveysChanged

onActiveMatchingSurveysChanged(callback): () => void

Register an event listener that runs when the set of active matching surveys changes. The listener receives the initial matching set and updates after event/action triggers, cancellation, consumption, session expiry, definitions refresh, captured pageviews, feature-flag updates, marking a survey as seen, and reset. Unchanged results are suppressed.

URL conditions are re-evaluated on captured $pageview events, including automatic SPA pageviews when capture_pageview is 'history_change'. With automatic pageviews disabled, capture $pageview after navigation. This does not observe arbitrary DOM mutations or time passing; selector, device and wait-period conditions are checked on the supported updates.

The optional callback context distinguishes load errors from a successfully loaded empty result. New subscribers receive the current snapshot without replaying earlier errors: a settled unavailable state is ([], { isLoaded: false }), while usable cached definitions are evaluated normally. An initial load already in progress delivers when it resolves. Recoverable load failures keep the subscription alive. Unsubscribing prevents any further delivery, including callbacks from an outstanding initial request.

Parameters

Parameter Type Description
callback SurveyCallback The callback to call with active matching surveys.

Returns

A function that can be called to unsubscribe the listener.

() => void

Example

 1const unsubscribe = posthog.onActiveMatchingSurveysChanged((surveys) => {
 2    // respond to changes in currently matching surveys
 3})

PostHog.onSurveysLoaded

onSurveysLoaded(callback): () => void

Register an event listener that runs when surveys are loaded.

Callback parameters:

  • surveys: Survey[]: An array containing all survey objects fetched from PostHog using the getSurveys method
  • context: { isLoaded: boolean, error?: string }: An object indicating if the surveys were loaded successfully

Parameters

Parameter Type Description
callback SurveyCallback The callback function will be called when surveys are loaded or updated.

Returns

A function that can be called to unsubscribe the listener.

() => void

Example

 1posthog.onSurveysLoaded((surveys, context) => { // do something })

PostHog.renderSurvey

renderSurvey(surveyId, selector): void

Although we recommend using popover surveys and display conditions, if you want to show surveys programmatically without setting up all the extra logic needed for API surveys, you can render surveys programmatically with the renderSurvey method.

This takes a survey ID and an HTML selector to render an unstyled survey.

Parameters

Parameter Type Description
surveyId string The ID of the survey to render.
selector string The selector of the HTML element to render the survey on.

Returns

void

Example

 1posthog.renderSurvey(coolSurveyID, '#survey-container')

Deprecated

Use displaySurvey instead - it's more complete and also supports popover surveys.

DisplaySurveyType

const DisplaySurveyType: object

Type Declaration

Name Type
Inline "inline"
Popover "popover"

SurveyEventName

const SurveyEventName: object

Type Declaration

Name Type
ABANDONED "survey abandoned"
DISMISSED "survey dismissed"
SENT "survey sent"
SHOWN "survey shown"

SurveyEventProperties

const SurveyEventProperties: object

Type Declaration

Name Type
PRODUCT_TOUR_ID "$product_tour_id"
SURVEY_COMPLETED "$survey_completed"
SURVEY_ID "$survey_id"
SURVEY_ITERATION "$survey_iteration"
SURVEY_ITERATION_START_DATE "$survey_iteration_start_date"
SURVEY_LANGUAGE "$survey_language"
SURVEY_LAST_SEEN_DATE "$survey_last_seen_date"
SURVEY_NAME "$survey_name"
SURVEY_PARTIALLY_COMPLETED "$survey_partially_completed"
SURVEY_QUESTIONS "$survey_questions"
SURVEY_RESPONSE "$survey_response"
SURVEY_SUBMISSION_ID "$survey_submission_id"

SurveyEventType

const SurveyEventType: object

Type Declaration

Name Type
Activation "events"
Cancellation "cancelEvents"

SurveyPosition

const SurveyPosition: object

Type Declaration

Name Type
Center "center"
Left "left"
MiddleCenter "middle_center"
MiddleLeft "middle_left"
MiddleRight "middle_right"
NextToTrigger "next_to_trigger"
Right "right"
TopCenter "top_center"
TopLeft "top_left"
TopRight "top_right"

SurveyQuestionBranchingType

const SurveyQuestionBranchingType: object

Type Declaration

Name Type
End "end"
NextQuestion "next_question"
ResponseBased "response_based"
SpecificQuestion "specific_question"

SurveyQuestionType

const SurveyQuestionType: object

Type Declaration

Name Type
Link "link"
MultipleChoice "multiple_choice"
Open "open"
Rating "rating"
SingleChoice "single_choice"

SurveySchedule

const SurveySchedule: object

Type Declaration

Name Type
Always "always"
Once "once"
Recurring "recurring"

SurveyTabPosition

const SurveyTabPosition: object

Type Declaration

Name Type
Bottom "bottom"
Left "left"
Right "right"
Top "top"

SurveyType

const SurveyType: object

Type Declaration

Name Type
API "api"
ExternalSurvey "external_survey"
Popover "popover"
Widget "widget"

SurveyWidgetType

const SurveyWidgetType: object

Type Declaration

Name Type
Button "button"
Selector "selector"
Tab "tab"

SDK utils

PostHog.featureFlags

featureFlags: TreeShakeable<PostHogFeatureFlags>

The feature flags instance. Provides access to feature flag override methods.

PostHog.version

version: string = Config.LIB_VERSION

The library version.

PostHog.flagsEndpointWasHit

get flagsEndpointWasHit(): boolean

Whether feature flags have been initialized for this instance.

Remarks

Despite the name, this is a proxy for processed feature flag values. It may be true for bootstrapped flags before a network request completes.

Returns

boolean

True once the SDK has processed feature flag values.

PostHog.get_session_replay_url

get_session_replay_url(options?): string

Returns the Replay url for the current session.

Parameters

Parameter Type Description
options? { timestampLookBack?: number; withTimestamp?: boolean; } Options for the URL.
options.timestampLookBack? number How many seconds to look back for the timestamp.
options.withTimestamp? boolean Whether to include the timestamp in the URL.

Returns

string

The URL for the current session replay, or an empty string if sessions are unavailable.

Examples

 1// basic usage
 2posthog.get_session_replay_url()
 1// timestamp
 2posthog.get_session_replay_url({ withTimestamp: true })
 1// timestamp and lookback
 2posthog.get_session_replay_url({
 3  withTimestamp: true,
 4  timestampLookBack: 30 // look back 30 seconds
 5})

PostHog.getEarlyAccessFeatures

getEarlyAccessFeatures(callback, force_reload?, stages?): void

Get the list of early access features. To check enrollment status, use isFeatureEnabled. Learn more in the docs

Parameters

Parameter Type Default value Description
callback EarlyAccessFeatureCallback undefined The callback function will be called when the early access features are loaded.
force_reload? boolean false Whether to force a reload of the early access features.
stages? EarlyAccessFeatureStage[] undefined The stages of the early access features to load.

Returns

void

Example

 1const posthog = usePostHog()
 2const activeFlags = useActiveFeatureFlags()
 3
 4const [activeBetas, setActiveBetas] = useState([])
 5const [inactiveBetas, setInactiveBetas] = useState([])
 6const [comingSoonFeatures, setComingSoonFeatures] = useState([])
 7
 8useEffect(() => {
 9  posthog.getEarlyAccessFeatures((features) => {
10    // Filter features by stage
11    const betaFeatures = features.filter(feature => feature.stage === 'beta')
12    const conceptFeatures = features.filter(feature => feature.stage === 'concept')
13
14    setComingSoonFeatures(conceptFeatures)
15
16    if (!activeFlags || activeFlags.length === 0) {
17      setInactiveBetas(betaFeatures)
18      return
19    }
20
21    const activeBetas = betaFeatures.filter(
22            beta => activeFlags.includes(beta.flagKey)
23        );
24    const inactiveBetas = betaFeatures.filter(
25            beta => !activeFlags.includes(beta.flagKey)
26        );
27    setActiveBetas(activeBetas)
28    setInactiveBetas(inactiveBetas)
29  }, true, ['concept', 'beta'])
30}, [activeFlags])

PostHog.getPageViewId

getPageViewId(): string | undefined

Returns the current page view ID.

Returns

string | undefined

The current page view ID, or undefined if no page view has been captured.

PostHog.loadToolbar

loadToolbar(params): boolean

returns a boolean indicating whether the toolbar loaded

Parameters

Parameter Type Description
params ToolbarParams Toolbar parameters.

Returns

boolean

Whether the toolbar loaded.

PostHog.on

on(event, cb): () => void

Exposes a set of events that PostHog will emit. e.g. eventCaptured is emitted immediately before trying to send an event

Unlike onFeatureFlags and onSessionId these are not called when the listener is registered, the first callback will be the next event after registering a listener

Available events:

  • eventCaptured: Emitted immediately before trying to send an event
  • featureFlagsReloading: Emitted when feature flags are being reloaded (e.g. after identify(), group(), or reloadFeatureFlags())

Parameters

Parameter Type Description
event "eventCaptured" | "featureFlagsReloading" The event to listen for.
cb (...args) => void The callback function to call when the event is emitted.

Returns

A function that can be called to unsubscribe the listener.

() => void

Examples

 1posthog.on('eventCaptured', (event) => {
 2  console.log(event)
 3})
 1// Track when feature flags are reloading to show a loading state
 2posthog.on('featureFlagsReloading', () => {
 3  console.log('Feature flags are being reloaded...')
 4})

PostHog.updateEarlyAccessFeatureEnrollment

updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage?): void

Opt the user in or out of an early access feature. Learn more in the docs

Parameters

Parameter Type Description
key string The key of the feature flag to update.
isEnrolled boolean Whether the user is enrolled in the feature.
stage? string The stage of the feature flag to update.

Returns

void

Example

 1const toggleBeta = (betaKey) => {
 2  if (activeBetas.some(
 3    beta => beta.flagKey === betaKey
 4  )) {
 5    posthog.updateEarlyAccessFeatureEnrollment(
 6      betaKey,
 7      false
 8    )
 9    setActiveBetas(
10      prevActiveBetas => prevActiveBetas.filter(
11        item => item.flagKey !== betaKey
12      )
13    );
14    return
15  }
16
17  posthog.updateEarlyAccessFeatureEnrollment(
18    betaKey,
19    true
20  )
21  setInactiveBetas(
22    prevInactiveBetas => prevInactiveBetas.filter(
23      item => item.flagKey !== betaKey
24    )
25  );
26}
27
28const registerInterest = (featureKey) => {
29  posthog.updateEarlyAccessFeatureEnrollment(
30    featureKey,
31    true
32  )
33  // Update UI to show user has registered
34}

PostHog.updateFlags

updateFlags(flags, payloads?, options?): void

Manually update feature flag values without making a network request.

This is useful when you have feature flag values from an external source (e.g., server-side evaluation, edge middleware) and want to inject them into the client SDK.

Parameters

Parameter Type Description
flags Record<string, boolean | string> An object mapping flag keys to their values (boolean or string variant)
payloads? Record<string, JsonType> Optional object mapping flag keys to their JSON payloads
options? { merge?: boolean; } Optional settings. Use { merge: true } to merge with existing flags instead of replacing.
options.merge? boolean -

Returns

void

Example

 1// Replace all flags with server-evaluated values
 2posthog.updateFlags({
 3  'my-flag': true,
 4  'my-experiment': 'variant-a'
 5})
 6
 7// Merge with existing flags (update only specified flags)
 8posthog.updateFlags(
 9  { 'my-flag': true },
10  undefined,
11  { merge: true }
12)
13
14// With payloads
15posthog.updateFlags(
16  { 'my-flag': true },
17  { 'my-flag': { some: 'data' } }
18)

sampleByDistinctId

sampleByDistinctId(percent): BeforeSendFn

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

 1import { sampleByDistinctId } from 'posthog-js/customizations'
 2
 3posthog.init('<ph_project_token>', { before_send: sampleByDistinctId(0.4) })

sampleByEvent

sampleByEvent(eventNames, percent): BeforeSendFn

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

sampleBySessionId

sampleBySessionId(percent): BeforeSendFn

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

 1import { sampleBySessionId } from 'posthog-js/customizations'
 2
 3posthog.init('<ph_project_token>', { before_send: sampleBySessionId(0.25) })

Compression

const Compression: object

Type Declaration

Name Type
Base64 "base64"
GZipJS "gzip-js"

DEFAULT_PRODUCT_TOUR_APPEARANCE

const DEFAULT_PRODUCT_TOUR_APPEARANCE: Required<ProductTourAppearance>

ProductTourEventName

const ProductTourEventName: object

Type Declaration

Name Type Default value
BANNER_ACTION_CLICKED "product tour banner action clicked" 'product tour banner action clicked'
BANNER_CONTAINER_SELECTOR_FAILED "product tour banner container selector failed" 'product tour banner container selector failed'
BUTTON_CLICKED "product tour button clicked" 'product tour button clicked'
COMPLETED "product tour completed" 'product tour completed'
DISMISSED "product tour dismissed" 'product tour dismissed'
SHOWN "product tour shown" 'product tour shown'
STEP_COMPLETED "product tour step completed" 'product tour step completed'
STEP_SELECTOR_FAILED "product tour step selector failed" 'product tour step selector failed'
STEP_SHOWN "product tour step shown" 'product tour step shown'

ProductTourEventProperties

const ProductTourEventProperties: object

Type Declaration

Name Type Default value
INFERENCE_DATA_PRESENT "$inference_data_present" '$inference_data_present'
TOUR_BANNER_SELECTOR "$product_tour_banner_selector" '$product_tour_banner_selector'
TOUR_BUTTON_ACTION "$product_tour_button_action" '$product_tour_button_action'
TOUR_BUTTON_LINK "$product_tour_button_link" '$product_tour_button_link'
TOUR_BUTTON_TEXT "$product_tour_button_text" '$product_tour_button_text'
TOUR_BUTTON_TOUR_ID "$product_tour_button_tour_id" '$product_tour_button_tour_id'
TOUR_DISMISS_REASON "$product_tour_dismiss_reason" '$product_tour_dismiss_reason'
TOUR_ERROR "$product_tour_error" '$product_tour_error'
TOUR_FAILURE_PHASE "$product_tour_failure_phase" '$product_tour_failure_phase'
TOUR_ID "$product_tour_id" '$product_tour_id'
TOUR_ITERATION "$product_tour_iteration" '$product_tour_iteration'
TOUR_LAST_SEEN_DATE "$product_tour_last_seen_date" '$product_tour_last_seen_date'
TOUR_LINKED_SURVEY_ID "$product_tour_linked_survey_id" '$product_tour_linked_survey_id'
TOUR_MATCHES_COUNT "$product_tour_matches_count" '$product_tour_matches_count'
TOUR_NAME "$product_tour_name" '$product_tour_name'
TOUR_RENDER_REASON "$product_tour_render_reason" '$product_tour_render_reason'
TOUR_STEP_ELEMENT_CLASSES "$product_tour_step_element_classes" '$product_tour_step_element_classes'
TOUR_STEP_ELEMENT_ID "$product_tour_step_element_id" '$product_tour_step_element_id'
TOUR_STEP_ELEMENT_TAG "$product_tour_step_element_tag" '$product_tour_step_element_tag'
TOUR_STEP_ELEMENT_TEXT "$product_tour_step_element_text" '$product_tour_step_element_text'
TOUR_STEP_ID "$product_tour_step_id" '$product_tour_step_id'
TOUR_STEP_ORDER "$product_tour_step_order" '$product_tour_step_order'
TOUR_STEP_SELECTOR "$product_tour_step_selector" '$product_tour_step_selector'
TOUR_STEP_SELECTOR_FOUND "$product_tour_step_selector_found" '$product_tour_step_selector_found'
TOUR_STEP_TYPE "$product_tour_step_type" '$product_tour_step_type'
TOUR_STEPS_COUNT "$product_tour_steps_count" '$product_tour_steps_count'
TOUR_TYPE "$product_tour_type" '$product_tour_type'
TOUR_WAIT_DURATION_MS "$product_tour_wait_duration_ms" '$product_tour_wait_duration_ms'
TOUR_WAITED_FOR_ELEMENT "$product_tour_waited_for_element" '$product_tour_waited_for_element'
USE_MANUAL_SELECTOR "$use_manual_selector" '$use_manual_selector'

severityLevels

const severityLevels: readonly ["fatal", "error", "warning", "log", "info", "debug"]

Types

ActionStepStringMatching

ActionStepStringMatching = "contains" | "exact" | "regex"

Sync with plugin-server/src/types.ts.

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

ApiResponse

A minimal response from Client.sendRequest.

Properties

Property Type Description
error? unknown The transport error when the request failed before receiving an HTTP response.
json? unknown The response body parsed as JSON when available.
statusCode number The HTTP status code returned by the transport, or a client-defined best-effort status for sendBeacon sends.
text? string The response body as text when available.

AutocaptureCompatibleElement

AutocaptureCompatibleElement = "a" | "button" | "form" | "input" | "select" | "textarea" | "label"

AutocaptureConfig

If an array is passed for an allowlist, autocapture events will only be sent for elements matching at least one of the elements in the array. Multiple allowlists can be used

Extended by

  • AutocaptureConfig

Properties

Property Type Description
capture_copied_text? boolean When true, autocapture captures cut, copy, and paste interactions. Paste events do not contain pasted text.
capture_value_css_selector_allowlist? string[] | ((element) => boolean) CSS selectors or a predicate opting individual native fields into value capture on change events. Selectors match the field itself, not its ancestors. An empty array disables value capture. String values are sent in $input_value and may be edited in before_send. Values are not automatically redacted; only opt in fields whose contents you intend to collect. Password fields, no-capture markers, sensitive-field exclusions, and mask_all_text still apply. Default ['[data-ph-capture-value]']
css_selector_allowlist? string[] List of CSS selectors to allow autocapture on e.g. ['[ph-capture]'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and allow list config ['[id]'] we will capture the click if the click-target or its parents has any id Everything is allowed when there's no allowlist
css_selector_ignorelist? string[] List of CSS selectors to ignore autocapture on e.g. ['[data-ph-no-autocapture]'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and ignore list config ['[id]'] we will ignore the click if the click-target or its parents has any id Nothing is ignored when there's an empty ignorelist, e.g. [] If no ignorelist is set, we default to ignoring .ph-no-autocapture and [data-ph-no-autocapture] Note: providing any custom list fully replaces the defaults — include .ph-no-autocapture and [data-ph-no-autocapture] explicitly if you still want them honoured.
dom_event_allowlist? DomAutocaptureEvents[] List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']
element_allowlist? AutocaptureCompatibleElement[] List of DOM elements to allow autocapture on e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'] We consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg if the allowlist has button then we allow the capture when the button or the svg is the click target but not if either of the divs are detected as the click target
element_attribute_ignorelist? string[] Exclude certain element attributes from autocapture E.g. ['aria-label'] or [data-attr-pii]
url_allowlist? (string | RegExp)[] List of URLs to allow autocapture on, can be strings to match or regexes e.g. ['https://example.com', 'test.com/.*'] this is useful when you want to autocapture on specific pages only if you set both url_allowlist and url_ignorelist, we check the allowlist first and then the ignorelist. the ignorelist can override the allowlist
url_ignorelist? (string | RegExp)[] List of URLs to not allow autocapture on, can be strings to match or regexes e.g. ['https://example.com', 'test.com/.*'] this is useful when you want to autocapture on most pages but not some specific ones if you set both url_allowlist and url_ignorelist, we check the allowlist first and then the ignorelist. the ignorelist can override the allowlist

BasicSurveyQuestion

  • SurveyQuestionBase

Properties

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

BeforeSendFn

BeforeSendFn = (cr) => CaptureResult | null

Parameters

Parameter Type
cr CaptureResult

Returns

CaptureResult | null

BeforeSendLogFn

BeforeSendLogFn = (record) => CaptureLogOptions | null

Pre-send filter. Inspect, mutate, or drop a captured log record before it enters the rate cap or the buffer. Return the (possibly transformed) record to keep it; return null to drop it.

Configure as a single function or an array. Arrays form a left-to-right chain: each function receives the previous function's return value, and a null from any link short-circuits the chain and drops the record. A function that throws also drops the record (the error is logged).

Parameters

Parameter Type
record CaptureLogOptions

Returns

CaptureLogOptions | null

Example

Redact secrets from log bodies

 1logs: { beforeSend: (record) => ({ ...record, body: record.body.replace(/token=\S+/g, 'token=[REDACTED]') }) }

BeforeSendMetricFn

BeforeSendMetricFn = (sample) => MetricSample | null

Pre-aggregation filter. Return the (possibly transformed) sample to keep it; return null to drop it. Configure as a single function or an array forming a left-to-right chain; a null from any link drops the sample and a thrown error also drops it (the error is logged).

Parameters

Parameter Type
sample MetricSample

Returns

MetricSample | null

Example

Drop debug metrics in production

 1metrics: { beforeSend: (m) => (m.name.startsWith('debug_') ? null : m) }

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

BrowserMetricsConfig

Metrics configuration options for the browser SDK. Adds the options that only the browser SDK implements to the shared metrics options.

Extends

  • MetricsConfig

Properties

Property Type Description Inherited from
beforeSend? BeforeSendMetricFn | BeforeSendMetricFn[] Pre-aggregation filter for metric samples, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a sample (return null to drop) before it is aggregated. MetricsConfig.beforeSend
environment? string The deployment environment for metric series (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. MetricsConfig.environment
flags? boolean Experimental EXPERIMENTAL: Record the round trip of every /flags HTTP attempt as the histogram posthog.flags.request.duration, in milliseconds. Each retry is a separate sample. The timer starts when the SDK hands the request to the transport, so the duration includes compressing the request body. Samples carry the server host, the response status or error type, and the browser's IANA timezone as client.timezone. Requests that the SDK drops before they reach the network are not recorded. An attempt that gets a response also splits that duration into three histograms with the same attributes: posthog.flags.request.pre_send_duration (until the request starts), posthog.flags.request.network_duration (until the last byte of the response arrives, from the request's Resource Timing entry) and posthog.flags.request.main_thread_duration (until the SDK's callback runs). The attempt records them only when the browser reports a Resource Timing entry within 5 seconds of the callback that no other /flags request from this copy of the SDK to the same URL can own. This option, the metric names, and their attributes may change or be removed in any release. Default undefined @experimental -
flushIntervalMs? number How often the aggregated window is flushed, in milliseconds. Samples are folded into per-series aggregates in memory between flushes — one data point per series per window, no matter how many calls. The browser SDK defaults to 60000: every tab of an app writes to the same series, so a longer window keeps busy series under the backend's per-series point limit. Default 10000 (60000 in the browser) MetricsConfig.flushIntervalMs
maxSeriesPerFlush? number Cardinality guardrail: maximum distinct series (name + type + unit + attribute combination) held per flush window. Samples for series beyond the cap are dropped with a single warning per window. Default 1000 MetricsConfig.maxSeriesPerFlush
network? boolean | NetworkMetricsConfig Record the duration of every HTTP or HTTPS fetch and XMLHttpRequest as a histogram. true uses the defaults. Requests to PostHog itself, URLs with other protocols, and server-sent event streams (text/event-stream responses) are not recorded. Long-polling requests look like ordinary requests; skip them with a name function that returns null. Each transport is measured to the boundary its API exposes: a fetch to its response headers, an XMLHttpRequest to the end of its response body. Default undefined -
resourceAttributes? MetricAttributes Additional resource attributes applied to every metrics batch. These describe the service/deployment, not individual series. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. Example { 'host.name': 'web-01', 'cloud.region': 'us-east-1' } MetricsConfig.resourceAttributes
serviceName? string The service name for metric series. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service' MetricsConfig.serviceName
serviceVersion? string The service version for metric series (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. MetricsConfig.serviceVersion

CanvasMaskRegion

CanvasMaskRegion = object

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

CapturedEventInfo

A captured event, as observed by onEvent.

Properties

Property Modifier Type Description
event readonly string The finalized captured event name.
properties readonly object The final event properties after client defaults and dynamic properties are applied.

CapturedNetworkRequest

CapturedNetworkRequest = Writable<Omit<PerformanceEntry, "toJSON">> & object

Type Declaration

Name Type
endTime? number
initiatorType? InitiatorType
isInitial? boolean
method? string
requestBody? string | null
requestHeaders? Headers
responseBody? string | null
responseHeaders? Headers
startTime? number
status? number
timeOrigin? number
timestamp? number

CaptureLogOptions

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

CaptureMetricOptions

Options accepted by posthog.metrics.count/gauge/histogram.

Extended by

  • HistogramOptions

Properties

Property Type Description
attributes? MetricAttributes Low-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series.
unit? string Unit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series.

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.

CaptureOptions

Per-call capture overrides, mirroring the client's public capture options.

Properties

Property Type Description
delivery? "immediate" | "unload" Start delivering this event now instead of waiting for a batch. immediate keeps the host's normal transport, retries and queue; unload uses best-effort unload-safe delivery. A host that cannot honor the mode delivers the event normally.
set? Record<string, unknown> Person properties to set, emitted as $set.
setOnce? Record<string, unknown> Person properties to set if unset, emitted as $set_once.
timestamp? Date Override the event timestamp sent to PostHog. UTC is preferred; non-UTC input is converted to UTC.
uuid? string Override the event UUID used for de-duplication.

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

Client

The host SDK surface handed to an extension in setup. A conforming host provides it as an adapter over its own analytics, transport, persistence, event, and remote-config internals.

Properties

Property Modifier Type Description
anonymousId readonly string The anonymous device id carried across identify calls.
canCapture readonly boolean Whether the host currently permits data capture.
deviceId readonly string | undefined The actual persisted device id, absent in cookieless contexts.
distinctId readonly string The id events are currently attributed to.
groups readonly object Active group memberships attached to events as $groups.
initialPersonProperties readonly object Initial person properties used for feature evaluation.
isOptedOut readonly boolean Effective consent opt-out state. Cookieless capture may still be permitted while opted out.
isRateLimited? readonly boolean Whether the client rate limit drops an event captured now. Reading it must not use a token.
kv readonly KeyValueStore Initializable, synchronously buffered key-value storage backed by the host client's persistence.
library readonly object Live host SDK metadata.
library.name readonly string -
library.version readonly string -
logger readonly Logger Logger that follows the host client's debug/noise policy.
onEvent readonly Listener<CapturedEventInfo> Fires for every captured event through a deeply readonly view.
onRemoteConfig readonly Listener<{ config: { analytics?: { endpoint?: string; }; autocapture_opt_out?: boolean; autocaptureExceptions?: boolean | { endpoint?: string; }; captureDeadClicks?: boolean; capturePerformance?: boolean | { __preview_web_vitals_soft_navs?: boolean; __web_vitals_max_value?: number; network_timing?: boolean; web_vitals?: boolean; web_vitals_allowed_metrics?: readonly SupportedWebVitalsMetrics[]; web_vitals_attribution?: boolean | readonly SupportedWebVitalsMetrics[]; web_vitals_delayed_flush_ms?: number; }; conversations?: boolean | { collectName?: boolean; color?: string; domains?: readonly string[]; enabled: boolean; greetingText?: string; identificationFormDescription?: string; identificationFormTitle?: string; placeholderText?: string; requireEmail?: boolean; token: string; widgetEnabled?: boolean; widgetPosition?: WidgetPosition; }; defaultIdentifiedOnly?: boolean; editorParams?: { actionId?: number; dataAttributes?: readonly string[]; distinctId?: string; featureFlags?: {[key: string]: string | boolean; }; instrument?: boolean; source?: ToolbarSource; temporaryToken?: string; token?: string; toolbarVersion?: "toolbar"; userEmail?: string; userIntent?: ToolbarUserIntent; }; elementsChainAsString?: boolean; errorTracking?: { autocaptureExceptions?: boolean; captureExtensionExceptions?: boolean; suppressionRules?: readonly object[]; }; hasFeatureFlags?: boolean; heatmaps?: boolean; isAuthenticated: boolean; logs?: { captureConsoleLogs?: boolean; }; productTours?: boolean; sessionRecording?: false | { canvasFps?: number | null; canvasQuality?: string | null; consoleLogRecordingEnabled?: boolean; endpoint?: string; eventTriggers?: readonly string[]; linkedFlag?: string | { flag: string; variant: string; } | null; masking?: { blockSelector?: string | null; maskAllElementAttributes?: boolean; maskAllInputs?: boolean; maskTextSelector?: string | null; }; minimumDurationMilliseconds?: number; networkPayloadCapture?: { recordBody?: boolean | readonly string[] | { request: ... | ... | ...; response: ... | ... | ...; }; recordHeaders?: boolean | { request: boolean; response: boolean; }; }; recordCanvas?: boolean | null; sampleRate?: string | null; scriptConfig?: { script?: string; }; triggerGroups?: readonly object[]; triggerMatchType?: "all" | "any"; urlBlocklist?: readonly object[]; urlTriggers?: readonly object[]; version?: 1 | 2; }; siteApps: readonly object[]; supportedCompression: readonly Compression[]; surveys?: boolean | readonly object[]; toolbarParams: { actionId?: number; dataAttributes?: readonly string[]; distinctId?: string; featureFlags?: {[key: string]: string | boolean; }; instrument?: boolean; source?: ToolbarSource; temporaryToken?: string; token?: string; toolbarVersion?: "toolbar"; userEmail?: string; userIntent?: ToolbarUserIntent; }; toolbarVersion: "toolbar"; }; ok: true; } | { ok: false; }> Replays the latest available remote-config outcome and fires subsequent outcomes when the host makes them available.
onSession readonly Listener<string> Observes session IDs through the host's session notifications, without creating a session. May replay an existing session on subscription.
projectToken readonly string Public project token used to authenticate endpoint-specific requests.
session readonly SessionContext | undefined The current session, if one exists. Reading it need not create one.

Methods

capture()

capture(event, properties?, options?): boolean

Synchronously admits an analytics event to the client's normal pipeline. Returns false when the client rate limit dropped the event, so the caller can send it again later. An event that is dropped for another reason, for example by before_send, returns true.

Parameters
Parameter Type
event string
properties? Properties | null
options? CaptureOptions
Returns

boolean

getExtension()
Call Signature

getExtension<T>(token): T | undefined

Returns the extension registered under a typed stable name, or undefined when it is not installed.

Type Parameters
Type Parameter
T extends Extension<Client>
Parameters
Parameter Type
token ExtensionToken<T>
Returns

T | undefined

Call Signature

getExtension<T>(name): T | undefined

Returns the extension registered under a stable name, or undefined when it is not installed.

Type Parameters
Type Parameter Default type
T extends Extension<Client> Extension<Client>
Parameters
Parameter Type
name string
Returns

T | undefined

registerDynamicEventProperties()

registerDynamicEventProperties(producer): Disposable

Registers a synchronous producer of properties merged into every captured event.

Parameters
Parameter Type
producer () => Record<string, unknown>
Returns

Disposable

sendRequest()

sendRequest(path, init?): Promise<ApiResponse>

Sends a request through the host SDK's transport.

Parameters
Parameter Type
path string
init? SendRequestInit
Returns

Promise<ApiResponse>

Compression

Compression = typeof Compression[keyof typeof Compression]

ConfigDefaults

ConfigDefaults = "latest" | typeof CONFIG_DEFAULTS_DATES[number] | "unset"

Configuration defaults snapshot used by PostHogConfig.defaults. Later dates include all earlier default changes. latest includes all changes in the loaded SDK version.

ConversationsConfig

Conversations configuration options

Properties

Property Type Description
theme? ConversationsTheme Theme of the support widget. Change it after init with posthog.conversations.setTheme(). Example posthog.init('phc_...', { conversations: { theme: { colorScheme: 'auto', primary: '#111827', dark: { primary: '#f9fafb' } }, }, })

ConversationsRemoteConfig

Remote configuration for conversations from the PostHog server.

Properties

Property Type Description
collectName? boolean Whether to show the name field in the identification form.
color? string Primary color for the widget UI.
domains? string[] Domains where the widget may be shown.
enabled boolean Whether conversations are enabled for this team.
greetingText? string Greeting text to show when the widget is first opened.
identificationFormDescription? string Description for the identification form.
identificationFormTitle? string Title for the identification form.
placeholderText? string Placeholder text for the message input.
requireEmail? boolean Whether to require an email address before starting a conversation.
token string Public token for authenticating conversations API requests.
widgetEnabled? boolean Whether the widget UI should be shown.
widgetPosition? WidgetPosition Position of the widget on the screen.

ConversationsTheme

Theme of the conversations widget. The top-level colors are the light colors; dark holds the dark ones.

Values are applied as --ph-conv-* CSS custom properties (--ph-conv-primary, --ph-conv-on-primary, --ph-conv-bg, --ph-conv-surface, --ph-conv-text, --ph-conv-muted, --ph-conv-border, --ph-conv-agent-bubble, --ph-conv-font, --ph-conv-radius, --ph-conv-launcher-shadow, --ph-conv-window-shadow). Rules in your own stylesheet that set them on #ph-conversations-widget-container take precedence over the theme.

Extends

  • ConversationsThemeColors

Properties

Property Type Description Inherited from
agentBubble? string Background of messages from your team. ConversationsThemeColors.agentBubble
background? string Window, message list and input background. ConversationsThemeColors.background
border? string Borders and dividers. ConversationsThemeColors.border
borderRadius? string Corner radius of the chat window, e.g. '16px'. -
colorScheme? "auto" | "light" | "dark" Which colors to use. 'auto' follows the visitor's prefers-color-scheme. Default 'light' -
dark? ConversationsThemeColors Colors used when the dark scheme is active. Unset values fall back to built-in dark colors, except primary and primaryText, which fall back to the light ones. -
fontFamily? string Font family of the widget. -
launcherShadow? string CSS filter applied to the launcher button, e.g. 'none' or 'drop-shadow(0 2px 8px rgba(0,0,0,0.2))'. -
mutedText? string Secondary text: timestamps, author names, descriptions. ConversationsThemeColors.mutedText
primary? string Launcher, header, customer messages and buttons. Overrides the color set in project settings. ConversationsThemeColors.primary
primaryText? string Text and icons drawn on primary. Computed from primary when it is a hex color and this is unset. ConversationsThemeColors.primaryText
surface? string Secondary background: identification form, unread tickets, code blocks. ConversationsThemeColors.surface
text? string Main text color. ConversationsThemeColors.text
windowShadow? string CSS box-shadow of the chat window. -

ConversationsThemeColors

Colors of the conversations widget. Any CSS color value is accepted.

Extended by

  • ConversationsTheme

Properties

Property Type Description
agentBubble? string Background of messages from your team.
background? string Window, message list and input background.
border? string Borders and dividers.
mutedText? string Secondary text: timestamps, author names, descriptions.
primary? string Launcher, header, customer messages and buttons. Overrides the color set in project settings.
primaryText? string Text and icons drawn on primary. Computed from primary when it is a hex color and this is unset.
surface? string Secondary background: identification form, unread tickets, code blocks.
text? string Main text color.

ConversationsTraits

User traits to send with messages

Indexable

[key: string]: string | number | boolean | null | undefined

Properties

Property Type
email? string | null
name? string | null

ConversationsUnavailableReason

ConversationsUnavailableReason = "disabled_by_config" | "consent_opted_out" | "disabled_for_toolbar" | "remote_config_pending" | "remote_config_failed" | "disabled_in_project" | "missing_token" | "extensions_unavailable" | "load_failed" | "initializing" | "not_loaded"

ConversationsWidgetState

ConversationsWidgetState = "open" | "closed"

Visual state of the conversations widget

DeadClickCandidate

Property Type
absoluteDelayMs? number
focusChangedDelayMs? number
mutationDelayMs? number
node Element
originalEvent MouseEvent | TouchEvent
scrollDelayMs? number
selectionChangedDelayMs? number
swipeDirection? "left" | "right" | "up" | "down"
swipeDistancePx? number
timestamp number
type? "click" | "swipe"
visibilityChangedDelayMs? number

DeadClicksAutoCaptureConfig

DeadClicksAutoCaptureConfig = object & Pick<AutocaptureConfig, "element_attribute_ignorelist">

Type Declaration

Name Type Description
__onCapture()? (click, properties) => void Allows setting behavior for when a dead click is captured. For e.g. to support capture to heatmaps If not provided the default behavior is to auto-capture dead click events Only intended to be provided by our own SDK
capture_clicks_with_modifier_keys? boolean By default, clicks with modifier keys (ctrl, shift, alt, meta/cmd) held down are not considered dead clicks, since these typically indicate intentional actions like "open in new tab". Set this to true to capture dead clicks even when modifier keys are held. Default false
capture_dead_swipes? boolean Determines whether PostHog should also detect "dead swipes" — touch swipe gestures (typically on mobile/touch devices) that produce no observable screen change (no scroll, mutation or selection change while the gesture is in progress, and no scroll, mutation, selection or visibility change afterwards). These usually indicate a failed navigation, e.g. swiping to go back or to move a carousel with nothing happening. Dead swipes are captured as $dead_swipe events. This only applies to the dead-click autocapture path, not the heatmaps path. Swipes over surfaces whose response cannot be observed — canvas, video and other media/plugin elements under the finger — are never captured, and capture is limited per page load (see max_dead_swipes_per_page_load). Default true
css_selector_ignorelist? string[] List of CSS selectors to ignore dead clicks on e.g. ['.my-download-link'] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > a > svg and ignore list config ['[download]'] we will ignore the dead click if the click-target or its parents has any download attribute Nothing is ignored when there's an empty ignorelist, e.g. [] If no ignorelist is set, we default to ignoring .ph-no-deadclick and .ph-no-capture A custom ignorelist fully replaces the default — include .ph-no-capture if you want it to suppress dead-click capture as well
max_dead_swipes_per_page_load? number The maximum number of dead swipes captured per page load. Swipe gestures are plentiful on touch devices, so a page whose responses the detector cannot see is capped rather than allowed to flood events. Only used when capture_dead_swipes is enabled. Default 10
mutation_threshold_ms? number We'll not consider a click to be a dead click, if it's followed by a mutation within mutation_threshold_ms milliseconds Default 2500
scroll_threshold_ms? number We'll not consider a click to be a dead click, if it's followed by a scroll within scroll_threshold_ms milliseconds Default 100
selection_change_threshold_ms? number We'll not consider a click to be a dead click if it selects/unselects text or moves a caret in editable content during its mouse gesture, regardless of how long the button is held. Selection changes outside a matching gesture suppress the click when they occur within selection_change_threshold_ms milliseconds immediately before or after it. When a closed shadow root hides whether a caret belongs to editable content, only the timed window applies. A value of 0 disables selection-based suppression. Default 100
swipe_threshold_px? number The minimum straight-line distance in CSS pixels between where a touch gesture starts and ends for it to be considered a swipe (rather than a tap). Only used when capture_dead_swipes is enabled. Default 30

DisplaySurveyInlineOptions

  • DisplaySurveyOptionsBase

Properties

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

DisplaySurveyOptions = DisplaySurveyPopoverOptions | DisplaySurveyInlineOptions

Options for posthog.displaySurvey().

DisplaySurveyOptionsBase

  • DisplaySurveyPopoverOptions
  • DisplaySurveyInlineOptions

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

DisplaySurveyType = typeof DisplaySurveyType[keyof typeof DisplaySurveyType]

Disposable

A resource handle with idempotent, best-effort cleanup.

Methods

dispose()

dispose(): void

Release resources owned by this object.

Returns

void

DomAutocaptureEvents

DomAutocaptureEvents = "click" | "change" | "submit"

EarlyAccessFeature

A feature that isn't publicly available yet.

Properties

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

EarlyAccessFeatureCallback = (earlyAccessFeatures) => void

Parameters

Parameter Type
earlyAccessFeatures EarlyAccessFeature[]

Returns

void

EarlyAccessFeatureResponse

Property Type
earlyAccessFeatures EarlyAccessFeature[]

EarlyAccessFeatureStage

EarlyAccessFeatureStage = "concept" | "alpha" | "beta" | "general-availability"

EndBranching

Property Type
type "end"

ErrorEventArgs

ErrorEventArgs = [event: string | Event, source?: string | undefined, lineno?: number | undefined, colno?: number | undefined, error?: Error | undefined]

ErrorTrackingOptions

Shared configuration for the error tracking burst-protection rate limiter.

Burst protection is scoped per exception type — the limiter is keyed by exception type, so each distinct $exception type gets its own token bucket and there is no aggregate cap across all types. It applies only to autocaptured exceptions; manual captureException calls are never rate limited. These options let customers with high-cardinality exception types tune the per-type allowance, and are shared between the browser and Node SDKs.

Extends

  • ExceptionRateLimiterConfig

Properties

Property Type Description Inherited from
__capturePostHogExceptions? boolean UNSTABLE: determines whether exception caused by the PostHog SDK will be captured Default false -
__exceptionRateLimiterBucketSize? number Deprecated Use ExceptionRateLimiterConfig.exceptionRateLimiterBucketSize instead. Still honoured as a fallback, but will be removed in a future major version. -
__exceptionRateLimiterRefillRate? number Deprecated Use ExceptionRateLimiterConfig.exceptionRateLimiterRefillRate instead. Still honoured as a fallback, but will be removed in a future major version. -
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

ErrorTrackingSuppressionRule

Property Type
type "AND" | "OR"
values ErrorTrackingSuppressionRuleValue[]

ErrorTrackingSuppressionRuleValue

Property Type
key "$exception_types" | "$exception_values"
operator SurveyMatchType
type string
value string | string[]

EvaluationReason

EvaluationReason = object

Properties

Property Type
code string
condition_index number | undefined
description string | undefined

EventHandler

EventHandler = (event) => boolean | void

Parameters

Parameter Type
event Event

Returns

boolean | void

EventName

EventName = KnownUnsafeEditableEvent | KnownEventName | string & object

ExceptionAutoCaptureConfig

ExceptionAutoCaptureConfig = object

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

ExceptionStepsConfig = object

Controls buffering and payload limits for exception steps added via addExceptionStep.

NOTE: This type is also defined in @posthog/core (exception-steps.ts). Keep both in sync.

Properties

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)

Extension

A shared browser extension. The client calls setup(client) once to start it and optional dispose() once for final best-effort resource cleanup. Everything an extension consumes flows through its host, Client by default.

setup may be async so an extension can read async KV state or remote config before it is ready. Async extensions must guard work after each await so cleanup cannot be followed by late listener, timer, or patch installation. The disposables an extension creates in setup are its own to release.

An extension that exposes app-facing controls extends Extension with named methods that share its state, e.g.:

 1interface SessionReplayExtension extends Extension {
 2    startRecording(): void
 3    stopRecording(): void
 4    isActive(): boolean
 5}

Type Parameters

Type Parameter Default type
Host Client

Properties

Property Modifier Type Description
bindings? readonly Readonly<Record<string, Extension<Client>>> Additional lookup targets whose lifecycle belongs to this extension.
name readonly string Stable extension name used for diagnostics and de-duplication within a client instance.

Methods

dispose()?

optional dispose(): void

Release final resources synchronously. Feature-level start/stop remains extension-owned.

Returns

void

flush()?

optional flush(reason?): Promise<void>

Flush buffered work. Shutdown awaits this within the host's timeout before disposal.

Parameters
Parameter Type
reason? "shutdown" | "flush"
Returns

Promise<void>

setup()

setup(client): void | Promise<void>

Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.

Parameters
Parameter Type
client Host
Returns

void | Promise<void>

ExtensionToken

ExtensionToken<T> = string & object

A typed stable name for resolving an installed extension.

Tokens are plain strings at runtime, so independently compiled scripts can share them without a registry or object-identity contract. The generic brand lets Client.getExtension infer the extension type. A token's string value must match an installed extension's stable name or one of its bindings keys.

Type Parameters

Type Parameter
T

Type Declaration

Name Type
[extensionTokenType] T

ExternalIntegrationKind

ExternalIntegrationKind = "intercom" | "crispChat"

FeatureFlagDetail

FeatureFlagDetail = object

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

FeatureFlagMetadata = object

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

FeatureFlagOptions = object

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

FeatureFlagOverrideOptions = object

Properties

Property Type
flags? boolean | string[] | FeatureFlagOverrides
payloads? FeatureFlagPayloadOverrides
suppressWarning? boolean

FeatureFlagOverrides

FeatureFlagOverrides = object

Index Signature

[flagName: string]: string | boolean

FeatureFlagPayloadOverrides

FeatureFlagPayloadOverrides = object

Index Signature

[flagName: string]: JsonType

FeatureFlagResult

FeatureFlagResult = object

Result of evaluating a feature flag, including both the flag value and its payload.

Properties

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

FeatureFlagsCallback = (flags, variants, context?) => void

Parameters

Parameter Type
flags string[]
variants Record<string, string | boolean>
context? { errorsLoading?: boolean; }
context.errorsLoading? boolean

Returns

void

FeatureFlagsConfig

Property Modifier Type Description
bootstrap readonly object -
bootstrap.featureFlagPayloads? readonly Readonly<Record<string, JsonType>> -
bootstrap.featureFlags? readonly Readonly<Record<string, string | boolean>> -
cacheTtlMs? readonly number -
compression? readonly Compression | "best-available" -
deduplicateCallsPerSession readonly boolean -
encodeBootstrapPayloads? readonly boolean Store bootstrapped payloads JSON-encoded, like payloads from /flags, so reads return them as supplied. Only $feature_flag_bootstrapped_payload reports the supplied value; $feature_flag_payload reports the stored JSON string, like payloads from /flags.
evaluationContexts readonly readonly string[] -
featureFlagsDisabled readonly boolean -
flagKeys? readonly readonly string[] -
idleRefreshBackoff readonly boolean -
onlyEvaluateSurveyFeatureFlags readonly boolean -
refreshIntervalMs? readonly number -
remoteRequestsDisabled readonly boolean -
requestMaxRetries? readonly number -
requestTimeoutMs readonly number -

FeatureFlagsConfigSource

get()

get(): Readonly<FeatureFlagsConfig>

Returns

Readonly<FeatureFlagsConfig>

FeatureFlagsReloadResult

Property Type Description
status "loaded" | "error" | "skipped" | "cancelled" loaded: evaluation completed; error: request/evaluation failed; skipped: evaluation unavailable; cancelled: reset/disposal.

FlagsResponse

Flags returns feature flags and their payloads

Extends

  • RemoteConfig

Properties

Property Type Description Inherited from
analytics? object Custom endpoint configuration for analytics events. RemoteConfig.analytics
analytics.endpoint? string - -
autocapture_opt_out? boolean If true, disables autocapture. When absent or not a boolean, the SDK keeps the last known server value; a visitor with no stored value keeps autocapture off until a response containing the field arrives. RemoteConfig.autocapture_opt_out
autocaptureExceptions? boolean | { endpoint?: string; } Exception autocapture configuration. RemoteConfig.autocaptureExceptions
captureDeadClicks? boolean Whether to capture dead clicks. RemoteConfig.captureDeadClicks
capturePerformance? boolean | PerformanceCaptureConfig Performance capture configuration shared by replay and web vitals. RemoteConfig.capturePerformance
conversations? boolean | ConversationsRemoteConfig Conversations widget configuration. RemoteConfig.conversations
defaultIdentifiedOnly? boolean Whether to capture only identified users by default. RemoteConfig.defaultIdentifiedOnly
editorParams? ToolbarParams Deprecated Renamed to toolbarParams; still present on older API responses. RemoteConfig.editorParams
elementsChainAsString? boolean Whether $elements_chain is sent as a string rather than an array. RemoteConfig.elementsChainAsString
errorsWhileComputingFlags boolean - -
errorTracking? object Error tracking configuration. RemoteConfig.errorTracking
errorTracking.autocaptureExceptions? boolean - -
errorTracking.captureExtensionExceptions? boolean - -
errorTracking.suppressionRules? ErrorTrackingSuppressionRule[] - -
evaluatedAt? number - -
featureFlagPayloads Record<string, JsonType> - -
featureFlags Record<string, string | boolean> - -
flags Record<string, FeatureFlagDetail> - -
hasFeatureFlags? boolean Whether the team has any feature flags enabled. RemoteConfig.hasFeatureFlags
heatmaps? boolean Whether heatmaps are enabled. RemoteConfig.heatmaps
isAuthenticated boolean Whether the current user is authenticated. RemoteConfig.isAuthenticated
logs? object Log capture configuration. RemoteConfig.logs
logs.captureConsoleLogs? boolean - -
minimalFlagCalledEvents? boolean Server-controlled gate for minimal $feature_flag_called events. true only when the project opted in; omitted otherwise. Absence always means full events. -
productTours? boolean Whether product tours are enabled. RemoteConfig.productTours
requestId? string - -
sessionRecording? false | SessionRecordingRemoteConfig Session recording configuration. RemoteConfig.sessionRecording
siteApps object[] Site apps available to the client. RemoteConfig.siteApps
supportedCompression Compression[] Supported compression algorithms. RemoteConfig.supportedCompression
surveys? boolean | Survey[] Whether surveys are enabled, optionally including their definitions. RemoteConfig.surveys
toolbarParams ToolbarParams Parameters for the toolbar. RemoteConfig.toolbarParams
toolbarVersion "toolbar" Deprecated Moved to toolbarParams. RemoteConfig.toolbarVersion

FlagVariant

FlagVariant = object

Properties

Property Type
flag string
variant string

GetMessagesResponse

Response from fetching messages

Properties

Property Type Description
has_more boolean Whether there are more messages to fetch
messages Message[] Array of messages
ticket_id string ID of the ticket
ticket_status TicketStatus Current status of the ticket
unread_count number Number of unread messages from the team

GetTicketsOptions

Options for fetching tickets list

Properties

Property Type Description
limit? number Number of tickets to return (default: 20)
offset? number Pagination offset (default: 0)
status? string Filter by ticket status (e.g., 'open', 'closed')

GetTicketsResponse

Response from fetching tickets list

Properties

Property Type Description
count number Total count of tickets
results Ticket[] Array of tickets

Headers

Headers = Record<string, string>

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

HistogramOptions

Options accepted by posthog.metrics.histogram.

Extends

  • CaptureMetricOptions

Properties

Property Type Description Inherited from
attributes? MetricAttributes Low-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series. CaptureMetricOptions.attributes
bounds? number[] Upper bucket boundaries, finite and strictly increasing. A value lands in the first bucket whose boundary is greater than or equal to it, and values above the last boundary land in an overflow bucket. Defaults to the OpenTelemetry defaults [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]. The first sample of a histogram (name and unit) fixes its bounds until the client resets. A later sample that passes different bounds is recorded in the fixed buckets and logs a warning, once per flush window. A sample with invalid bounds is dropped with a warning. The client fixes the bounds of at most maxSeriesPerFlush histograms. Past that limit, the client drops samples of a new histogram that pass bounds other than the defaults, and logs one warning. Each client fixes bounds on its own. PostHog stores one set of bounds per histogram series and reads every client's counts against it. Every client must therefore pass the same bounds for the same histogram. -
unit? string Unit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series. CaptureMetricOptions.unit

InferredSelector

Property Type
autoData string
excludeText? boolean
precision? number
text string | null

InitiatorType

InitiatorType = "audio" | "beacon" | "body" | "css" | "early-hint" | "embed" | "fetch" | "frame" | "iframe" | "icon" | "image" | "img" | "input" | "link" | "navigation" | "object" | "ping" | "script" | "track" | "video" | "xmlhttprequest"

IsFeatureEnabledOptions

IsFeatureEnabledOptions = FeatureFlagOptions & object

Options for isFeatureEnabled.

Type Declaration

Name Type Description
defaultValue? boolean Value to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists.

JSONContent

Property Type
attrs? Record<string, any>
content? JSONContent[]
marks? object[]
text? string
type? string

JsonRecord

JsonRecord = object

Index Signature

[key: string]: JsonType

JsonType

JsonType = string | number | boolean | null | undefined | JsonRecord | JsonType[]

KeyValueStore

Key-value store for small extension state. A host may initialize an asynchronous backend before exposing synchronous operations over its in-memory buffer. Writes must update that buffer before returning; ordered durable flushing remains the host's responsibility. Reads treat undefined values as absent.

Keys map verbatim to the host client's shared persistence. In browser-v1, unknown keys are normally included as event properties, collisions overwrite host/core state, and reset clears them. Every SDK-owned key therefore needs an explicit event/hidden/derived exposure policy in each host, and sensitive data must not be stored unless its transmission is approved. Values must be JSON-serializable.

Methods

get()
Call Signature

get<T>(keys): Partial<T>

Read several initialized values in one operation. Missing keys are omitted.

Type Parameters
Type Parameter
T extends object
Parameters
Parameter Type
keys readonly (keyof T & string)[]
Returns

Partial<T>

Call Signature

get<T>(key): T | undefined

Read one initialized value by key, returning undefined when it is missing.

Type Parameters
Type Parameter Default type
T unknown
Parameters
Parameter Type
key string
Returns

T | undefined

initialize()

initialize(): void | Promise<void>

Populate the in-memory buffer from durable storage. Calls are idempotent.

Returns

void | Promise<void>

remove()

remove(keyOrKeys): void

Remove one or several values from the initialized buffer in one operation.

Parameters
Parameter Type
keyOrKeys string | readonly string[]
Returns

void

set()
Call Signature

set(key, value): void

Immediately update the initialized buffer. null is durable; undefined is accepted for compatibility but treated as absent by reads and is not portable.

Parameters
Parameter Type
key string
value unknown
Returns

void

Call Signature

set(values): void

Coherently update several related values in the initialized buffer.

Parameters
Parameter Type
values Record<string, unknown>
Returns

void

KnownEventName

KnownEventName = "$heatmaps_data" | "$opt_in" | "$exception" | "$$heatmap" | "$web_vitals" | "$dead_click" | "$dead_swipe" | "$autocapture" | "$copy_autocapture" | "$rageclick"

These are known events PostHog events that can be processed by the beforeCapture function That means PostHog functionality does not rely on receiving 100% of these for calculations So, it is safe to sample them to reduce the volume of events sent to PostHog

KnownUnsafeEditableEvent

KnownUnsafeEditableEvent = typeof knownUnsafeEditableEvent[number]

These events can be processed by the beforeCapture function but can cause unexpected confusion in data.

Some features of PostHog rely on receiving 100% of these events

KnownUnsafeEditableEvent

KnownUnsafeEditableEvent = "$set" | "$pageview" | "$pageleave" | "$identify" | "$groupidentify" | "$create_alias" | "$feature_flag_called"

Known events that can be safely edited in beforeCapture without breaking PostHog functionality

LinkSurveyQuestion

  • SurveyQuestionBase

Properties

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

Listener

Listener<T> = (handler) => Disposable

Call it with a handler to start listening; dispose the returned Disposable to stop. There is one Listener per event type, so every event carries its own payload type. The handler is called synchronously, and stateful listeners may replay their current value during registration when documented. The returned disposable unregisters it from future payloads.

Type Parameters

Type Parameter
T

Parameters

Parameter Type
handler (payload) => void

Returns

Disposable

LogAttributes

LogAttributes = Record<string, LogAttributeValue>

LogAttributeValue

LogAttributeValue = string | number | boolean | null | undefined | unknown[] | Record<string, unknown>

LogCaptureOptions

Options for the captureLog API and posthog.logger convenience methods.

Extended by

  • LogsConfig
  • BrowserLogsConfig

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'.

Logger

Per-level convenience logger. Each method captures a structured log record at the corresponding severity, equivalent to posthog.captureLog({ body, level, attributes }).

Example

 1posthog.logger.info('checkout completed', { order_id: 'ord_789' })
 2posthog.logger.error('payment failed', { code: 'E001' })

Methods

debug()

debug(body, attributes?): void

Debug-level detail. Verbose, only useful while diagnosing.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

error()

error(body, attributes?): void

Error. Operation failed; the app may continue.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

fatal()

fatal(body, attributes?): void

Fatal. Operation failed; the app likely cannot continue.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

info()

info(body, attributes?): void

Informational. Normal app events worth recording.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

trace()

trace(body, attributes?): void

Lowest severity. Trace-level diagnostic detail.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

warn()

warn(body, attributes?): void

Warning. Something unexpected but non-fatal.

Parameters
Parameter Type
body string
attributes? LogAttributes
Returns

void

Logger

Logger = object

Properties

Property Type
createLogger (prefix) => Logger
critical (...args) => void
debug (...args) => void
error (...args) => void
info (...args) => void
warn (...args) => void

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

LogSdkContext

SDK-internal context the host SDK passes to buildOtlpLogRecord at capture time. Each SDK populates the fields that apply to it: browser fills currentUrl, mobile fills screenName / appState. Missing fields are omitted from the OTLP record (no stray attributes).

Internal to @posthog/core — customers don't see this in autocomplete.

Properties

Property Type Description
activeFeatureFlags? string[] -
appState? "foreground" | "background" Mobile-only — app foreground/background state at capture time
currentUrl? string Web-only — current page URL
distinctId? string -
lastActivityTimestamp? number Web-only — ms epoch of the most recent session activity
screenName? string Mobile-only — current screen / view name
sessionId? string -
sessionStartTimestamp? number Web-only — ms epoch when the current session started
windowId? string Web-only — current window id

LogSeverityLevel

LogSeverityLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal"

Log capture types

MarkAsReadResponse

Response from marking messages as read

Properties

Property Type Description
success boolean Whether the operation was successful
unread_count number Number of unread messages (should be 0 after marking as read)

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

Message

A message in a conversation

Properties

Property Type Description
author_name? string Display name of the message author
author_type MessageAuthorType Type of the message author
content string The message content as plain text (fallback)
created_at string ISO timestamp when the message was created
id string Unique identifier for the message
is_private boolean Whether this is an internal note (not shown to customer)
rich_content? TipTapDoc Rich content in TipTap JSON format (preferred for rendering) Falls back to content if missing or invalid

MessageAuthorType

MessageAuthorType = "customer" | "AI" | "human"

Author types for messages in a conversation

MetricAttributes

MetricAttributes = Record<string, MetricAttributeValue>

MetricAttributeValue

MetricAttributeValue = string | number | boolean

Metric attribute values are restricted to scalars. Every distinct attribute-value combination creates a new metric series, so high-cardinality values (user IDs, request IDs, URLs) must not be used as attributes — put those on logs or events instead.

MetricSample

A captured metric as seen by beforeSend, before aggregation. Mutating name, value, unit, attributes, or bounds changes what gets aggregated; returning null drops the sample.

Properties

Property Type Description
attributes? MetricAttributes -
bounds? number[] Histogram bucket boundaries. See HistogramOptions.bounds. Only histograms use them.
name string -
type MetricType -
unit? string -
value number -

MetricsConfig

Options for the posthog.metrics API (count, gauge, histogram). Shared by every SDK; browser-only options live in BrowserMetricsConfig.

Extended by

  • BrowserMetricsConfig

Properties

Property Type Description
beforeSend? BeforeSendMetricFn | BeforeSendMetricFn[] Pre-aggregation filter for metric samples, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a sample (return null to drop) before it is aggregated.
environment? string The deployment environment for metric series (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'.
flushIntervalMs? number How often the aggregated window is flushed, in milliseconds. Samples are folded into per-series aggregates in memory between flushes — one data point per series per window, no matter how many calls. The browser SDK defaults to 60000: every tab of an app writes to the same series, so a longer window keeps busy series under the backend's per-series point limit. Default 10000 (60000 in the browser)
maxSeriesPerFlush? number Cardinality guardrail: maximum distinct series (name + type + unit + attribute combination) held per flush window. Samples for series beyond the cap are dropped with a single warning per window. Default 1000
resourceAttributes? MetricAttributes Additional resource attributes applied to every metrics batch. These describe the service/deployment, not individual series. 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 metric series. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service'
serviceVersion? string The service version for metric series (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'.

MetricType

MetricType = "count" | "gauge" | "histogram"

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

NetworkMetricsConfig

Options for automatic HTTP and HTTPS fetch and XMLHttpRequest duration metrics. Recording never changes the request or its settlement. Fetch returns a derived promise so rejected requests remain observable to the caller.

Properties

Property Type Description
attributes? (request, response) => MetricAttributes | undefined Adds attributes to each recorded request. The result is merged over the default attributes, so it can also replace them, e.g. to set url.template to a route template. Keep attribute values low-cardinality. The default attributes follow the OTel HTTP client semantic conventions: http.request.method, server.address, server.port, url.scheme, url.template, http.response.status_code and error.type. The default url.template replaces each all-digit or uuid-like path segment with :id. Ids that carry a prefix or suffix, such as order-123 or 38217.pdf, are kept as they are, so return your own url.template for those routes. http.response.status_code is only set when a response arrived. error.type is the status code for a 4xx or 5xx response, the error name (e.g. TypeError) for a rejected fetch, or _OTHER when no response arrived and there is no error.
name? string | ((request) => string | null | undefined) The metric name. A string is used for every request. A function is called once per request; return a falsy value to skip that request. Default 'http.client.request.duration'

NetworkMetricsRequest

The request a network metric describes.

Properties

Property Type Description
method string The HTTP method in upper case, e.g. 'GET'.
url string The full request URL, including the query string.

NetworkMetricsResponse

How a network request ended.

Properties

Property Type Description
durationMs number How long the request took, in milliseconds. The end boundary follows the transport: a fetch is measured to its response headers, an XMLHttpRequest to the end of its response body.
status number | undefined The HTTP status code. undefined when the request failed before a response arrived.

NetworkRecordOptions

NetworkRecordOptions = object

Properties

Property Type Description
initiatorTypes? InitiatorType[] -
maskRequestFn? (data) => 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

NetworkRequest

NetworkRequest = object

Deprecated

  • use CapturedNetworkRequest instead

Properties

Property Type
url string

NextOptions

NextOptions = object

Properties

Property Type
revalidate false | 0 | number
tags string[]

NextOptions

NextOptions = object

Properties

Property Type
revalidate false | 0 | number
tags string[]

NextQuestionBranching

Property Type
type "next_question"

OtlpAnyValue

Property Type Description
arrayValue? object -
arrayValue.values OtlpAnyValue[] -
boolValue? boolean -
doubleValue? number -
intValue? string | number proto3 JSON maps int64 to a string, which is the form the SDK emits. number stays valid because encoded records persist in the logs queue: one written by an earlier version rehydrates in the numeric form and is re-sent unchanged. The wire format accepts both.
kvlistValue? object -
kvlistValue.values OtlpKeyValue[] -
stringValue? string -

OtlpExemplar

A sampled measurement linked to the span it was recorded in. IDs are lowercase hex.

Properties

Property Type
asDouble number
filteredAttributes OtlpKeyValue[]
spanId string
timeUnixNano string
traceId string

OtlpHistogramDataPoint

Property Type Description
attributes OtlpKeyValue[] -
bucketCounts number[] -
count number Plain JSON numbers, not strings — see the ingest's u64 handling.
exemplars? OtlpExemplar[] -
explicitBounds number[] -
max number -
min number -
startTimeUnixNano string -
sum number -
timeUnixNano string -

OtlpKeyValue

Property Type
key string
value OtlpAnyValue

OtlpLogRecord

Property Type
attributes OtlpKeyValue[]
body object
body.stringValue string
flags? number
observedTimeUnixNano string
severityNumber number
severityText OtlpSeverityText
spanId? string
timeUnixNano string
traceId? string

OtlpLogsPayload

Property Type
resourceLogs object[]

OtlpMetric

Property Type
gauge? object
gauge.dataPoints OtlpNumberDataPoint[]
histogram? object
histogram.aggregationTemporality number
histogram.dataPoints OtlpHistogramDataPoint[]
name string
sum? object
sum.aggregationTemporality number
sum.dataPoints OtlpNumberDataPoint[]
sum.isMonotonic boolean
unit? string

OtlpMetricsPayload

Property Type
resourceMetrics object[]

OtlpNumberDataPoint

Property Type Description
asDouble number -
attributes OtlpKeyValue[] -
exemplars? OtlpExemplar[] -
startTimeUnixNano? string -
timeUnixNano string Unix nanos as a decimal string (uint64 doesn't fit in JS Number).

OtlpSeverityEntry

Property Type
number number
text OtlpSeverityText

OtlpSeverityText

OtlpSeverityText = "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL"

OverrideConfig

OverrideConfig = object

Properties

Property Type
event_trigger boolean
linked_flag boolean
sampling boolean
url_trigger boolean

OverrideFeatureFlagsOptions

OverrideFeatureFlagsOptions = boolean | string[] | FeatureFlagOverrides | FeatureFlagOverrideOptions

Options for overriding feature flags on the client-side.

Can be:

  • false to clear all overrides
  • string[] to enable a list of flags
  • FeatureFlagOverrides to set variants directly
  • FeatureFlagOverrideOptions for granular control over flags and payloads

PerformanceCaptureConfig

Property Type Description
__preview_web_vitals_soft_navs? boolean Scope web vitals metrics to the browser's Soft Navigation entries, so that client-side route changes in single-page apps each start a fresh measurement window instead of accumulating against the original hard-navigation timestamp. Without this, an SPA's LCP observer keeps treating the "largest paint so far" as belonging to the initial page load across every subsequent route change, which inflates LCP (and the other metrics) by the time spent on the app. This is a preview option (opt-in) because it relies on Chrome's Soft Navigation Detection API, which is still experimental. When enabled, PostHog loads a pinned stable web-vitals 6.x bundle and passes reportSoftNavs to the observers. The default path remains on the existing web-vitals 5.x bundle. In browsers without soft-nav support, metrics fall back to their existing hard-navigation behavior. Default false
__web_vitals_max_value? number We observe very large values reported by the Chrome web vitals library These outliers are likely not real, useful values, and we exclude them You can set this to 0 in order to include all values, NB this is not recommended Default 15 * 60 * 1000 (15 minutes)
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

PersistentStore

Property Type
_error (error) => void
_get (name) => any
_is_supported () => boolean
_parse (name) => any
_remove (name, cross_subdomain?) => void
_set (name, value, expire_days?, cross_subdomain?, secure?, debug?) => boolean

PostHog

The PostHog instance interface.

This can be used to type window.posthog when loading PostHog via a <script> tag.

Example

 1import type { PostHog } from '@posthog/types'
 2
 3declare global {
 4    interface Window {
 5        posthog?: PostHog
 6    }
 7}
 8
 9// Now you can use window.posthog with type safety
10window.posthog?.capture('my_event', { property: 'value' })

Properties

Property Type Description
__loaded boolean Whether the PostHog instance has been loaded.
config PostHogConfig The current configuration of the PostHog instance.
decideEndpointWasHit boolean Deprecated Use flagsEndpointWasHit instead
featureFlags TreeShakeable<{ override(flags, suppressWarning?): void; overrideFeatureFlags(overrideOptions): void; }> The feature flags instance. Provides access to feature flag override methods.
flagsEndpointWasHit boolean Whether the flags endpoint has been hit.
logger Logger Logger with convenience methods for each severity level. Example posthog.logger.info('checkout completed', { order_id: 'ord_789' }) posthog.logger.error('payment failed', { error_code: 'E001' })
people object Deprecated Use setPersonProperties instead
people.set (prop, to?, callback?) => void -
people.set_once (prop, to?, callback?) => void -
sessionManager? object The session manager instance. May be undefined in cookieless mode.
sessionManager.resetSessionId () => void Reset the session ID, creating a new session
sessionRecording? object The session recording instance. May be undefined if session recording is not initialized.
sessionRecording._forceAllowLocalhostNetworkCapture boolean Force allow network capture on localhost (for debugging)
version string The library version.

Methods

addExceptionStep()

addExceptionStep(message, properties?): void

Adds a breadcrumb-like step that will be attached to the next captured exception as $exception_steps.

Parameters
Parameter Type Description
message string The step message
properties? Properties Additional context for this step
Returns

void

alias()

alias(alias, original?): number | void | CaptureResult

Create an alias for the current user.

Parameters
Parameter Type Description
alias string The alias to create
original? string The original distinct ID (defaults to current distinct ID)
Returns

number | void | CaptureResult

canRenderSurvey()

canRenderSurvey(surveyId): SurveyRenderReason | null

Check if a survey can be rendered.

Parameters
Parameter Type Description
surveyId string The survey ID
Returns

SurveyRenderReason | null

The render reason or null if can't render

canRenderSurveyAsync()

canRenderSurveyAsync(surveyId, forceReload?): Promise<SurveyRenderReason>

Check if a survey can be rendered (async version).

Parameters
Parameter Type Description
surveyId string The survey ID
forceReload? boolean Whether to force a reload from the server
Returns

Promise<SurveyRenderReason>

A promise that resolves to the render reason

capture()

capture(event_name, properties?, options?): CaptureResult | undefined

Capture an event.

Parameters
Parameter Type Description
event_name string The name of the event
properties? Properties | null A set of properties to include with the event
options? CaptureOptions Additional options for the capture
Returns

CaptureResult | undefined

The capture result

captureException()

captureException(error, additionalProperties?): CaptureResult | undefined

Capture an exception.

Parameters
Parameter Type Description
error unknown The error to capture
additionalProperties? Properties Additional properties to include with the event
Returns

CaptureResult | undefined

The capture result

captureLog()

captureLog(options): void

Capture a log entry and send it to the PostHog logs endpoint.

Parameters
Parameter Type Description
options CaptureLogOptions The log entry options (body, level, attributes, etc.)
Returns

void

captureTraceFeedback()

captureTraceFeedback(traceId, userFeedback): void

Capture written user feedback for a LLM trace.

Parameters
Parameter Type Description
traceId string | number The trace ID to capture feedback for
userFeedback string The feedback to capture
Returns

void

captureTraceMetric()

captureTraceMetric(traceId, metricName, metricValue): void

Capture a metric for a LLM trace.

Parameters
Parameter Type Description
traceId string | number The trace ID to capture the metric for
metricName string The name of the metric to capture
metricValue string | number | boolean The value of the metric to capture
Returns

void

clear_opt_in_out_capturing()

clear_opt_in_out_capturing(): void

Clear the opt-in/out status.

Returns

void

clearIdentity()

clearIdentity(): void

Clear HMAC-based identity verification, reverting to anonymous mode.

Returns

void

createPersonProfile()

createPersonProfile(): void

Create a person profile for the current user.

Returns

void

debug()

debug(debug?): void

Enable or disable debug mode.

Parameters
Parameter Type Description
debug? boolean Whether to enable debug mode (defaults to true)
Returns

void

get_distinct_id()

get_distinct_id(): string

Get the current distinct ID.

Returns

string

The current distinct ID

get_explicit_consent_status(): "pending" | "granted" | "denied"

Get the explicit consent status.

Returns

"pending" | "granted" | "denied"

The consent status

get_property()

get_property(property_name): any

Get a property value from persistence.

Parameters
Parameter Type Description
property_name string The property name
Returns

any

The property value

get_session_id()

get_session_id(): string

Get the current session ID.

Returns

string

The current session ID

get_session_replay_url()

get_session_replay_url(options?): string

Get the URL to view the current session recording.

Parameters
Parameter Type Description
options? { timestampLookBack?: number; withTimestamp?: boolean; } Options for the URL
options.timestampLookBack? number How many seconds to look back for the timestamp
options.withTimestamp? boolean Whether to include the timestamp in the URL
Returns

string

The session replay URL

getActiveMatchingSurveys()

getActiveMatchingSurveys(callback, forceReload?): void

Get active surveys that match the current user.

Parameters
Parameter Type Description
callback (surveys) => void Callback to receive the surveys
forceReload? boolean Whether to force a reload from the server
Returns

void

getEarlyAccessFeatures()

getEarlyAccessFeatures(callback, forceReload?, stages?): void

Get the list of early access features.

Parameters
Parameter Type Description
callback EarlyAccessFeatureCallback Callback to receive the features
forceReload? boolean Whether to force a reload from the server
stages? EarlyAccessFeatureStage[] The stages of the early access features to load
Returns

void

getFeatureFlag()

getFeatureFlag(key, options?): string | boolean | undefined

Get the value of a feature flag.

Parameters
Parameter Type Description
key string The feature flag key
options? FeatureFlagOptions Options for the feature flag lookup
Returns

string | boolean | undefined

The feature flag value (boolean for simple flags, string for multivariate)

getFeatureFlagPayload()

getFeatureFlagPayload(key): JsonType

Get the payload of a feature flag.

Parameters
Parameter Type Description
key string The feature flag key
Returns

JsonType

The feature flag payload

Deprecated

Use getFeatureFlagResult() instead which properly tracks the feature flag call.

getFeatureFlagResult()

getFeatureFlagResult(key, options?): FeatureFlagResult | undefined

Get a feature flag evaluation result including both the flag value and payload.

By default, this method emits the $feature_flag_called event.

Parameters
Parameter Type Description
key string The feature flag key
options? FeatureFlagOptions Options for the feature flag lookup
Returns

FeatureFlagResult | undefined

The feature flag result including key, enabled, variant, and payload, or undefined if not loaded

getGroups()

getGroups(): Record<string, any>

Get the current groups.

Returns

Record<string, any>

A record of group types to group keys

getPageViewId()

getPageViewId(): string | undefined

Get the current page view ID.

Returns

string | undefined

The current page view ID

getSessionProperty()

getSessionProperty(property_name): any

Get a session property value.

Parameters
Parameter Type Description
property_name string The property name
Returns

any

The property value

getSurveys()

getSurveys(callback, forceReload?): void

Get the list of surveys.

Parameters
Parameter Type Description
callback (surveys) => void Callback to receive the surveys
forceReload? boolean Whether to force a reload from the server
Returns

void

group()

group(groupType, groupKey, groupPropertiesToSet?): void

Associate the user with a group.

Parameters
Parameter Type Description
groupType string The type of group (e.g., 'company', 'project')
groupKey string The unique identifier for the group
groupPropertiesToSet? Properties Properties to set on the group
Returns

void

has_opted_in_capturing()

has_opted_in_capturing(): boolean

Check if the user has opted in to capturing.

Returns

boolean

Whether the user has opted in

has_opted_out_capturing()

has_opted_out_capturing(): boolean

Check if the user has opted out of capturing.

Returns

boolean

Whether the user has opted out

identify()

identify(new_distinct_id, userPropertiesToSet?, userPropertiesToSetOnce?): void

Identify a user with a distinct ID and optionally set person properties.

Parameters
Parameter Type Description
new_distinct_id string A non-empty distinct ID for the user
userPropertiesToSet? Properties Properties to set on the user (using $set)
userPropertiesToSetOnce? Properties Properties to set once on the user (using $set_once)
Returns

void

init()

init(token, config?, name?): PostHog

Initializes a new instance of the PostHog capturing object.

Parameters
Parameter Type Description
token string Your PostHog API token
config? Partial<PostHogConfig> A dictionary of config options to override
name? string The name for the new posthog instance that you want created
Returns

PostHog

The newly initialized PostHog instance

isFeatureEnabled()
Call Signature

isFeatureEnabled(key, options): boolean

Check if a feature flag is enabled.

Parameters
Parameter Type Description
key string The feature flag key
options FeatureFlagOptions & object & object Options for the feature flag lookup
Returns

boolean

Whether the feature flag is enabled

Call Signature

isFeatureEnabled(key, options?): boolean | undefined

Parameters
Parameter Type
key string
options? IsFeatureEnabledOptions
Returns

boolean | undefined

loadToolbar()

loadToolbar(params): boolean

Load the PostHog toolbar.

Parameters
Parameter Type Description
params ToolbarParams Toolbar parameters
Returns

boolean

Whether the toolbar was loaded

on()

on(event, cb): () => void

Register an event listener.

Parameters
Parameter Type Description
event "eventCaptured" | "featureFlagsReloading" The event name to listen for
cb (...args) => void The callback to call
Returns

A function to unsubscribe

() => void

onActiveMatchingSurveysChanged()

onActiveMatchingSurveysChanged(callback): () => void

Observe the initial matching surveys and updates after event/action and survey lifecycle changes, definitions refreshes, captured pageviews, feature-flag updates, and reset. URL changes require a captured pageview; arbitrary DOM mutations and elapsed time are not observed. Unchanged results are suppressed. Recoverable load errors are reported through the optional context without ending the subscription.

Parameters
Parameter Type Description
callback (surveys, context?) => void Callback to receive the active matching surveys
Returns

A function to unsubscribe

() => void

onFeatureFlags()

onFeatureFlags(callback): () => void

Register a callback to be called when feature flags are loaded.

Parameters
Parameter Type Description
callback FeatureFlagsCallback The callback to call
Returns

A function to unsubscribe

() => void

onSessionId()

onSessionId(callback): () => void

Register a callback to be called when the session ID changes.

Parameters
Parameter Type Description
callback SessionIdChangedCallback The callback to call
Returns

A function to unsubscribe

() => void

opt_in_capturing()

opt_in_capturing(): void

Opt the user into capturing.

Returns

void

opt_out_capturing()

opt_out_capturing(): void

Opt the user out of capturing.

Returns

void

register()

register(properties, days?): void

Register properties to be sent with every event.

Parameters
Parameter Type Description
properties Properties The properties to register
days? number Number of days to persist the properties
Returns

void

register_for_session()

register_for_session(properties): void

Register properties for the current session only.

Parameters
Parameter Type Description
properties Properties The properties to register
Returns

void

register_once()

register_once(properties, default_value?, days?): void

Register properties to be sent with every event, but only if they haven't been set before.

Parameters
Parameter Type Description
properties Properties The properties to register
default_value? any Default value for the property
days? number Number of days to persist the properties
Returns

void

reloadFeatureFlags()

reloadFeatureFlags(): void

Reload feature flags from the server.

Returns

void

renderSurvey()

renderSurvey(surveyId, selector): void

Render a survey in a specific container.

Parameters
Parameter Type Description
surveyId string The survey ID
selector string CSS selector for the container
Returns

void

reset()

reset(options?): void

Reset the user's identity and start a new session.

Parameters
Parameter Type Description
options? boolean | ResetOptions Boolean to reset the device ID (legacy), or reset options including bootstrap values.
Returns

void

Remarks

This also clears the stored consent, so with opt_out_capturing_by_default the instance is opted out again afterwards — call reset() before opt_in_capturing(), not after.

resetGroupPropertiesForFlags()

resetGroupPropertiesForFlags(group_type?): void

Reset group properties used for feature flag evaluation.

Parameters
Parameter Type Description
group_type? string Optional group type to reset (resets all if not provided)
Returns

void

resetGroups()

resetGroups(): void

Reset all groups for the current user.

Returns

void

resetPersonPropertiesForFlags()

resetPersonPropertiesForFlags(reloadFeatureFlags?): void

Reset person properties used for feature flag evaluation.

Parameters
Parameter Type Description
reloadFeatureFlags? boolean Whether to reload feature flags after resetting
Returns

void

sessionRecordingStarted()

sessionRecordingStarted(): boolean

Check if session recording has started.

Returns

boolean

Whether session recording has started

set_config()

set_config(config): void

Update the configuration.

Parameters
Parameter Type Description
config Partial<PostHogConfig> The configuration to merge
Returns

void

setGroupPropertiesForFlags()

setGroupPropertiesForFlags(properties, reloadFeatureFlags?): void

Set group properties to be used for feature flag evaluation.

Parameters
Parameter Type Description
properties {[type: string]: Properties; } The properties to set (keyed by group type)
reloadFeatureFlags? boolean Whether to reload feature flags after setting
Returns

void

setIdentity()

setIdentity(distinctId, hash): void

Set HMAC-based identity verification.

Parameters
Parameter Type Description
distinctId string The verified user distinct_id
hash string HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings
Returns

void

setInternalOrTestUser()

setInternalOrTestUser(): void

Marks the current user as a test user by setting the $internal_or_test_user person property to true. This also enables person processing for the current user.

This is useful for using in a cohort your internal/test filters for your posthog org.

Returns

void

See

https://posthog.com/tutorials/filter-internal-users Create a cohort with $internal_or_test_user IS SET, and set your internal test filters to be NOT IN that cohort.

Example
 1// Manually mark as test user
 2posthog.setInternalOrTestUser()
 3
 4// Or use internal_or_test_user_hostname config for automatic detection
 5posthog.init('token', { internal_or_test_user_hostname: 'localhost' })
setPersonProperties()

setPersonProperties(userPropertiesToSet?, userPropertiesToSetOnce?): void

Set properties on the current user.

Parameters
Parameter Type Description
userPropertiesToSet? Properties Properties to set on the user (using $set)
userPropertiesToSetOnce? Properties Properties to set once on the user (using $set_once)
Returns

void

setPersonPropertiesForFlags()

setPersonPropertiesForFlags(properties, reloadFeatureFlags?): void

Set person properties to be used for feature flag evaluation.

Parameters
Parameter Type Description
properties Properties The properties to set
reloadFeatureFlags? boolean Whether to reload feature flags after setting
Returns

void

shutdown()

shutdown(shutdownTimeoutMs?): Promise<void>

Flush any queued events and gracefully tear down the SDK.

Parameters
Parameter Type Description
shutdownTimeoutMs? number Accepted for parity with the Node.js SDK; unused in the browser.
Returns

Promise<void>

Resolves once teardown is complete.

Remarks

Provided for parity with the server-side Node.js SDK. In the browser the SDK already flushes on page unload, so this best-effort flushes queued events and always resolves — it never throws — which makes isomorphic teardown safe.

startExceptionAutocapture()

startExceptionAutocapture(config?): void

Start automatic exception capture.

Parameters
Parameter Type Description
config? ExceptionAutoCaptureConfig Optional configuration for exception autocapture
Returns

void

startSessionRecording()

startSessionRecording(override?): void

Start session recording (if not already started).

Parameters
Parameter Type Description
override? true | { event_trigger?: true; linked_flag?: boolean; sampling?: boolean; url_trigger?: true; } Options to override default behavior, or true to override all controls
Returns

void

stopExceptionAutocapture()

stopExceptionAutocapture(): void

Stop automatic exception capture.

Returns

void

stopSessionRecording()

stopSessionRecording(): void

Stop session recording.

Returns

void

unregister()

unregister(property): void

Unregister a property so it is no longer sent with events.

Parameters
Parameter Type Description
property string The property name to unregister
Returns

void

unregister_for_session()

unregister_for_session(property): void

Unregister a session property.

Parameters
Parameter Type Description
property string The property name to unregister
Returns

void

unsetPersonProperties()

unsetPersonProperties(propertyNames): void

Remove properties from the current user.

Parameters
Parameter Type Description
propertyNames string | string[] The name (or names) of the person properties to remove (using $unset)
Returns

void

updateEarlyAccessFeatureEnrollment()

updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage?): void

Update enrollment in an early access feature.

Parameters
Parameter Type Description
key string The feature key
isEnrolled boolean Whether the user is enrolled
stage? EarlyAccessFeatureStage The stage of the feature
Returns

void

updateFlags()

updateFlags(flags, payloads?, options?): void

Manually update feature flag values without making a network request.

Parameters
Parameter Type Description
flags Record<string, boolean | string> An object mapping flag keys to their values (boolean or string variant)
payloads? Record<string, JsonType> Optional object mapping flag keys to their JSON payloads
options? { merge?: boolean; } Optional settings. Use { merge: true } to merge with existing flags instead of replacing.
options.merge? boolean -
Returns

void

PostHogConfig

PostHogConfig = Omit<PostHogConfig, "loaded"> & object

Type Declaration

Name Type Description
disableDeviceModel? boolean Disables capturing the $device_model super-property. When capturing is enabled (the default), PostHog resolves the hardware model once during init via navigator.userAgentData.getHighEntropyValues(['model']) and registers it as the raw OEM code (e.g. Pixel 7). This is Chromium-only and only meaningful on Android — it resolves to undefined on Safari/Firefox and to an empty string on desktop, in which cases nothing is registered. This opt-out is offered because getHighEntropyValues is still experimental and Chromium-only (not yet a cross-browser standard); set it to true to skip the call entirely. Default false
loaded() (posthog) => void -

PostHogConfig

Configuration options for the PostHog JavaScript SDK.

See

https://posthog.com/docs/libraries/js#config

Properties

Property Type Description
__add_tracing_headers? string[] Deprecated Use tracing_headers instead. Kept for backwards compatibility.
__preview_capture_bot_pageviews? boolean PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION Enables collection of bot traffic as $bot_pageview events with detailed bot detection properties instead of dropping them entirely. Use it alongside opt_out_useragent_filter
__preview_cookie_wins_on_conflict boolean Deprecated Use cookieWinsOnConflict instead.
__preview_deferred_init_extensions boolean Experimental EXPERIMENTAL: Defers initialization of non-critical extensions (autocapture, session recording, etc.) to the next event loop tick using setTimeout. This reduces main thread blocking during SDK initialization for better page load performance, while keeping critical functionality (persistence, sessions, capture) available immediately. When enabled: - Persistence, sessions, and basic capture work immediately - Extensions (autocapture, recording, heatmaps, etc.) start after yielding back to the browser Default false (will be true for defaults >= '2025-11-06' in the future) @experimental
__preview_disable_beacon? boolean Deprecated Use disable_beacon instead.
__preview_disable_xhr_credentials? boolean Deprecated This option is a no-op. The browser SDK no longer sets XMLHttpRequest.withCredentials.
__preview_eager_load_replay? boolean Deprecated This option is a no-op. Session replay is lazy-loaded by default.
__preview_external_dependency_versioned_paths? string | boolean Deprecated Use strict_script_versioning and asset_host instead. When set to true, this is equivalent to strict_script_versioning: true. When set to a string, this is equivalent to strict_script_versioning: true and asset_host set to that string.
__preview_flags_v2? boolean Deprecated This option is a no-op. The browser SDK already uses the /flags/?v=2 endpoint.
__preview_lazy_load_replay? boolean Deprecated - does nothing was present only for PostHog testing of replay lazy loading
__preview_replay_sync_fetch? boolean Private preview: invoke recorded fetch requests synchronously to preserve application error stacks. Enabled by default in new cores; set to false to retain legacy fetch ordering. An old core without this option also retains legacy ordering when it loads a new recorder. Applied when the recorder installs its network observers, not a live remote kill switch. Default true
_onCapture (eventName, eventData) => void Deprecated - use before_send instead
addTracingHeaders? string[] Deprecated Use tracing_headers instead. Kept for backwards compatibility.
advanced_disable_decide? boolean Deprecated Use advanced_disable_flags instead. This will be removed in a future major version. One of the very first things the PostHog library does when init() is called is make a request to the /decide endpoint on PostHog's backend. This endpoint contains information on how to run the PostHog library so events are properly received in the backend. This endpoint is required to run most features of the library. However, if you're not using any of the described features, you may wish to turn off the call completely to avoid an extra request and reduce resource usage on both the client and the server. Default false
advanced_disable_feature_flags boolean Will keep /flags running, but without evaluating any feature flags. Useful for when you need to load the config data associated with the flags endpoint (e.g. /flags?v=2&config=true) without evaluating any feature flags. Most folks use this to save money on feature flag evaluation (by bootstrapping feature flags on the server side). This also stops surveys from displaying. PostHog creates an internal targeting flag for almost every survey, and every flag evaluates to false while flags are disabled. If you use surveys, set advanced_only_evaluate_survey_feature_flags instead, which evaluates survey flags only. Default false
advanced_disable_feature_flags_on_first_load boolean Stops from firing feature flag requests on first page load. Only requests feature flags when user identity or properties are updated, or you manually request for flags to be loaded. Default false
advanced_disable_flags? boolean One of the very first things the PostHog library does when init() is called is make a request to the /flags endpoint on PostHog's backend. This endpoint contains information on how to run the PostHog library so events are properly received in the backend, and it also contains feature flag evaluation information for the current user. This endpoint is required to run most features of this library. However, if you're not using any of the described features, you may wish to turn off the call completely to avoid an extra request and reduce resource usage on both the client and the server. WARNING: Disabling this will also prevent remote configuration from loading, which could mean features like web vitals, surveys, and other features configured in PostHog settings are disabled unless explicitly enabled via client-side config. When setting this to true, make sure to explicitly configure any features you want to use (e.g., capture_performance, autocapture, etc.) in your SDK's init config. Default false
advanced_disable_toolbar_metrics boolean Determines whether PostHog should disable toolbar metrics. This is our internal instrumentation for our toolbar in your website. Default false
advanced_enable_surveys boolean When this is enabled, surveys will always be initialized, regardless of the /flags response or remote config settings. This is useful if you want to use surveys but disable all other flag-dependent functionality. Used internally for displaying external surveys without making a /flags request. Default false
advanced_feature_flags_dedup_per_session boolean When enabled, $feature_flag_called event deduplication is scoped to the current session. By default, the SDK deduplicates $feature_flag_called events globally and only re-emits them when identify (with a new distinct ID) or reset is called. This can be problematic for experiments: if a flag is checked before an experiment starts, the event is cached and won't fire again for that user until identify/reset, meaning the experiment never sees the event. When this option is true, the deduplication cache is keyed on the session ID, so each new session will re-emit $feature_flag_called for every flag that is checked. Default false
advanced_only_evaluate_survey_feature_flags boolean Determines whether PostHog should only evaluate feature flags for surveys. Useful for when you want to use this library to evaluate feature flags for surveys only but you have additional feature flags that you evaluate on the server side. Default false
api_host string URL of your PostHog instance. Default 'https://us.i.posthog.com'
api_method? string Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons
api_transport? "XHR" | "fetch" The transport method to use for API requests. Default 'fetch'
asset_host string | null Optional host override for static assets loaded by PostHog, such as recorder.js, surveys.js, or toolbar.js. Only applies to /static/* asset paths; dynamic assets like remote config continue to use the regular asset host derived from api_host. Default null
autocapture boolean | AutocaptureConfig Determines whether PostHog should autocapture events. This setting does not affect capturing pageview events (see capture_pageview). by default autocapture is ignored on elements that match a ph-no-capture css class on the element or a parent 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. 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[] Used to extend the list of user agents that are blocked by default. See from './utils/blocked-uas' - Default list of blocked user agents. Default []
custom_campaign_params string[] Used to extend the list of campaign parameters that are saved by default. See from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc. Default []
custom_personal_data_properties string[] Custom list of personal data properties to mask. E.g. if you added email to this list, then any email property in the URL will be masked. https://www.example.com/login?email=john.doe%40example.com => https://www.example.com/login?email=
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
enable_heatmaps? boolean Deprecated Use capture_heatmaps instead.
enable_recording_console_log? boolean Determines whether PostHog should enable recording console logs. This is related to the Session Recording feature. For more session recording settings, see the session_recording and capture_performance configuration option. When undefined, it falls back to the remote config setting. Default undefined
error_tracking ErrorTrackingOptions Determines the error tracking options. See ErrorTrackingOptions Default {}
evaluation_contexts? readonly string[] Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'web', 'checkout'] Default undefined
evaluation_environments? readonly string[] Evaluation environments for feature flags. Deprecated Use evaluation_contexts instead. This property will be removed in a future version.
external_scripts_inject_target? "body" | "head" Where to inject external dependency scripts (recorder, surveys, etc.) in the DOM. - 'body': Injects scripts into document.body (legacy behavior) - 'head': Injects scripts into document.head (avoids SSR hydration errors) Default 'body' (or 'head' when defaults >= '2026-01-30')
feature_flag_cache_ttl_ms? number Sets the maximum age (in milliseconds) for cached feature flag values. When the cache is older than this value: - getFeatureFlag() will return undefined instead of stale cached values - $feature/ properties will not be attached to events - A background refresh will be triggered automatically This prevents stale feature flag values from being used when the /flags request fails (e.g., due to ad blockers or network issues). When not set or set to 0, cache expiration is disabled (cached values never expire). Default 0
feature_flag_request_max_retries number How many times to retry a /flags request before giving up. Only failures that are plausibly transient are retried: HTTP 502 and 504, and a request that timed out. Every other status is terminal, as is a transport failure that is not a timeout — in a browser those are usually an ad blocker, an extension or CORS, which the status-zero circuit breaker already handles, so retrying them would only add a second doomed request. Set to 0 to disable retries. Default 1
feature_flag_request_timeout_ms number Sets timeout for fetching feature flags Default 3000
fetch_options? object Used when sending data via fetch, use with care. This is intentionally meant to be used with NextJS fetch Incorrect cache usage may cause out-of-date data for feature flags, actions tracking, etc. See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options
fetch_options.cache? RequestCache -
fetch_options.next_options? NextOptions -
flag_keys? readonly string[] List of feature flag keys to remotely evaluate for this SDK instance. When set, only these flags are evaluated by /flags; omitted flags are not remotely evaluated. Dependencies of the requested flags may still be evaluated internally by PostHog. If unset, all eligible flags are evaluated. Examples: ['checkout-redesign', 'new-onboarding'] Default undefined
flags_api_host? string | null URL to use for feature flag requests specifically. If not set, feature flag requests will use the URL derived from api_host. This is useful when you want to route feature flag requests to a different endpoint than other analytic APIs. Default null
get_current_url? (defaultUrl) => string Overrides the URL used for client-side URL targeting: session replay URL triggers, the session replay URL blocklist, survey URL display conditions, product tour URL conditions, web experiment URL conditions, and autocapture URL allow/ignore lists. These features match against window.location.href directly, which does not reflect any $current_url you rewrite in before_send. In environments where the browser URL is not meaningful for targeting — e.g. Electron/desktop apps served from a generated host — return the logical URL you want these features to match against. This does not change the $current_url property captured on events (use before_send for that). Default undefined (uses window.location.href)
get_device_id (uuid) => string Function to get the device ID. This doesn't usually need to be set, but can be useful if you want to use a custom device ID. Default (uuid) => uuid
identity_claims? Record<string, { hash: string; value: string; }> Additional server-signed identity claims. Claims are forwarded to products such as conversations only when identity_distinct_id and identity_hash are also present. Claim verification and consumption happen server-side.
identity_distinct_id? string Verified distinct_id for HMAC-based identity verification. When both identity_distinct_id and identity_hash are provided, products like conversations use server-verified identity instead of anonymous session identifiers. Can be set at init time or later via posthog.setIdentity(). Example posthog.init('phc_...', { identity_distinct_id: 'user_123', identity_hash: 'a1b2c3d4e5f6...', })
identity_hash? string HMAC-SHA256 of identity_distinct_id, signed with the Secret API key from Support settings. Project secret API keys (project settings) and personal API keys are rejected. Must be provided together with identity_distinct_id.
inapp_link_new_window? boolean Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons
inapp_protocol? string Deprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons
integrations? Record<ExternalIntegrationKind, boolean> Used to set-up external integrations with PostHog data - such as session replays, distinct id, etc.
internal_or_test_user_hostname? string | RegExp | null A hostname pattern to match test environments. When the current hostname matches, setInternalOrTestUser() is called automatically on startup, enabling person processing and setting $internal_or_test_user: true. Can be a string (exact match) or RegExp (pattern match). Set to null to explicitly disable (useful when using defaults: '2026-01-30'). Default undefined (when defaults is before '2026-01-30') Default /^(localhost|127\.0\.0\.1)$/ (when defaults >= '2026-01-30') Example // Exact match posthog.init('token', { internal_or_test_user_hostname: 'example.com' }) // Regex pattern posthog.init('token', { internal_or_test_user_hostname: /\.local$/ }) // Disable posthog.init('token', { internal_or_test_user_hostname: null })
ip boolean Deprecated - THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. Use a custom transformation or "Discard IP data" project setting instead: See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address.
loaded (posthog_instance) => void A function to be called once the PostHog scripts have loaded successfully.
logs? LogsConfig Logs-specific configuration options. Default undefined
mask_all_element_attributes boolean Prevent autocapture from capturing any attribute names on elements. Default false
mask_all_text boolean Prevent autocapture from capturing textContent on elements. Default false
mask_personal_data_properties boolean Mask personal data properties from the current URL. This will mask personal data properties such as advertising IDs (gclid, fbclid, etc.), and you can also add custom properties to mask with custom_personal_data_properties. Default false See - - Default 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) => void A function that is called when a request to the PostHog API fails.
on_xhr_error? (failedRequest) => void Deprecated - use on_request_error instead
opt_in_site_apps boolean Determines if users should be opted in to site apps. Default false
opt_out_capturing_by_default boolean Determines if users should be opted out of PostHog tracking by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing(). Default false
opt_out_capturing_cookie_prefix string | null Deprecated Use consent_persistence_name instead. This will be removed in a future major version.
opt_out_capturing_persistence_type "localStorage" | "cookie" Determines where we'll save the information about whether users are opted out of capturing. Default 'localStorage'
opt_out_persistence_by_default? boolean Determines if users should be opted out of browser data storage by this PostHog instance by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing(). Default false
opt_out_useragent_filter boolean Determines if users should be opted out of user agent filtering such as googlebot or other bots. If this is set to true, PostHog will set $browser_type to either bot or browser for all events, but will process all events as if they were from a browser. When the filter drops events, a one-time warning is written to the console (even without debug mode). The filter applies to events only; logs sent with captureLog bypass it. Set this to true behind a test flag for end-to-end tests (Playwright, Puppeteer). Default false
override_display_language? string | null Display language override for Product Tours. Must be a valid BCP 47 language code. In the future this will be used for Surveys and other products that deliver in-app experiences to end-users.
persistence "localStorage" | "cookie" | "memory" | "localStorage+cookie" | "sessionStorage" Determines how PostHog stores information about the user. See persistence for details. 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 | null A function to be called when a script is being loaded. This can be used to modify the script before it is loaded. This is useful for adding a nonce to the script, for example.
prepare_external_dependency_stylesheet? (stylesheet) => HTMLStyleElement | null A function to be called when a stylesheet is being loaded. This can be used to modify the stylesheet before it is loaded. This is useful for adding a nonce to the stylesheet, for example.
process_person? "always" | "never" | "identified_only" Deprecated - use person_profiles instead
properties_string_max_length number Determines the maximum length of the properties string that can be sent with capture calls. Default 65535
property_blacklist? string[] Deprecated - use property_denylist instead
property_denylist string[] A list of properties that should never be sent with capture calls. Default []
rageclick boolean | RageclickConfig Determines whether PostHog should capture rage clicks. By default, rage clicks are ignored on elements that match a ph-no-capture or ph-no-rageclick CSS class on the element or a parent. When defaults is '2025-11-30' or later, the default is { content_ignorelist: true }, which also ignores repeat-click controls such as pagination arrows and pagers (see content_ignorelist). When defaults is '2026-05-30' or later, the default also excludes stepper controls (+, -, −, –) and text-selection surfaces. Default true
rate_limiting? object Client side rate limiting. A token bucket, per browser, that stops a runaway loop on your site from flooding capture. When it drains, further capture calls are dropped and a one-off $$client_ingestion_warning is sent reporting how many events were dropped and the page and session that tripped it - usually the fastest way to find the loop. Raise these limits if you legitimately capture in bursts; a warning under the defaults is more often a bug on the page than a limit set too low.
rate_limiting.events_burst_limit? number How many events can be captured in a burst. This defaults to 10 times the events_per_second count Default 10 * events_per_second
rate_limiting.events_per_second? number The average number of events per second that should be permitted Default 10
remote_config_refresh_interval_ms? number Controls how often feature flags are automatically refreshed in long-running sessions. The default interval is 5 minutes (300000ms) to pick up server-side flag changes without requiring a page reload. This is useful for SPAs and long-running tabs. An explicitly set positive interval stays fixed, even when the page gets no user interaction. Each refresh is a billable feature flag request. A page that stays open all day makes up to 288 requests per day on the default interval, and every open tab and every named instance refreshes on its own timer, so they add up. Set this option to 0 to stop the background refreshes if that cost is not useful to you. Tradeoffs: - Shorter intervals: Feature flag changes propagate faster, but increases network requests, cost, and server load. - Longer intervals: Reduces network traffic (better for mobile/battery) and cost, but flag changes take longer to propagate. - Disabled (0 or any negative value): No background refreshes. Flags only update on page load or manual reloadFeatureFlags() calls. Use this if you control flag updates manually or have infrequent flag changes. Hidden pages skip scheduled refreshes and reload due flags when they become visible. When this option is omitted, a visible page that gets no user interaction (such as a dashboard, a page being read, a video player, or a kiosk) doubles the interval after every refresh, up to one hour. Automatic refreshes continue at that interval; they do not stop. The next click, key press, wheel, touch, or return to visibility restores the five-minute default. Scrolling driven by a script, such as an auto-playing carousel, does not count as an interaction. Set this option explicitly to keep a fixed cadence, or to 0 to stop background refreshes completely. This option does not reload remote config. Default 300000 (5 minutes)
request_batching boolean Determines whether PostHog should batch requests to the PostHog API. Default true
request_headers object A list of headers that should be sent with requests to the PostHog API. Default {}
request_queue_config? RequestQueueConfig Used to change the behavior of the request queue. This is an advanced feature and should be used with caution.
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 Rewrites the URL used for PostHog API, feature flag, and asset requests. This is intended for customers who use a reverse proxy and need custom paths. The proxy must map the rewritten paths back to the canonical PostHog paths. UI links are not rewritten. Example posthog.init('phc_...', { api_host: 'https://a.example.com', rewriteRequestPath: (url) => { if (url.pathname === '/e/') { url.pathname = '/my-events/' } else if (url.pathname === '/s/') { url.pathname = '/my-replay/' } else if (url.pathname === '/flags/') { url.pathname = '/my-flags/' } return url }, })
sanitize_properties ((properties, event_name) => Properties) | null Deprecated - use before_send instead
save_campaign_params boolean Determines whether PostHog should save marketing parameters. These are utm_* paramaters and friends. See from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc. Default true
save_referrer boolean Determines whether PostHog should save referrer information. Default true
scroll_root_selector? string | string[] Let the pageview scroll stats use a custom css selector for the root element, e.g. main It will use window.document.documentElement if not specified.
secure_cookie boolean Determines whether PostHog should use secure cookies. If this is true, PostHog cookies will be marked as secure, meaning they will only be transmitted over HTTPS. Default window.location.protocol === 'https:'
segment? SegmentIntegrationConfig | SegmentAnalytics The Segment analytics object, or integration configuration. Example segment: { analytics: window.analytics, filterProperties: (properties) => { for (const key in properties) { if (key.startsWith('$sdk_debug_')) { delete properties[key] } } return properties } } See https://posthog.com/docs/libraries/segment
session_idle_timeout_seconds number Determines the session idle timeout in seconds. If no events are captured for this many seconds, the next event starts a new session with a new $session_id (and $window_id). The SDK may also proactively reset the stored session after the timeout while the page is idle, so the next event creates a new session. Session recording has a separate idle threshold: session_recording.session_idle_threshold_ms. That setting only controls when the user is considered idle, it does not rotate $session_id. Must be between 60 seconds and 10 hours. Values outside this range are clamped. Default 30 * 60 -- 30 minutes
session_recording SessionRecordingOptions Determines the session recording options. For more session recording settings, see the enable_recording_console_log and capture_performance configuration option. When defaults is '2025-11-30' or later, strictMinimumDuration defaults to true. See SessionRecordingOptions Default {}
split_storage? boolean Store the feature-flag config cluster and survey config in their own localStorage entries (<name>__flags, <name>__surveys) instead of the single main persistence blob. These payloads are large and change rarely, so keeping them out of the main blob stops them riding on every high-frequency main-blob write and broadcasting cross-tab storage events. Only applies when persistence resolves to localStorage / localStorage+cookie (the split is pointless for memory / sessionStorage and impossible for cookie). On load the old main-blob location is read once and migrated forward, so upgrades never miss a cached flag. The 2026-05-30 config default opts in. Default false
store_google? boolean Deprecated - Use save_campaign_params instead
strict_script_versioning boolean | "fallback" Determines whether PostHog should load external dependency scripts from semver-qualified asset paths such as /static/1.370.0/recorder.js instead of the legacy /static/recorder.js?v=1.370.0 form. Set to true to use only versioned paths, false to use only legacy paths, or 'fallback' to try the versioned path first and retry with the legacy path if it fails. Default 'fallback'
surveys? SurveyConfig Survey-specific configuration options. Default undefined
surveys_request_timeout_ms number Sets timeout for fetching surveys Default 10000
token string The token for your PostHog project. It should NOT be provided manually in the config, but rather passed as the first parameter to posthog.init().
trace_propagation_targets? string[] Hosts that should receive a W3C Trace Context traceparent header on fetch and XMLHttpRequest requests, so your backend can continue the trace started in the browser. Each request gets a new trace id and span id, with the sampled flag set (00-<trace-id>-<span-id>-01). The browser does not record a span of its own, so the span id in the header is the parent of your server's root span. Matching is exact and nothing is sent to unlisted hosts: - an entry with a scheme (https://api.example.com, http://localhost:8000) matches that origin only - any other entry (api.example.com) matches that hostname on any scheme or port Only list hosts that accept the header. A cross-origin request with a traceparent header triggers a CORS preflight, and fails if the server's Access-Control-Allow-Headers doesn't include traceparent. A traceparent header already set by your app or by OpenTelemetry's instrumentation is never overwritten or duplicated. If OpenTelemetry's XHR instrumentation also propagates to a cross-origin host (its propagateTraceHeaderCorsUrls), list that host in only one of the two. Example posthog.init('<token>', { trace_propagation_targets: ['https://api.example.com', 'internal.example.com'] })
tracing_headers? string[] A list of hostnames for which to inject PostHog tracing headers to all requests (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID, X-POSTHOG-WINDOW-ID). Used to link frontend sessions to backend traces (see https://posthog.com/docs/llm-analytics/link-session-replay).
ui_host string | null If using a reverse proxy for api_host then this should be the actual PostHog app URL (e.g. https://us.posthog.com). This ensures that links to PostHog point to the correct host. Default null
upgrade boolean Determines whether PostHog should upgrade old cookies. If set to true, the library will check for a cookie from our old js library and import super properties from it, then the old cookie is deleted. This option only works in the initialization, so make sure you set it when you create the library. Default false
verbose? boolean Deprecated Use debug instead
xhr_headers? object Deprecated - use request_headers instead

PostHogFeatureFlags

Legacy constructor and configuration mapping for the shared flags extension.

Extends

  • PostHogFeatureFlags

Constructors

Constructor

new PostHogFeatureFlags(instance): PostHogFeatureFlags

Parameters
Parameter Type
instance PostHog
Returns

PostHogFeatureFlags

Properties

Property Modifier Type Default value Description Overrides Inherited from
_override_warning public boolean undefined - - PostHogFeatureFlags._override_warning
$anon_distinct_id public string | undefined undefined - - PostHogFeatureFlags.$anon_distinct_id
featureFlagEventHandlers public FeatureFlagsCallback[] undefined - - PostHogFeatureFlags.featureFlagEventHandlers
name readonly ExtensionToken<PostHogFeatureFlags> FeatureFlagsExtension Stable extension name used for diagnostics and de-duplication within a client instance. PostHogFeatureFlags.name -

Accessors

hasLoadedFlags
Get Signature

get hasLoadedFlags(): boolean

Returns

boolean

Methods

_callFlagsEndpoint()

_callFlagsEndpoint(options?): void

Parameters
Parameter Type
options? { disableFlags?: boolean; }
options.disableFlags? boolean
Returns

void

_fireFeatureFlagsCallbacks()

_fireFeatureFlagsCallbacks(errorsLoading?): void

Parameters
Parameter Type
errorsLoading? boolean
Returns

void

_prepareFeatureFlagsForCallbacks()

_prepareFeatureFlagsForCallbacks(): object

Returns

object

Name Type
flags string[]
flagVariants Record<string, string | boolean>
addFeatureFlagsHandler()

addFeatureFlagsHandler(handler): void

Parameters
Parameter Type
handler FeatureFlagsCallback
Returns

void

destroy()

destroy(): void

Returns

void

dispose()

dispose(): void

Release final resources synchronously. Feature-level start/stop remains extension-owned.

Returns

void

ensureFlagsLoaded()

ensureFlagsLoaded(): void

Returns

void

getAllFeatureFlags()

getAllFeatureFlags(): FeatureFlagResult[]

Returns

FeatureFlagResult[]

getEarlyAccessFeatures()

getEarlyAccessFeatures(callback, force_reload?, stages?): void

Parameters
Parameter Type
callback EarlyAccessFeatureCallback
force_reload? boolean
stages? EarlyAccessFeatureStage[]
Returns

void

getFeatureFlag()

getFeatureFlag(key, options?): string | boolean | undefined

Get feature flag's value for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

An evaluated boolean flag returns true or false; undefined means no current evaluation is available for the key. Globally inactive flags are omitted from the remote /flags response, so after that response loads they are unavailable rather than represented by a false result.

Usage:

if(posthog.getFeatureFlag('my-flag') === 'some-variant') { // do something }

// Only use fresh values from the server (returns undefined until /flags responds)
if(posthog.getFeatureFlag('my-flag', { fresh: true }) === 'some-variant') { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Optional settings.
Returns

string | boolean | undefined

The flag value, or undefined if no current evaluation is available.

getFeatureFlagDetails()

getFeatureFlagDetails(key): FeatureFlagDetail | undefined

Parameters
Parameter Type
key string
Returns

FeatureFlagDetail | undefined

getFeatureFlagPayload()

getFeatureFlagPayload(key): JsonType

Parameters
Parameter Type
key string
Returns

JsonType

Deprecated

Use getFeatureFlagResult() instead which properly tracks the feature flag call. getFeatureFlagPayload() does not emit the $feature_flag_called event which may result in missing analytics. This method will be removed in a future version.

getFeatureFlagResult()

getFeatureFlagResult(key, options?): FeatureFlagResult | undefined

Get a feature flag result including both the flag value and payload, while properly tracking the call. This method emits the $feature_flag_called event by default.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A result with enabled: false is a conclusive off evaluation. undefined means no current evaluation is available for the key. This includes globally inactive flags, which are omitted from the remote /flags response.

Usage:

const result = posthog.getFeatureFlagResult('my-flag')
if (result?.enabled) {
    console.log('Flag is enabled with payload:', result.payload)
}

// Only use fresh values from the server
const freshResult = posthog.getFeatureFlagResult('my-flag', { fresh: true })
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Options for the feature flag lookup.
Returns

FeatureFlagResult | undefined

The feature flag result including key, enabled, variant, and payload.

getFlagPayloads()

getFlagPayloads(): Record<string, JsonType>

Returns

Record<string, JsonType>

getFlags()

getFlags(): string[]

Returns

string[]

getFlagsWithDetails()

getFlagsWithDetails(): Record<string, FeatureFlagDetail>

Returns

Record<string, FeatureFlagDetail>

getFlagVariants()

getFlagVariants(): Record<string, string | boolean>

Returns

Record<string, string | boolean>

getRemoteConfigPayload()

getRemoteConfigPayload(key, callback): void

Parameters
Parameter Type
key string
callback RemoteConfigFeatureFlagCallback
Returns

void

initialize()

initialize(): void

Returns

void

isFeatureEnabled()
Call Signature

isFeatureEnabled(key, options?): boolean

See if feature flag is enabled for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A false result means the flag value evaluated off; it does not mean the SDK observed the flag's global active setting. When no current evaluation is available, this method returns options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted from the remote /flags response and therefore have no value.

Usage:

if(posthog.isFeatureEnabled('beta-feature')) { // do something }

// Only use fresh values from the server
if(posthog.isFeatureEnabled('beta-feature', { fresh: true })) { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions & object & object Optional settings.
Returns

boolean

Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

Call Signature

isFeatureEnabled(key, options?): boolean | undefined

See if feature flag is enabled for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A false result means the flag value evaluated off; it does not mean the SDK observed the flag's global active setting. When no current evaluation is available, this method returns options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted from the remote /flags response and therefore have no value.

Usage:

if(posthog.isFeatureEnabled('beta-feature')) { // do something }

// Only use fresh values from the server
if(posthog.isFeatureEnabled('beta-feature', { fresh: true })) { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? IsFeatureEnabledOptions Optional settings.
Returns

boolean | undefined

Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

onFeatureFlags()

onFeatureFlags(callback): () => void

Parameters
Parameter Type
callback FeatureFlagsCallback
Returns

() => void

onReloading()

onReloading(handler): () => void

Parameters
Parameter Type
handler () => void
Returns

() => void

override()

override(flags, suppressWarning?): void

Parameters
Parameter Type
flags boolean | string[] | Record<string, string | boolean>
suppressWarning? boolean
Returns

void

Deprecated

Use overrideFeatureFlags instead. This will be removed in a future version.

overrideFeatureFlags()

overrideFeatureFlags(overrideOptions): void

Override feature flags on the client-side. Useful for setting non-persistent feature flags, or for testing/debugging feature flags in the PostHog app.

Usage:

- posthog.featureFlags.overrideFeatureFlags(false) // clear all overrides
- posthog.featureFlags.overrideFeatureFlags(['beta-feature']) // enable flags
- posthog.featureFlags.overrideFeatureFlags({'beta-feature': 'variant'}) // set variants
- posthog.featureFlags.overrideFeatureFlags({ flags: ['beta-feature'] }) // enable flags
- posthog.featureFlags.overrideFeatureFlags({ flags: {'beta-feature': 'variant'} }) // set variants
- posthog.featureFlags.overrideFeatureFlags({ // set both flags and payloads
    flags: {'beta-feature': 'variant'},
    payloads: { 'beta-feature': { someData: true } }
  })
- posthog.featureFlags.overrideFeatureFlags({ // only override payloads
    payloads: { 'beta-feature': { someData: true } }
  })
Parameters
Parameter Type
overrideOptions OverrideFeatureFlagsOptions
Returns

void

receivedFeatureFlags()

receivedFeatureFlags(response, errorsLoading?, options?): void

Parameters
Parameter Type
response Partial<FlagsResponse>
errorsLoading? boolean
options? { partialResponse?: boolean; }
options.partialResponse? boolean
Returns

void

reloadFeatureFlags()

reloadFeatureFlags(): void

Reloads feature flags asynchronously.

Constraints:

  1. Avoid parallel requests
  2. Delay a few milliseconds after each reloadFeatureFlags call to batch subsequent changes together
Returns

void

reloadFeatureFlagsAsync()

reloadFeatureFlagsAsync(): Promise<FeatureFlagsReloadResult>

Await the next requested evaluation, rather than cached or locally injected flag changes.

Returns

Promise<FeatureFlagsReloadResult>

removeFeatureFlagsHandler()

removeFeatureFlagsHandler(handler): void

Parameters
Parameter Type
handler FeatureFlagsCallback
Returns

void

reset()

reset(): void

Returns

void

resetFlagCallReported()

resetFlagCallReported(): void

Returns

void

resetGroupPropertiesForFlags()

resetGroupPropertiesForFlags(group_type?): void

Parameters
Parameter Type
group_type? string
Returns

void

resetPersonPropertiesForFlags()

resetPersonPropertiesForFlags(reloadFeatureFlags?): void

Parameters
Parameter Type
reloadFeatureFlags? boolean
Returns

void

sendFlagCallsPendingCapture()

sendFlagCallsPendingCapture(): void

Sends $feature_flag_called for the flags read while capture was off, once the client can capture.

Returns

void

setAnonymousDistinctId()

setAnonymousDistinctId(anon_distinct_id): void

Parameters
Parameter Type
anon_distinct_id string | undefined
Returns

void

setGroupPropertiesForFlags()

setGroupPropertiesForFlags(properties, reloadFeatureFlags?): void

Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type. For example: setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })

Parameters
Parameter Type
properties {[type: string]: Properties; }
reloadFeatureFlags? boolean
Returns

void

setPersonPropertiesForFlags()

setPersonPropertiesForFlags(properties, reloadFeatureFlags?): void

Set override person properties for feature flags. This is used when dealing with new persons / where you don't want to wait for ingestion to update user properties.

Parameters
Parameter Type
properties Properties
reloadFeatureFlags? boolean
Returns

void

setReloadingPaused()

setReloadingPaused(isPaused): void

Parameters
Parameter Type
isPaused boolean
Returns

void

setup()

setup(client): void | Promise<void>

Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.

Parameters
Parameter Type
client Client
Returns

void | Promise<void>

unsetPersonPropertiesForFlags()

unsetPersonPropertiesForFlags(propertyNames, reloadFeatureFlags?): void

Remove override person properties used for feature flags. This is the counterpart to setPersonPropertiesForFlags, used when person properties are unset so flags re-evaluate without the removed values.

Parameters
Parameter Type
propertyNames string[]
reloadFeatureFlags? boolean
Returns

void

updateConfig()

updateConfig(config, remoteRequestsDisabled): void

Parameters
Parameter Type
config PostHogConfig
remoteRequestsDisabled boolean
Returns

void

updateEarlyAccessFeatureEnrollment()

updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage?): void

Parameters
Parameter Type
key string
isEnrolled boolean
stage? string
Returns

void

updateFlags()

updateFlags(flags, payloads?, options?): void

Parameters
Parameter Type
flags Record<string, boolean | string>
payloads? Record<string, JsonType>
options? { merge?: boolean; }
options.merge? boolean
Returns

void

PostHogFeatureFlags

A shared browser extension. The client calls setup(client) once to start it and optional dispose() once for final best-effort resource cleanup. Everything an extension consumes flows through its host, Client by default.

setup may be async so an extension can read async KV state or remote config before it is ready. Async extensions must guard work after each await so cleanup cannot be followed by late listener, timer, or patch installation. The disposables an extension creates in setup are its own to release.

An extension that exposes app-facing controls extends Extension with named methods that share its state, e.g.:

 1interface SessionReplayExtension extends Extension {
 2    startRecording(): void
 3    stopRecording(): void
 4    isActive(): boolean
 5}

Extended by

  • PostHogFeatureFlags

Implements

  • Extension

Constructors

Constructor

new PostHogFeatureFlags(configSource): PostHogFeatureFlags

Parameters
Parameter Type
configSource FeatureFlagsConfigSource
Returns

PostHogFeatureFlags

Properties

Property Modifier Type Description
_override_warning public boolean -
$anon_distinct_id public string | undefined -
featureFlagEventHandlers public FeatureFlagsCallback[] -
name readonly string Stable extension name used for diagnostics and de-duplication within a client instance.

Accessors

hasLoadedFlags
Get Signature

get hasLoadedFlags(): boolean

Returns

boolean

Methods

_callFlagsEndpoint()

_callFlagsEndpoint(options?): void

Parameters
Parameter Type
options? { disableFlags?: boolean; }
options.disableFlags? boolean
Returns

void

_fireFeatureFlagsCallbacks()

_fireFeatureFlagsCallbacks(errorsLoading?): void

Parameters
Parameter Type
errorsLoading? boolean
Returns

void

_prepareFeatureFlagsForCallbacks()

_prepareFeatureFlagsForCallbacks(): object

Returns

object

Name Type
flags string[]
flagVariants Record<string, string | boolean>
addFeatureFlagsHandler()

addFeatureFlagsHandler(handler): void

Parameters
Parameter Type
handler FeatureFlagsCallback
Returns

void

destroy()

destroy(): void

Returns

void

dispose()

dispose(): void

Release final resources synchronously. Feature-level start/stop remains extension-owned.

Returns

void

ensureFlagsLoaded()

ensureFlagsLoaded(): void

Returns

void

getAllFeatureFlags()

getAllFeatureFlags(): FeatureFlagResult[]

Returns

FeatureFlagResult[]

getEarlyAccessFeatures()

getEarlyAccessFeatures(callback, force_reload?, stages?): void

Parameters
Parameter Type
callback EarlyAccessFeatureCallback
force_reload? boolean
stages? EarlyAccessFeatureStage[]
Returns

void

getFeatureFlag()

getFeatureFlag(key, options?): string | boolean | undefined

Get feature flag's value for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

An evaluated boolean flag returns true or false; undefined means no current evaluation is available for the key. Globally inactive flags are omitted from the remote /flags response, so after that response loads they are unavailable rather than represented by a false result.

Usage:

if(posthog.getFeatureFlag('my-flag') === 'some-variant') { // do something }

// Only use fresh values from the server (returns undefined until /flags responds)
if(posthog.getFeatureFlag('my-flag', { fresh: true }) === 'some-variant') { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Optional settings.
Returns

string | boolean | undefined

The flag value, or undefined if no current evaluation is available.

getFeatureFlagDetails()

getFeatureFlagDetails(key): FeatureFlagDetail | undefined

Parameters
Parameter Type
key string
Returns

FeatureFlagDetail | undefined

getFeatureFlagPayload()

getFeatureFlagPayload(key): JsonType

Parameters
Parameter Type
key string
Returns

JsonType

Deprecated

Use getFeatureFlagResult() instead which properly tracks the feature flag call. getFeatureFlagPayload() does not emit the $feature_flag_called event which may result in missing analytics. This method will be removed in a future version.

getFeatureFlagResult()

getFeatureFlagResult(key, options?): FeatureFlagResult | undefined

Get a feature flag result including both the flag value and payload, while properly tracking the call. This method emits the $feature_flag_called event by default.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A result with enabled: false is a conclusive off evaluation. undefined means no current evaluation is available for the key. This includes globally inactive flags, which are omitted from the remote /flags response.

Usage:

const result = posthog.getFeatureFlagResult('my-flag')
if (result?.enabled) {
    console.log('Flag is enabled with payload:', result.payload)
}

// Only use fresh values from the server
const freshResult = posthog.getFeatureFlagResult('my-flag', { fresh: true })
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions Options for the feature flag lookup.
Returns

FeatureFlagResult | undefined

The feature flag result including key, enabled, variant, and payload.

getFlagPayloads()

getFlagPayloads(): Record<string, JsonType>

Returns

Record<string, JsonType>

getFlags()

getFlags(): string[]

Returns

string[]

getFlagsWithDetails()

getFlagsWithDetails(): Record<string, FeatureFlagDetail>

Returns

Record<string, FeatureFlagDetail>

getFlagVariants()

getFlagVariants(): Record<string, string | boolean>

Returns

Record<string, string | boolean>

getRemoteConfigPayload()

getRemoteConfigPayload(key, callback): void

Parameters
Parameter Type
key string
callback RemoteConfigFeatureFlagCallback
Returns

void

initialize()

initialize(): void

Returns

void

isFeatureEnabled()
Call Signature

isFeatureEnabled(key, options?): boolean

See if feature flag is enabled for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A false result means the flag value evaluated off; it does not mean the SDK observed the flag's global active setting. When no current evaluation is available, this method returns options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted from the remote /flags response and therefore have no value.

Usage:

if(posthog.isFeatureEnabled('beta-feature')) { // do something }

// Only use fresh values from the server
if(posthog.isFeatureEnabled('beta-feature', { fresh: true })) { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? FeatureFlagOptions & object & object Optional settings.
Returns

boolean

Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

Call Signature

isFeatureEnabled(key, options?): boolean | undefined

See if feature flag is enabled for user.

By default, this method may return cached values from localStorage if the /flags endpoint hasn't responded yet. This reduces flicker but means you might briefly see stale values (e.g., a flag that was made globally inactive on the server).

A false result means the flag value evaluated off; it does not mean the SDK observed the flag's global active setting. When no current evaluation is available, this method returns options.defaultValue if provided, otherwise undefined. Globally inactive flags are omitted from the remote /flags response and therefore have no value.

Usage:

if(posthog.isFeatureEnabled('beta-feature')) { // do something }

// Only use fresh values from the server
if(posthog.isFeatureEnabled('beta-feature', { fresh: true })) { // do something }
Parameters
Parameter Type Description
key string Key of the feature flag.
options? IsFeatureEnabledOptions Optional settings.
Returns

boolean | undefined

Whether the flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.

onFeatureFlags()

onFeatureFlags(callback): () => void

Parameters
Parameter Type
callback FeatureFlagsCallback
Returns

() => void

onReloading()

onReloading(handler): () => void

Parameters
Parameter Type
handler () => void
Returns

() => void

override()

override(flags, suppressWarning?): void

Parameters
Parameter Type
flags boolean | string[] | Record<string, string | boolean>
suppressWarning? boolean
Returns

void

Deprecated

Use overrideFeatureFlags instead. This will be removed in a future version.

overrideFeatureFlags()

overrideFeatureFlags(overrideOptions): void

Override feature flags on the client-side. Useful for setting non-persistent feature flags, or for testing/debugging feature flags in the PostHog app.

Usage:

- posthog.featureFlags.overrideFeatureFlags(false) // clear all overrides
- posthog.featureFlags.overrideFeatureFlags(['beta-feature']) // enable flags
- posthog.featureFlags.overrideFeatureFlags({'beta-feature': 'variant'}) // set variants
- posthog.featureFlags.overrideFeatureFlags({ flags: ['beta-feature'] }) // enable flags
- posthog.featureFlags.overrideFeatureFlags({ flags: {'beta-feature': 'variant'} }) // set variants
- posthog.featureFlags.overrideFeatureFlags({ // set both flags and payloads
    flags: {'beta-feature': 'variant'},
    payloads: { 'beta-feature': { someData: true } }
  })
- posthog.featureFlags.overrideFeatureFlags({ // only override payloads
    payloads: { 'beta-feature': { someData: true } }
  })
Parameters
Parameter Type
overrideOptions OverrideFeatureFlagsOptions
Returns

void

receivedFeatureFlags()

receivedFeatureFlags(response, errorsLoading?, options?): void

Parameters
Parameter Type
response Partial<FlagsResponse>
errorsLoading? boolean
options? { partialResponse?: boolean; }
options.partialResponse? boolean
Returns

void

reloadFeatureFlags()

reloadFeatureFlags(): void

Reloads feature flags asynchronously.

Constraints:

  1. Avoid parallel requests
  2. Delay a few milliseconds after each reloadFeatureFlags call to batch subsequent changes together
Returns

void

reloadFeatureFlagsAsync()

reloadFeatureFlagsAsync(): Promise<FeatureFlagsReloadResult>

Await the next requested evaluation, rather than cached or locally injected flag changes.

Returns

Promise<FeatureFlagsReloadResult>

removeFeatureFlagsHandler()

removeFeatureFlagsHandler(handler): void

Parameters
Parameter Type
handler FeatureFlagsCallback
Returns

void

reset()

reset(): void

Returns

void

resetFlagCallReported()

resetFlagCallReported(): void

Returns

void

resetGroupPropertiesForFlags()

resetGroupPropertiesForFlags(group_type?): void

Parameters
Parameter Type
group_type? string
Returns

void

resetPersonPropertiesForFlags()

resetPersonPropertiesForFlags(reloadFeatureFlags?): void

Parameters
Parameter Type
reloadFeatureFlags? boolean
Returns

void

sendFlagCallsPendingCapture()

sendFlagCallsPendingCapture(): void

Sends $feature_flag_called for the flags read while capture was off, once the client can capture.

Returns

void

setAnonymousDistinctId()

setAnonymousDistinctId(anon_distinct_id): void

Parameters
Parameter Type
anon_distinct_id string | undefined
Returns

void

setGroupPropertiesForFlags()

setGroupPropertiesForFlags(properties, reloadFeatureFlags?): void

Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type. For example: setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })

Parameters
Parameter Type
properties {[type: string]: Properties; }
reloadFeatureFlags? boolean
Returns

void

setPersonPropertiesForFlags()

setPersonPropertiesForFlags(properties, reloadFeatureFlags?): void

Set override person properties for feature flags. This is used when dealing with new persons / where you don't want to wait for ingestion to update user properties.

Parameters
Parameter Type
properties Properties
reloadFeatureFlags? boolean
Returns

void

setReloadingPaused()

setReloadingPaused(isPaused): void

Parameters
Parameter Type
isPaused boolean
Returns

void

setup()

setup(client): void | Promise<void>

Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.

Parameters
Parameter Type
client Client
Returns

void | Promise<void>

unsetPersonPropertiesForFlags()

unsetPersonPropertiesForFlags(propertyNames, reloadFeatureFlags?): void

Remove override person properties used for feature flags. This is the counterpart to setPersonPropertiesForFlags, used when person properties are unset so flags re-evaluate without the removed values.

Parameters
Parameter Type
propertyNames string[]
reloadFeatureFlags? boolean
Returns

void

updateEarlyAccessFeatureEnrollment()

updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage?): void

Parameters
Parameter Type
key string
isEnrolled boolean
stage? string
Returns

void

updateFlags()

updateFlags(flags, payloads?, options?): void

Parameters
Parameter Type
flags Record<string, boolean | string>
payloads? Record<string, JsonType>
options? { merge?: boolean; }
options.merge? boolean
Returns

void

PostHogInterface

PostHogInterface = Omit<PostHog, "config" | "init" | "set_config"> & object

Type Declaration

Name Type
config PostHogConfig
set_config() (config) => void

ProductTour

Property Type
appearance? ProductTourAppearance
auto_launch? boolean
conditions? ProductTourConditions
current_iteration? number
description? string
disable_image_preload? boolean
display_frequency? ProductTourDisplayFrequency
end_date string | null
id string
internal_targeting_flag_key? string
linked_flag_key? string
name string
start_date string | null
steps ProductTourStep[]
tour_type ProductTourType

ProductTourAppearance

Property Type Description
backgroundColor? string -
borderColor? string -
borderRadius? number -
boxShadow? string -
buttonBorderRadius? number -
buttonColor? string -
dismissOnClickOutside? boolean defaults to true, auto-set to false for announcements/banners
fontFamily? string -
showOverlay? boolean -
textColor? string -
whiteLabel? boolean -
zIndex? number -

ProductTourBannerConfig

Property Type
action? object
action.link? string
action.tourId? string
action.type "none" | "link" | "trigger_tour"
animation? object
animation.duration? number
behavior "sticky" | "static" | "custom"
selector? string

ProductTourButtonAction

ProductTourButtonAction = "dismiss" | "link" | "next_step" | "previous_step" | "trigger_tour"

Button actions available on modal steps

ProductTourCallback

ProductTourCallback = (tours, context?) => void

Parameters

Parameter Type
tours ProductTour[]
context? { error?: string; isLoaded: boolean; }
context.error? string
context.isLoaded boolean

Returns

void

ProductTourConditions

Property Type
actions? { values: SurveyActionType[]; } | null
autoShowDelaySeconds? number
cancelEvents? { values: SurveyEventWithFilters[]; } | null
deviceTypes? string[]
events? { values: SurveyEventWithFilters[]; } | null
linkedFlagVariant? string
seenTourWaitPeriod? ProductTourWaitPeriod
selector? string
url? string
urlMatchType? SurveyMatchType

ProductTourDismissReason

ProductTourDismissReason = "user_clicked_skip" | "user_clicked_outside" | "escape_key" | "element_unavailable" | "container_unavailable"

ProductTourDisplayFrequency

ProductTourDisplayFrequency = "show_once" | "until_interacted" | "always"

ProductTourEventName

ProductTourEventName = typeof ProductTourEventName[keyof typeof ProductTourEventName]

ProductTourEventProperties

ProductTourEventProperties = typeof ProductTourEventProperties[keyof typeof ProductTourEventProperties]

ProductTourRenderReason

ProductTourRenderReason = "auto" | "api" | "trigger" | "event"

ProductTourSelectorError

ProductTourSelectorError = "not_found" | "multiple_matches" | "not_visible"

ProductTourStep

Property Type Description
bannerConfig? ProductTourBannerConfig Banner configuration (only for banner steps)
buttons? ProductTourStepButtons Button configuration for modal steps
content JSONContent | null -
contentHtml? string Pre-rendered HTML content from the editor. If present, SDK should use this instead of rendering from JSONContent.
id string -
inferenceData? InferredSelector Enhanced element data for more reliable lookup at runtime
linkedSurveyId? string ID of the auto-created survey for this step (set by backend)
linkedSurveyQuestionId? string ID of the survey question (set by backend, used for event tracking)
maxWidth? number Maximum tooltip width in pixels (defaults to 320px)
modalPosition? SurveyPosition Position for modal/survey steps (defaults to middle_center)
progressionTrigger "button" | "click" -
selector? string -
survey? ProductTourSurveyQuestion Inline survey question config - if present, this is a survey step
translations? Record<string, ProductTourStepTranslation> translation data for this tour step
type ProductTourStepType -
useManualSelector? boolean Use CSS selector instead of inference. Defaults to false (use inference).

ProductTourStepButton

Property Type Description
action ProductTourButtonAction -
link? string URL to open when action is 'link'
text string -
tourId? string Tour ID to trigger when action is 'trigger_tour'

ProductTourStepButtons

Property Type
primary? ProductTourStepButton
secondary? ProductTourStepButton

ProductTourStepTranslation

all translatable content for a given tour step

Properties

Property Type
buttons? object
buttons.primary? Pick<ProductTourStepButton, "text">
buttons.secondary? Pick<ProductTourStepButton, "text">
content? JSONContent | null
contentHtml? string
survey? Pick<ProductTourSurveyQuestion, "questionText" | "lowerBoundLabel" | "upperBoundLabel" | "submitButtonText" | "backButtonText">

ProductTourStepType

ProductTourStepType = "element" | "modal" | "survey" | "banner"

ProductTourSurveyQuestion

Property Type Description
backButtonText? string -
display? "number" | "emoji" Rating display type - emoji or number
lowerBoundLabel? string Label for low end of rating scale (e.g., "Not likely")
questionText string -
scale? 3 | 5 | 10 Rating scale - 3 or 5 for emoji, 5 or 10 for number
submitButtonText? string -
type ProductTourSurveyQuestionType -
upperBoundLabel? string Label for high end of rating scale (e.g., "Very likely")

ProductTourSurveyQuestionType

ProductTourSurveyQuestionType = "open" | "rating"

ProductTourType

ProductTourType = "tour" | "announcement" | "banner"

maps to main repo EffectiveProductTourType

ProductTourWaitPeriod

Property Type
days number
types ProductTourType[]

Properties

Properties = Record<string, Property>

Property

Property = any

Common types shared across PostHog SDKs

PropertyFilters

PropertyFilters = Record<string, { operator: PropertyOperator; values: string[]; }>

PropertyMatchType

PropertyMatchType = SurveyMatchType

PropertyOperator

PropertyOperator = PropertyMatchType | "gt" | "lt"

QueuedRequestWithOptions

  • RequestWithOptions

Extended by

  • RetriableRequestWithOptions

Properties

Property Type Description Inherited from
batchGroup? string requests sharing a batchKey are still sent separately when this differs -
batchKey? string key of queue, e.g. 'sessionRecording' vs 'event' -
callback? (response) => void - RequestWithOptions.callback
compression? Compression | "best-available" - RequestWithOptions.compression
compressionFallback? Compression Used when best-available compression negotiation does not select a format. RequestWithOptions.compressionFallback
data? Record<string, any> | Record<string, any>[] - RequestWithOptions.data
disableTransport? ("XHR" | "fetch" | "sendBeacon")[] - RequestWithOptions.disableTransport
fetchOptions? object - RequestWithOptions.fetchOptions
fetchOptions.cache? RequestCache - -
fetchOptions.next? NextOptions - -
fireCallbackOnDrop? boolean When set, _send_request invokes callback with a synthetic response on the paths that otherwise drop a request without notifying the caller (client not loaded, server rate limit). Opt-in so existing callers keep their current behavior; the logs pipeline uses it to keep records for a later retry instead of losing them silently. RequestWithOptions.fireCallbackOnDrop
headers? Record<string, any> - RequestWithOptions.headers
method? "POST" | "GET" - RequestWithOptions.method
noRetries? boolean - RequestWithOptions.noRetries
onDispatch? () => void Called each time _send_request hands the request to the transport. It is not called on the paths that drop the request before the network. RequestWithOptions.onDispatch
onSend? (url) => void Called by the fetch and XHR transports with the final request URL, just before they send it. Body encoding can run between onDispatch and this call. RequestWithOptions.onSend
preferSyncCompression? boolean Bypasses asynchronous CompressionStream gzip in favor of synchronous compression. Used for immediate requests so compression does not delay dispatch until after a navigation or page unload. RequestWithOptions.preferSyncCompression
timeout? number - RequestWithOptions.timeout
timestampMode? "body" | "capture-body" | "query" Controls where the request dispatch time is sent. - body adds ISO sent_at to the request object, or every object in an array (for example, flags and recordings). - capture-body wraps events in { api_key, batch, sent_at } with an ISO timestamp. - query adds numeric sent_at to POST requests or cache-busting _ to GET requests. RequestWithOptions.timestampMode
transport? "XHR" | "fetch" | "sendBeacon" - RequestWithOptions.transport
url string - RequestWithOptions.url
urlQueryArgs? object - RequestWithOptions.urlQueryArgs
urlQueryArgs.compression Compression - -

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

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

RemoteConfig

Remote configuration for a PostHog browser client.

These settings can be configured in PostHog. Configuration set directly on the client takes precedence over values from the server.

Extended by

  • FlagsResponse

Properties

Property Type Description
analytics? object Custom endpoint configuration for analytics events.
analytics.endpoint? string -
autocapture_opt_out? boolean If true, disables autocapture. When absent or not a boolean, the SDK keeps the last known server value; a visitor with no stored value keeps autocapture off until a response containing the field arrives.
autocaptureExceptions? boolean | { endpoint?: string; } Exception autocapture configuration.
captureDeadClicks? boolean Whether to capture dead clicks.
capturePerformance? boolean | PerformanceCaptureConfig Performance capture configuration shared by replay and web vitals.
conversations? boolean | ConversationsRemoteConfig Conversations widget configuration.
defaultIdentifiedOnly? boolean Whether to capture only identified users by default.
editorParams? ToolbarParams Deprecated Renamed to toolbarParams; still present on older API responses.
elementsChainAsString? boolean Whether $elements_chain is sent as a string rather than an array.
errorTracking? object Error tracking configuration.
errorTracking.autocaptureExceptions? boolean -
errorTracking.captureExtensionExceptions? boolean -
errorTracking.suppressionRules? ErrorTrackingSuppressionRule[] -
hasFeatureFlags? boolean Whether the team has any feature flags enabled.
heatmaps? boolean Whether heatmaps are enabled.
isAuthenticated boolean Whether the current user is authenticated.
logs? object Log capture configuration.
logs.captureConsoleLogs? boolean -
productTours? boolean Whether product tours are enabled.
sessionRecording? false | SessionRecordingRemoteConfig Session recording configuration.
siteApps object[] Site apps available to the client.
supportedCompression Compression[] Supported compression algorithms.
surveys? boolean | Survey[] Whether surveys are enabled, optionally including their definitions.
toolbarParams ToolbarParams Parameters for the toolbar.
toolbarVersion "toolbar" Deprecated Moved to toolbarParams.

RemoteConfigFeatureFlagCallback

RemoteConfigFeatureFlagCallback = (payload) => void

Parameters

Parameter Type
payload JsonType

Returns

void

RequestCallback

RequestCallback = (response) => void

Parameters

Parameter Type
response RequestResponse

Returns

void

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

RequestRestoreLinkPayload

Payload for requesting a self-service restore link email

Properties

Property Type
email string
request_url string

RequestRestoreLinkResponse

Response from self-service restore link request

Properties

Property Type
ok true

RequestTarget

RequestTarget = "api" | "flags" | "assets"

Configured host used to resolve a relative request path.

RequestTransport

RequestTransport = "XHR" | "fetch" | "sendBeacon"

Browser transport requested for a send.

RequestWithOptions

  • QueuedRequestWithOptions

Properties

Property Type Description
callback? (response) => void -
compression? Compression | "best-available" -
compressionFallback? Compression Used when best-available compression negotiation does not select a format.
data? Record<string, any> | Record<string, any>[] -
disableTransport? ("XHR" | "fetch" | "sendBeacon")[] -
fetchOptions? object -
fetchOptions.cache? RequestCache -
fetchOptions.next? NextOptions -
fireCallbackOnDrop? boolean When set, _send_request invokes callback with a synthetic response on the paths that otherwise drop a request without notifying the caller (client not loaded, server rate limit). Opt-in so existing callers keep their current behavior; the logs pipeline uses it to keep records for a later retry instead of losing them silently.
headers? Record<string, any> -
method? "POST" | "GET" -
noRetries? boolean -
onDispatch? () => void Called each time _send_request hands the request to the transport. It is not called on the paths that drop the request before the network.
onSend? (url) => void Called by the fetch and XHR transports with the final request URL, just before they send it. Body encoding can run between onDispatch and this call.
preferSyncCompression? boolean Bypasses asynchronous CompressionStream gzip in favor of synchronous compression. Used for immediate requests so compression does not delay dispatch until after a navigation or page unload.
timeout? number -
timestampMode? "body" | "capture-body" | "query" Controls where the request dispatch time is sent. - body adds ISO sent_at to the request object, or every object in an array (for example, flags and recordings). - capture-body wraps events in { api_key, batch, sent_at } with an ISO timestamp. - query adds numeric sent_at to POST requests or cache-busting _ to GET requests.
transport? "XHR" | "fetch" | "sendBeacon" -
url string -
urlQueryArgs? object -
urlQueryArgs.compression Compression -

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"

RestoreFromTokenPayload

Payload for restoring ticket access from a one-time token

Properties

Property Type Description
current_url? string Optional current URL for backend observability
distinct_id? string Optional distinct ID for debugging/observability
restore_token string Opaque one-time restore token from email link
widget_session_id string Current browser widget session ID requesting restore

RestoreFromTokenResponse

Response from restore token exchange endpoint

Properties

Property Type Description
code? string Optional machine-readable backend code
migrated_ticket_ids? string[] Migrated ticket IDs, if any
status RestoreFromTokenStatus Restore result
widget_session_id? string Canonical widget session ID to use after restore

RestoreFromTokenStatus

RestoreFromTokenStatus = "success" | "expired" | "invalid" | "used"

RetriableRequestWithOptions

  • QueuedRequestWithOptions

Properties

Property Type Description Inherited from
batchGroup? string requests sharing a batchKey are still sent separately when this differs QueuedRequestWithOptions.batchGroup
batchKey? string key of queue, e.g. 'sessionRecording' vs 'event' QueuedRequestWithOptions.batchKey
callback? (response) => void - QueuedRequestWithOptions.callback
compression? Compression | "best-available" - QueuedRequestWithOptions.compression
compressionFallback? Compression Used when best-available compression negotiation does not select a format. QueuedRequestWithOptions.compressionFallback
data? Record<string, any> | Record<string, any>[] - QueuedRequestWithOptions.data
disableTransport? ("XHR" | "fetch" | "sendBeacon")[] - QueuedRequestWithOptions.disableTransport
fetchOptions? object - QueuedRequestWithOptions.fetchOptions
fetchOptions.cache? RequestCache - -
fetchOptions.next? NextOptions - -
fireCallbackOnDrop? boolean When set, _send_request invokes callback with a synthetic response on the paths that otherwise drop a request without notifying the caller (client not loaded, server rate limit). Opt-in so existing callers keep their current behavior; the logs pipeline uses it to keep records for a later retry instead of losing them silently. QueuedRequestWithOptions.fireCallbackOnDrop
headers? Record<string, any> - QueuedRequestWithOptions.headers
method? "POST" | "GET" - QueuedRequestWithOptions.method
noRetries? boolean - QueuedRequestWithOptions.noRetries
onDispatch? () => void Called each time _send_request hands the request to the transport. It is not called on the paths that drop the request before the network. QueuedRequestWithOptions.onDispatch
onSend? (url) => void Called by the fetch and XHR transports with the final request URL, just before they send it. Body encoding can run between onDispatch and this call. QueuedRequestWithOptions.onSend
preferSyncCompression? boolean Bypasses asynchronous CompressionStream gzip in favor of synchronous compression. Used for immediate requests so compression does not delay dispatch until after a navigation or page unload. QueuedRequestWithOptions.preferSyncCompression
retriesPerformedSoFar? number - -
timeout? number - QueuedRequestWithOptions.timeout
timestampMode? "body" | "capture-body" | "query" Controls where the request dispatch time is sent. - body adds ISO sent_at to the request object, or every object in an array (for example, flags and recordings). - capture-body wraps events in { api_key, batch, sent_at } with an ISO timestamp. - query adds numeric sent_at to POST requests or cache-busting _ to GET requests. QueuedRequestWithOptions.timestampMode
transport? "XHR" | "fetch" | "sendBeacon" - QueuedRequestWithOptions.transport
url string - QueuedRequestWithOptions.url
urlQueryArgs? object - QueuedRequestWithOptions.urlQueryArgs
urlQueryArgs.compression Compression - -

SegmentAnalytics

SegmentAnalytics = object

Segment analytics object used for integration with PostHog

Properties

Property Type Description
register (integration) => Promise<any> Segment SDK versions use different plugin and resolved value types. any keeps current SDK types assignable without breaking legacy consumers that expect Promise<void>.
user () => SegmentAnalyticsUser | Promise<SegmentAnalyticsUser> -

SegmentAnalyticsUser

SegmentAnalyticsUser = object

Methods

anonymousId()

anonymousId(): string | null | undefined

Returns

string | null | undefined

id()

id(): string | null | undefined

Returns

string | null | undefined

SegmentEnrichmentFilterFn

SegmentEnrichmentFilterFn = (properties) => Properties | null

Filters non-colliding properties generated by PostHog before they are added to a Segment event. Original Segment properties are excluded. Returning null skips PostHog enrichment for that event.

Parameters

Parameter Type
properties Properties

Returns

Properties | null

SegmentIntegrationConfig

SegmentIntegrationConfig = object

Configuration for the PostHog Segment integration.

Properties

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.

SendMessagePayload

Payload for sending a message via the conversations API

Properties

Property Type Description
distinct_id string Distinct ID for linking to PostHog Person
identity_distinct_id? string Verified distinct_id for HMAC identity mode (requires identity_hash)
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.
message string The message content to send
session_context? SessionContext Session context captured when creating a new ticket Stored in a JSONField for flexibility
session_id? string Session ID captured when creating a new ticket Stored as a separate queryable DB field
ticket_id string | null Ticket ID to send the message to (null to create a new ticket)
traits object User identification traits
traits.email string | null -
traits.name string | null -
widget_session_id string Widget session ID for access control

SendMessageResponse

Response from sending a message

Properties

Property Type Description
created_at string ISO timestamp when the message was created
message_id string ID of the newly created message
ticket_id string ID of the ticket this message belongs to
ticket_status TicketStatus Current status of the ticket
unread_count number Number of unread messages from the team After customer sends a message, this is always 0

SendRequestInit

Options for sending a request through Client.sendRequest.

Properties

Property Type Description
body? unknown JSON-serialized by the client.
compression? Compression | "best-available" Compression used by the browser transport.
headers? Record<string, string> Additional headers merged with the host SDK's configured request headers.
method? "POST" | "GET" HTTP method to use; the host transport's default applies when omitted.
query? Record<string, string> Query string parameters appended to the request URL.
sentAt? "body" | "query" Where POST requests add sent_at. For GET, query adds the cache-busting _ parameter and body has no effect.
target? RequestTarget Configured host to send through; defaults to the regular API host.
timeoutMs? number Abort the request if it does not complete within this many milliseconds.
transport? RequestTransport Browser transport to prefer. Fetch is the normal runtime transport. Use sendBeacon only for an eligible best-effort teardown POST. Its response confirms browser handoff, not delivery.

SessionContext

Session context captured when creating a new ticket

Properties

Property Type Description
current_url? string Page URL where the ticket was created
session_replay_url? string URL to the session replay at the time the ticket was created Includes timestamp to jump to the exact moment

SessionContext

The current session, stamped on events to tie them to a session and a browser tab.

Properties

Property Modifier Type Description
lastActivityTimestamp readonly number Most recent session activity, as a Unix timestamp in milliseconds.
sessionId readonly string The stable session identifier attached to events captured during this session.
sessionStartTimestamp readonly number When the session started, as a Unix timestamp in milliseconds.
windowId readonly string The logical browser tab/window identifier attached alongside the session id.

SessionIdChangedCallback

SessionIdChangedCallback = (sessionId, windowId, changeReason?) => void

Parameters

Parameter Type Description
sessionId string -
windowId string | null | undefined -
changeReason? { activityTimeout: boolean; crossTabAdoption?: boolean; noSessionId: boolean; sessionPastMaximumLength: boolean; } -
changeReason.activityTimeout boolean -
changeReason.crossTabAdoption? boolean This tab picked up a session rotation another tab had already written to storage, instead of minting its own.
changeReason.noSessionId boolean -
changeReason.sessionPastMaximumLength boolean -

Returns

void

SessionRecordingCanvasOptions

SessionRecordingCanvasOptions = object

Properties

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

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[]

SessionRecordingOptions

Property Type Description
__mutationBytesBucketSize? number ADVANCED: enables the mutation byte budget by setting its burst allowance, in bytes. Also the largest single mutation event that will be recorded. Unset (the default), the byte budget is off. 1048576 (1MB) is a sensible starting point. Normally only altered alongside posthog support guidance. Default undefined
__mutationBytesRefillRate? number ADVANCED: the sustained mutation byte budget, in bytes per second. Mutation events beyond the budget are dropped and the recording resyncs with a full snapshot. Only takes effect when __mutationBytesBucketSize is set. Normally only altered alongside posthog support guidance. Default 25600
__mutationThrottlerBucketSize? number ADVANCED: alters the bucket size for the token bucket mutation throttling Normally only altered alongside posthog support guidance. Accepts values between 0 and 100 Default 100
__mutationThrottlerRefillRate? number ADVANCED: alters the refill rate for the token bucket mutation throttling Normally only altered alongside posthog support guidance. Accepts values between 0 and 100 Default 10
attributeFilter? string[] ADVANCED: limit which DOM attributes are observed for mutations, by passing the list to the native MutationObserver attributeFilter. Mutations to unlisted attributes never reach the recorder at all, so they cost no recording CPU - useful to exclude high-frequency inline style mutations from JS-driven animations on animation-heavy pages. Attributes left off the list are invisible to replay, so only set this when that loss of fidelity is acceptable. When unset (the default) or set to an empty array, all attributes are observed. A list without id also stops captureJsonLd from keeping @id fragments. Normally only altered alongside posthog support guidance.
blockClass? string | RegExp Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-no-capture'
blockSelector? string | null Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default null
canvasCapture? object Tune how canvas frames are captured for replay. Only has any effect when canvas recording is enabled. - resolutionScale: capture canvas frames at a fraction of their display resolution. A number in (0, 1]; 1 is full-resolution capture (the default) and, e.g., 0.6 captures at 60%. Out-of-range or non-finite values are clamped into (0, 1]. Aspect ratio is preserved and replay upscales the frame back to the original display size, so playback dimensions are unchanged, just softer. Resolution is the highest-leverage lever for canvas byte size, since bytes scale with pixel area. - maskRegionsFn: mask regions of a recorded canvas — see its doc comment.
canvasCapture.maskRegionsFn? ((canvas) => CanvasMaskRegion[] | null | undefined) | null If set, called once per canvas per captured frame; the returned regions (CSS pixels, relative to the canvas element) are painted black before the frame is encoded. Lets apps that render into canvas (e.g. Flutter web) mask content that DOM-based masking cannot see. Re-read from config on every frame, so the real provider can be swapped in after recording has started. Return [] for a frame with nothing to mask (recorded as is), or null if regions could not be computed — that frame is skipped rather than recorded unmasked. Anything other than an array — null, a thrown error, or an implicit undefined from an untyped caller — skips that frame. Not setting this at all records the canvas unmasked. The provider is called for every canvas on the page, including canvases inside shadow DOM. For a canvas it does not manage, return [] ("nothing to mask") — returning null skips that canvas's frames entirely. Called synchronously on the main thread for every captured frame (canvas FPS is 4 by default, 12 max), so keep it cheap — avoid forcing layout, and return few regions. Setting this also changes DOM full snapshots (taken at recording start and at each full_snapshot_interval_millis): they normally serialize canvas pixels on a separate path (rr_dataURL) that never sees these regions, so when this option is set that serialization is skipped entirely. Whether to skip is re-evaluated at each snapshot, so a provider installed via set_config after recording started is honored at the next snapshot without a recorder restart. A canvas appears blank in a snapshot until the next canvas frame paints it — ~250ms at the default 4 fps while its pixels are changing, and at most 30s otherwise, because every canvas the provider answers (with regions or []) re-sends an unchanged frame as a keyframe every 30s; a canvas whose frames are skipped (null) stays blank. Without this option, snapshot behavior is unchanged. An app whose real provider only exists once its runtime has booted picks what happens in between by what it declares in posthog.init: a function covering the whole canvas blacks those frames out, () => null skips them, and declaring nothing records them. Client-side only, cannot be set via remote configuration. Default undefined
canvasCapture.resolutionScale? number -
captureCanvas? SessionRecordingCanvasOptions Allows local config to override remote canvas recording settings from the flags response. To mask content inside a recorded canvas, see canvasCapture.maskRegionsFn.
captureJsonLd? boolean Captures sanitized Schema.org JSON-LD as session replay custom events. JSON-LD inside a text mask or blocked element is never captured. The recorder keeps properties on its universal safe list at every depth. This list includes @type values shaped like a Schema.org term, which means letters and digits only. It drops property branches that are not on the allowlist. Retained strings starting with http://, https://, //, /, ./, or ../ use replay URL masking, including query parameter and hash settings. This applies to nested entities and scalar arrays, but not to the fixed @context, normalized @type, or captured DOM IDs. Other strings, including bare relative paths and URLs embedded in text, are unchanged. A URL rejected by the masking callback is omitted. If the callback throws, the script is not captured. It keeps an @id as a fragment only when replay also captures a DOM element with the same id value. It drops every @id when maskAllElementAttributes, maskAttributeFn, or an attributeFilter without id can hide id attributes from replay. It also keeps the containing entity tree, even when it redacts all other fields. The event tag is $json_ld. The payload is a JSON-LD object or array. The event includes the current page URL in data.href, subject to replay URL masking and hash capture settings. The URL is omitted when the masking callback rejects it or throws. The recorder removes all script nodes from snapshots when this option is enabled. The JSON-LD observer starts only when this option is true at recording start. See https://github.com/PostHog/posthog-js/blob/main/packages/browser/src/extensions/replay/external/json-ld.ts Default false before the 2026-08-30 defaults, otherwise true
collectFonts? boolean Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
compress_events? boolean ADVANCED: whether to partially compress rrweb events before sending them to the server, defaults to true, can be set to false to disable partial compression NB requests are still compressed when sent to the server regardless of this setting Default true
full_snapshot_interval_millis? number ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable Default 1000 * 60 * 5 (5 minutes)
ignoreClass? string | RegExp Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-ignore-input'
inlineStylesheet? boolean Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default true
inlineStylesheetBudgetRules? number Max CSSRules inlined synchronously per full snapshot. Sheets past the budget keep their rel/href and are inlined across idle callbacks instead of blocking the snapshot; the queue is flushed synchronously (bounded) when recording stops and on pagehide. The residual risk: replay falls back to loading a sheet from its original href (which may be purged, auth-gated, or renamed by replay time) only if the tab dies without pagehide firing, the teardown flush hits its safety cap, or stringifying the sheet fails. The default is applied by posthog-js when it starts the recorder; the recorder itself is unbounded without it. Set 0 to inline everything up front (the pre-budget behaviour). Default 10000
maskAllElementAttributes? boolean Derived from rrweb.record options. Masks every string-valued source DOM attribute, including rendering attributes such as class, id, style, src, href, and synthesized form values. Only rrweb-generated layout metadata is retained, so this option intentionally reduces replay fidelity. Mutually exclusive with maskAttributeFn: when both are set this option wins and the callback is ignored. See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
maskAllInputs? boolean Derived from rrweb.record options. When true (the default) session replay masks the value of every input, except file inputs, whose values are recorded unmasked — block those with ph-no-capture or blockSelector if they hold sensitive data. Set it to false to record input values, which is not recommended for apps that handle sensitive data. A session_recording masking option set in posthog.init takes precedence over the project "Privacy and masking" setting; the SDK warns once when the two differ. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy Default true
maskAttributeFn? ((name, value, element?) => string) | null Derived from rrweb.record options. Called with (name, value, element) for every non-empty string-valued attribute in the final serialized representation so you can mask specific attributes. Returning the original value leaves it visible. Mutually exclusive with maskAllElementAttributes: when both are set that option wins and this callback is ignored, so a callback cannot accidentally unmask what the coarse option hides. See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskCapturedNetworkRequestFn? ((data) => CapturedNetworkRequest | null | undefined) | null Modify the network request before it is captured. Returning null or undefined stops it being captured. Initial navigation and performance-timing entries are also passed to this function. They have isInitial === true, can have method === undefined, and contain the page URL in name. If the function returns null or undefined for an initial entry, PostHog retains the replay-required timing metadata but omits its URL, headers, and body. Return a modified entry to retain a redacted URL.
maskInputFn? ((text, element?) => string) | null Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskInputOptions? Partial<MaskInputOptions> Derived from rrweb.record options. Selects which input types to mask by input attribute, for use when maskAllInputs is false. Password inputs are always masked by default: the SDK adds password: true to a partial override, so set password: false explicitly if you must record password fields. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy
maskNetworkRequestFn? ((data) => NetworkRequest | null | undefined) | null Deprecated - use maskCapturedNetworkRequestFn instead
maskTextClass? string | RegExp Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-mask'
maskTextFn? ((text, element?) => string) | null Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskTextSelector? string | null Derived from rrweb.record options. A CSS selector for non-input text to mask in session replay. Session replay masks input values by default (see maskAllInputs), but it does not mask other DOM text or images. This selector and the ph-mask class mask text content only — for example a rendered card number — and do not hide an image, whose src is still recorded. To redact a rendered image such as a scanned document, block the image or a container element with ph-no-capture (see blockClass/blockSelector), which replaces it with a placeholder and stops recording its subtree. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy
recordBody? boolean Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
recordCrossOriginIframes? boolean Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
recordHeaders? boolean Derived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
sampleRate? number The sample rate for session recordings, a number between 0 and 1. For example, 0.5 means roughly 50% of sessions will be recorded. When undefined, falls back to the remote config setting. When set, takes precedence over the remote config. Default undefined
sampling? SessionRecordingSamplingConfig Derived from rrweb.record options. Controls how often certain event types are captured within an already-recorded session, e.g. { mousemove: false } stops recording mouse movement. Not to be confused with sampleRate below, which controls whether a session is recorded at all, or with posthog.startSessionRecording({ sampling: true }), which overrides that session-level sample rate. NB disabled event types no longer count as user activity for replay idle detection (session_idle_threshold_ms). For example, with mousemove: false pure mouse movement no longer keeps a session active, while clicks, scrolls, and inputs still do. See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default undefined
selectMaskingFn? (element) => "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)

SessionRecordingPersistedConfig

SessionRecordingPersistedConfig = Omit<SessionRecordingRemoteConfig, "recordCanvas" | "canvasFps" | "canvasQuality" | "networkPayloadCapture" | "sampleRate" | "minimumDurationMilliseconds"> & object

the config stored in persistence when session recording remote config is received

Type Declaration

Name Type Description
cache_timestamp? number Used to determine if the persisted config is still valid or we need to wait for a new one only accepts undefined since older versions of the library didn't set this.
canvasRecording object -
canvasRecording.enabled SessionRecordingRemoteConfig["recordCanvas"] -
canvasRecording.fps SessionRecordingRemoteConfig["canvasFps"] -
canvasRecording.quality SessionRecordingRemoteConfig["canvasQuality"] -
enabled boolean -
minimumDurationMilliseconds number | null | undefined -
networkPayloadCapture SessionRecordingRemoteConfig["networkPayloadCapture"] & object -
sampleRate number | null -

SessionRecordingRemoteConfig

SessionRecordingRemoteConfig = SessionRecordingCanvasOptions & object

Type Declaration

Name Type Description
consoleLogRecordingEnabled? boolean -
endpoint? string -
eventTriggers? string[] -
linkedFlag? string | FlagVariant | null -
masking? Pick<SessionRecordingOptions, "maskAllInputs" | "maskTextSelector" | "blockSelector" | "maskAllElementAttributes"> -
minimumDurationMilliseconds? number -
networkPayloadCapture? Pick<NetworkRecordOptions, "recordBody" | "recordHeaders"> -
sampleRate? string | null -
scriptConfig? object -
scriptConfig.script? string -
triggerGroups? SessionRecordingTriggerGroup[] V2 Trigger Groups - multiple named trigger groups with their own conditions and sample rates. Only used when version === 2.
triggerMatchType? "any" | "all" Controls how event, URL, sampling, and linked flag triggers are combined. any means that if any of the triggers match, the session will be recorded. all means that all the triggers must match for the session to be recorded.
urlBlocklist? SessionRecordingUrlTrigger[] -
urlTriggers? SessionRecordingUrlTrigger[] -
version? 1 | 2 Config version - defaults to 1 (legacy). When version is 2, triggerGroups is used instead of individual trigger fields.

SessionRecordingSamplingConfig

Sampling options for session recording, a subset of rrweb's sampling strategy

Properties

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

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

SessionStartReason = "sampling_overridden" | "recording_initialized" | "linked_flag_matched" | "linked_flag_overridden" | typeof SAMPLED | "session_id_changed" | "url_trigger_matched" | "event_trigger_matched"

SeverityLevel

SeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug"

ShowTourOptions

Property Type
enableStrictValidation? boolean
reason? ProductTourRenderReason

SiteApp

SiteApp = object

Properties

Property Type
errored boolean
id string
loaded boolean
processedBuffer boolean
processEvent? (globals) => void

SiteAppGlobals

SiteAppGlobals = object

Properties

Property Type
event object
event.distinct_id? string
event.elements_chain? string
event.event EventName
event.properties Properties
event.timestamp? Date
event.uuid string
groups Record<string, { id: string; properties: Properties; type: string; }>
person object
person.properties Properties

SiteAppLoader

SiteAppLoader = object

Properties

Property Type
id string
init (config) => object

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

SnippetArrayItem

SnippetArrayItem = [method: string, args: any[]]

SpecificQuestionBranching

Property Type
index number
type "specific_question"

SupportedWebVitalsMetrics

SupportedWebVitalsMetrics = "LCP" | "CLS" | "FCP" | "INP"

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 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 - -
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 - -

SurveyAppearance

SurveyAppearance = object

Properties

Property Type
allowGoBack? boolean
autoDisappear? boolean
backButtonText? string
backgroundColor? string
borderColor? string
displayIntroScreen? boolean
displayThankYouMessage? boolean
inputBackground? string
inputTextColor? string
introScreenButtonText? string
introScreenDescription? string
introScreenDescriptionContentType? SurveyQuestionDescriptionContentType
introScreenHeader? string
placeholder? string
position? SurveyPosition
ratingButtonActiveColor? string
ratingButtonColor? string
shuffleQuestions? boolean
submitButtonColor? string
submitButtonText? string
submitButtonTextColor? string
surveyPopupDelaySeconds? number
textColor? string
thankYouMessageCloseButtonText? string
thankYouMessageDescription? string
thankYouMessageDescriptionContentType? SurveyQuestionDescriptionContentType
thankYouMessageHeader? string
widgetColor? string
widgetLabel? string
widgetSelector? string
widgetType? SurveyWidgetType

SurveyCallback

SurveyCallback = (surveys, context?) => void

Parameters

Parameter Type
surveys Survey[]
context? { error?: string; isLoaded: boolean; }
context.error? string
context.isLoaded boolean

Returns

void

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

SurveyConfig

Survey configuration options

Properties

Property Type
autoSubmitDelay? number
autoSubmitIfComplete? boolean
prefillFromUrl? 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

SurveyEventName = typeof SurveyEventName[keyof typeof SurveyEventName]

SurveyEventProperties

SurveyEventProperties = typeof SurveyEventProperties[keyof typeof SurveyEventProperties]

SurveyEventType

SurveyEventType = typeof SurveyEventType[keyof typeof SurveyEventType]

SurveyEventWithFilters

Property Type
name string
propertyFilters? PropertyFilters

SurveyMatchType

SurveyMatchType = typeof SurveyMatchType[keyof typeof SurveyMatchType]

SurveyPosition

SurveyPosition = typeof SurveyPosition[keyof typeof SurveyPosition]

SurveyPosition

SurveyPosition = typeof SurveyPosition[keyof typeof SurveyPosition]

SurveyQuestion

SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion

SurveyQuestionBase

  • BasicSurveyQuestion
  • LinkSurveyQuestion
  • RatingSurveyQuestion
  • MultipleSurveyQuestion

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

SurveyQuestionBranchingType = typeof SurveyQuestionBranchingType[keyof typeof SurveyQuestionBranchingType]

SurveyQuestionDescriptionContentType

SurveyQuestionDescriptionContentType = "html" | "text"

SurveyQuestionDescriptionContentType

SurveyQuestionDescriptionContentType = typeof SurveyQuestionDescriptionContentType[keyof typeof SurveyQuestionDescriptionContentType]

SurveyQuestionTranslation

Property Type
buttonText? string
choices? string[]
description? string | null
link? string | null
lowerBoundLabel? string
question? string
upperBoundLabel? string

SurveyQuestionType

SurveyQuestionType = typeof SurveyQuestionType[keyof typeof 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

SurveyResponseValue = SurveyResponseValue

SurveyResponseValue

SurveyResponseValue = string | number | string[] | null

SurveySchedule

SurveySchedule = typeof SurveySchedule[keyof typeof SurveySchedule]

SurveyTabPosition

SurveyTabPosition = typeof SurveyTabPosition[keyof typeof SurveyTabPosition]

SurveyTranslation

Property Type
backButtonText? string
introScreenButtonText? string
introScreenDescription? string
introScreenHeader? string
name? string
submitButtonText? string
thankYouMessageCloseButtonText? string
thankYouMessageDescription? string
thankYouMessageHeader? string

SurveyType

SurveyType = typeof SurveyType[keyof typeof SurveyType]

SurveyValidationRule

Property Type
errorMessage? string
type SurveyValidationType
value? number

SurveyValidationType

SurveyValidationType = typeof SurveyValidationType[keyof typeof SurveyValidationType]

SurveyWidgetType

SurveyWidgetType = typeof SurveyWidgetType[keyof typeof SurveyWidgetType]

SurveyWidgetType

SurveyWidgetType = typeof SurveyWidgetType[keyof typeof SurveyWidgetType]

SurveyWithTypeAndAppearance

SurveyWithTypeAndAppearance = Pick<Survey, "id" | "type" | "appearance">

Ticket

A support ticket in the conversations system

Properties

Property Type Description
created_at string ISO timestamp when the ticket was created
id string Unique identifier for the ticket
last_message? string Preview of the last message
last_message_at? string ISO timestamp of the last message
message_count number Total number of messages in this ticket
messages? Message[] Array of messages (only present in detailed ticket view)
status TicketStatus Current status of the ticket
unread_count? number Number of unread messages from the team

TicketStatus

TicketStatus = "new" | "open" | "pending" | "on_hold" | "resolved"

Status of a support ticket

TipTapDoc

TipTap document - the root node of rich content

Properties

Property Type
content? TipTapNode[]
type "doc"

TipTapMark

TipTap mark types for inline formatting

Properties

Property Type
attrs? object
attrs.href? string
attrs.target? string
type "link" | "bold" | "italic" | "underline" | "strike" | "code"

TipTapNode

TipTap node representing content in the document tree

Properties

Property Type
attrs? Record<string, unknown>
content? TipTapNode[]
marks? TipTapMark[]
text? string
type string

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

ToolbarSource = "url" | "localstorage"

ToolbarUserIntent

ToolbarUserIntent = "add-action" | "edit-action"

Toolbar types

ToolbarVersion

ToolbarVersion = "toolbar"

TreeShakeable

TreeShakeable<T> = "optional" extends keyof TreeShakeableConfig ? T | undefined : T

For the full bundle (default), resolves to T (extensions guaranteed present). For the slim bundle (augmented with { optional: true }), resolves to T | undefined.

Type Parameters

Type Parameter
T

UserProvidedTraits

User-provided identification data (collected via the widget form)

Properties

Property Type
email? string
name? string

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.

WidgetPosition

WidgetPosition = "bottom_left" | "bottom_right" | "top_left" | "top_right"

Position of the conversations widget on the screen.

Writable

Writable<T> = { -readonly [P in keyof T]: T[P] }

Type Parameters

Type Parameter
T