PostHog JavaScript Web SDK 1.x

Getting started

The JavaScript Web SDK runs in the browser.

To send your first event, run the AI wizard, add the HTML snippet, or install posthog-js and call posthog.init once. The snippet and npm install need your project token and host from your project settings.

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

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

Install with the AI wizard

Run the AI wizard in your project directory to detect your framework, install PostHog, and configure your project:

Terminal
npx -y @posthog/wizard@latest

Install with the HTML snippet

Paste the snippet inside your site's <head> tags so PostHog loads on every page. Replace the project token and host with your own.

The snippet loads the latest SDK and calls init, so you can skip the package install and initialize steps below.

HTML
<script>
!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||[]);
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})
</script>

Install with a package manager

Terminal
npm install posthog-js

Initialize

TypeScript
import posthog from 'posthog-js'
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})

See Configuration, Security, and Persistence for setup guides.

Capture an event

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

Identify a user

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

Pass this to your agent

Pass the link to the markdown version of this page to your agent as additional reference when you work.

Setup

posthog.init

TypeScript
init(
token: string,
config?: Partial<PostHogConfig>,
name?: string
): PostHog;

Initialize a PostHog SDK instance with your project token and configuration options.

Parameters

ParameterTypeDescription
tokenstringYour PostHog project token
config?Partial<PostHogConfig>Configuration options overriding defaults
name?stringOptional name when running multiple PostHog instances

Returns

PostHog

The initialized PostHog instance

Remarks

Call posthog.init() once on page load. If your app already knows the signed-in user at startup, call posthog.identify() inside the loaded callback.

When you initialize extra named instances via the third name parameter, each instance is attached to posthog[name] and returned directly. Disable autocapture: false on secondary instances so clicks and pageviews aren't captured twice. See configuration options.

Examples

JavaScript
// Basic initialization
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})
JavaScript
// Identify inside the loaded callback
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
loaded: (ph) => {
ph.identify('user_123', { email: 'user@example.com' })
},
})
JavaScript
// Secondary named instance without duplicate autocapture
const secondary = posthog.init('<other_project_token>', {
api_host: 'https://us.i.posthog.com',
autocapture: false,
}, 'secondary')
secondary.capture('secondary_event')

posthog.set_config

TypeScript
set_config(config: Partial<PostHogConfig>): void;

Updates the configuration of the PostHog instance.

Parameters

ParameterTypeDescription
configPartial<PostHogConfig>A dictionary of new configuration values to update

posthog.debug

TypeScript
debug(debug?: boolean): void;

Enables or disables debug mode for detailed logging.

Parameters

ParameterTypeDescription
debug?booleanIf true, will enable debug mode.

Remarks

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

Examples

JavaScript
// enable debug mode
posthog.debug(true)
JavaScript
// disable debug mode
posthog.debug(false)

posthog.shutdown

TypeScript
shutdown(): Promise<void>;

Flushes any queued events and resolves once teardown is complete.

Returns

Promise<void>

Resolves once best-effort cleanup and queue flushing complete.

Remarks

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

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

Example

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

posthog

TypeScript
const posthog: PostHog;

The default PostHog JavaScript Web SDK singleton instance.

new PostHog(...)

TypeScript
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

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

Events and properties

posthog.capture

TypeScript
capture(
event_name: EventName,
properties?: Properties | null,
options?: CaptureOptions
): CaptureResult | undefined;

Captures an event with optional properties and configuration.

Parameters

ParameterTypeDescription
event_nameEventNameThe name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase')
properties?Properties | nullProperties to include with the event describing the user or event details
options?CaptureOptionsOptional configuration for the capture request

Returns

CaptureResult | undefined

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

Remarks

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

To send a critical event right before page navigation or reload, pass { transport: 'sendBeacon', send_instantly: true }. Passing transport: 'sendBeacon' alone chooses the transport without bypassing the batch queue, so add send_instantly: true when you cannot wait for the flush interval.

Examples

JavaScript
// basic event capture
posthog.capture('cta-button-clicked', {
button_name: 'Get Started',
page: 'homepage'
})
JavaScript
// send immediately before page unload
posthog.capture(
'user_clicked_reload',
{ button: 'reload' },
{ transport: 'sendBeacon', send_instantly: true }
)

posthog.register

TypeScript
register(properties: Properties, days?: number): void;

Registers super properties that are included with all events.

Parameters

ParameterTypeDescription
propertiesPropertiesproperties to store about the user
days?numberHow many days since the user's last visit to store the super properties

Remarks

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

Examples

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

posthog.register_once

TypeScript
register_once(
properties: Properties,
default_value?: any,
days?: number
): void;

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

Parameters

ParameterTypeDescription
propertiesPropertiesAn associative array of properties to store about the user
default_value?anyValue to override if already set in super properties (ex: 'False') Default: 'None'
days?numberHow many days since the users last visit to store the super properties

Remarks

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

Examples

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

posthog.register_for_session

TypeScript
register_for_session(properties: Properties): void;

Registers super properties for the current session only.

Parameters

ParameterTypeDescription
propertiesPropertiesAn associative array of properties to store about the user

Remarks

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

Examples

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

posthog.unregister

TypeScript
unregister(property: string): void;

Removes a super property from persistent storage.

Parameters

ParameterTypeDescription
propertystringThe name of the super property to remove

Remarks

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

Example

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

posthog.unregister_for_session

TypeScript
unregister_for_session(property: string): void;

Removes a session super property from the current session.

Parameters

ParameterTypeDescription
propertystringThe name of the session super property to remove

Remarks

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

Example

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

posthog.get_property

TypeScript
get_property(property_name: string): any;

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

Parameters

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

JavaScript
// grab value for '$user_id' after the posthog library has loaded
posthog.init('<ph_project_token>', {
loaded: function(posthog) {
user_id = posthog.get_property('$user_id');
}
});

posthog.getSessionProperty

TypeScript
getSessionProperty(property_name: string): 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

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

JavaScript
// grab value for 'user_id' after the posthog library has loaded
posthog.init('<ph_project_token>', {
loaded: function(posthog) {
user_id = posthog.getSessionProperty('user_id');
}
});

posthog.logger

TypeScript
get logger(): Logger;

Logger with convenience methods for each severity level.

Example

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

Returns

Logger

posthog.captureLog

TypeScript
captureLog(options: CaptureLogOptions): 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

ParameterTypeDescription
optionsCaptureLogOptionsThe log entry options

Example

JavaScript
posthog.captureLog({
body: 'checkout completed',
level: 'info',
attributes: { order_id: 'ord_789', amount_cents: 4999 },
})

posthog.captureTraceFeedback

TypeScript
captureTraceFeedback(traceId: string | number, userFeedback: string): void;

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

Parameters

ParameterTypeDescription
traceIdstring | numberThe trace ID to capture feedback for.
userFeedbackstringThe feedback to capture.

posthog.captureTraceMetric

TypeScript
captureTraceMetric(
traceId: string | number,
metricName: string,
metricValue: string | number | boolean
): void;

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

Parameters

ParameterTypeDescription
traceIdstring | numberThe trace ID to capture the metric for.
metricNamestringThe name of the metric to capture.
metricValuestring | number | booleanThe value of the metric to capture.

Identity and groups

posthog.identify

TypeScript
identify(
new_distinct_id?: string,
userPropertiesToSet?: Properties,
userPropertiesToSetOnce?: Properties
): void;

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

Parameters

ParameterTypeDescription
new_distinct_id?stringA non-empty string that uniquely identifies a user.
userPropertiesToSet?PropertiesOptional: 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?PropertiesOptional: An associative array of properties to store about the user. If property is previously set, this does not override that value.

Remarks

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

Under person_profiles: 'identified_only' (the default), calling identify, alias, group, setPersonProperties, or createPersonProfile creates a person profile for the user. Calling setPersonPropertiesForFlags or setGroupPropertiesForFlags does not create a person profile.

Examples

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

posthog.reset

TypeScript
reset(options?: boolean | ResetOptions): 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

ParameterTypeDescription
options?boolean | ResetOptionsBoolean to reset the device ID (legacy), or reset options including bootstrap values.

Examples

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

posthog.setPersonProperties

TypeScript
setPersonProperties(userPropertiesToSet?: Properties, userPropertiesToSetOnce?: Properties): void;

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

Parameters

ParameterTypeDescription
userPropertiesToSet?PropertiesOptional: 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?PropertiesOptional: An associative array of properties to store about the user. If property is previously set, this does not override that value.

Remarks

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

Examples

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

posthog.unsetPersonProperties

TypeScript
unsetPersonProperties(propertyNames: string | string[]): void;

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

Parameters

ParameterTypeDescription
propertyNamesstring | string[]The name (or names) of the person properties to remove.

Remarks

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

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

Examples

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

posthog.createPersonProfile

TypeScript
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

Example

JavaScript
posthog.createPersonProfile()

posthog.get_distinct_id

TypeScript
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

JavaScript
// get the current user ID
const userId = posthog.get_distinct_id()
console.log('Current user:', userId)
JavaScript
// use in loaded callback
posthog.init('<ph_project_token>', {
loaded: (posthog) => {
const id = posthog.get_distinct_id()
// use the ID
}
})

posthog.alias

TypeScript
alias(alias: string, original?: string): number | void | CaptureResult;

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

Parameters

ParameterTypeDescription
aliasstringA unique identifier that you want to use for this user in the future.
original?stringThe 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

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

posthog.group

TypeScript
group(
groupType: string,
groupKey: string,
groupPropertiesToSet?: Properties
): void;

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

Parameters

ParameterTypeDescription
groupTypestringGroup type (example: 'organization')
groupKeystringGroup key (example: 'org::5')
groupPropertiesToSet?PropertiesOptional properties to set for group

Remarks

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

Examples

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

posthog.getGroups

TypeScript
getGroups(): Record<string, any>;

Returns the current groups.

Returns

Record<string, any>

The current groups

posthog.resetGroups

TypeScript
resetGroups(): void;

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

Example

JavaScript
posthog.resetGroups()

posthog.setInternalOrTestUser

TypeScript
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 excluding internal or test users from analytics. See how to filter internal users and create a cohort with $internal_or_test_user set.

Example

JavaScript
// Manually mark as test user
posthog.setInternalOrTestUser()
// Or use internal_or_test_user_hostname config for automatic detection
posthog.init('<ph_project_token>', { internal_or_test_user_hostname: 'localhost' })

posthog.setIdentity

TypeScript
setIdentity(distinctId: string, hash: string): void;

Set HMAC-based identity verification.

Parameters

ParameterTypeDescription
distinctIdstringThe verified user distinct_id
hashstringHMAC-SHA256 of distinctId, signed with the Secret API key from Support settings

Remarks

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

Example

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

posthog.clearIdentity

TypeScript
clearIdentity(): void;

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

Example

JavaScript
posthog.clearIdentity()

Feature flags

posthog.isFeatureEnabled

TypeScript
isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined;

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

Parameters

ParameterTypeDescription
keystringKey of the feature flag.
options?IsFeatureEnabledOptionsOptional lookup settings. If { send_event: false }, we won't send a $feature_flag_called event to PostHog, or the $experiment_exposure event of a config version 2 experiment split. If { fresh: true }, we won't return cached values from localStorage - only values loaded from the server. If { defaultValue: false }, we return that value instead of undefined when the flag has no value.

Returns

boolean | undefined

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

Remarks

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

Examples

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

posthog.getFeatureFlag

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

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

Parameters

ParameterTypeDescription
keystringKey of the feature flag.
options?FeatureFlagOptionsOptional lookup settings. If { send_event: false }, we won't send a $feature_flag_called event to PostHog, or the $experiment_exposure event of a config version 2 experiment split. If { fresh: true }, we won't return cached values from localStorage - only values loaded from the server.

Returns

string | boolean | undefined

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

Remarks

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

Examples

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

posthog.getFeatureFlagResult

TypeScript
getFeatureFlagResult(key: string, options?: FeatureFlagOptions): 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, and also $experiment_exposure when a config version 2 experiment split supplies the value.

Parameters

ParameterTypeDescription
keystringKey of the feature flag.
options?FeatureFlagOptionsOptions for the feature flag lookup.

Returns

FeatureFlagResult | undefined

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

Examples

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

posthog.getAllFeatureFlags

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

posthog.onFeatureFlags

TypeScript
onFeatureFlags(callback: FeatureFlagsCallback): () => 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

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

JavaScript
posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
// do something
})

posthog.reloadFeatureFlags

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

Example

JavaScript
posthog.reloadFeatureFlags()

posthog.setPersonPropertiesForFlags

TypeScript
setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags?: boolean): 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

ParameterTypeDefault valueDescription
propertiesPropertiesundefinedThe properties to override.
reloadFeatureFlags?booleantrueWhether to reload feature flags.

Examples

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

posthog.resetPersonPropertiesForFlags

TypeScript
resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): void;

Resets the person properties for feature flags.

Parameters

ParameterTypeDefault valueDescription
reloadFeatureFlags?booleantrueWhether to reload feature flags.

Examples

JavaScript
posthog.resetPersonPropertiesForFlags()
JavaScript
// Reset properties without reloading
posthog.resetPersonPropertiesForFlags(false)

posthog.setGroupPropertiesForFlags

TypeScript
setGroupPropertiesForFlags(properties: object, reloadFeatureFlags?: boolean): void;

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

Parameters

ParameterTypeDefault valueDescription
properties{ [type: string]: Properties; }undefinedThe properties to override, the key of which is the group type.
reloadFeatureFlags?booleantrueWhether to reload feature flags.

Examples

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

posthog.resetGroupPropertiesForFlags

TypeScript
resetGroupPropertiesForFlags(group_type?: string): void;

Resets the group properties for feature flags.

Parameters

ParameterTypeDescription
group_type?stringOptional group type to reset. If omitted, all group properties are reset.

Example

JavaScript
posthog.resetGroupPropertiesForFlags()

posthog.updateFlags

TypeScript
updateFlags(
flags: Record<string, boolean | string>,
payloads?: Record<string, JsonType>,
options?: object
): 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

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

Example

JavaScript
// Replace all flags with server-evaluated values
posthog.updateFlags({
'my-flag': true,
'my-experiment': 'variant-a'
})
// Merge with existing flags (update only specified flags)
posthog.updateFlags(
{ 'my-flag': true },
undefined,
{ merge: true }
)
// With payloads
posthog.updateFlags(
{ 'my-flag': true },
{ 'my-flag': { some: 'data' } }
)

Session replay

posthog.startSessionRecording

TypeScript
startSessionRecording(override?:
| true
| {
event_trigger?: true;
linked_flag?: boolean;
sampling?: boolean;
url_trigger?: true;
}): void;

Turns session recording on and sets disable_session_recording to false.

Parameters

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

Examples

JavaScript
// Start and ignore controls
posthog.startSessionRecording(true)
JavaScript
// Start and override specific controls
posthog.startSessionRecording({
sampling: true,
linked_flag: false,
url_trigger: true,
})

posthog.stopSessionRecording

TypeScript
stopSessionRecording(): void;

Turns session recording off and sets disable_session_recording to true.

Example

JavaScript
// Stop session recording
posthog.stopSessionRecording()

posthog.sessionRecordingStarted

TypeScript
sessionRecordingStarted(): boolean;

Returns whether session recording is currently running.

Returns

boolean

Whether session recording is currently running.

Example

JavaScript
// Stop session recording if it's running
if (posthog.sessionRecordingStarted()) {
posthog.stopSessionRecording()
}

posthog.get_session_replay_url

TypeScript
get_session_replay_url(options?: object): string;

Returns the Replay url for the current session.

Parameters

ParameterTypeDescription
options?{ timestampLookBack?: number; withTimestamp?: boolean; }Options for the URL.
options.timestampLookBack?numberHow many seconds to look back for the timestamp.
options.withTimestamp?booleanWhether 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

JavaScript
// basic usage
posthog.get_session_replay_url()
JavaScript
// timestamp
posthog.get_session_replay_url({ withTimestamp: true })
JavaScript
// timestamp and lookback
posthog.get_session_replay_url({
withTimestamp: true,
timestampLookBack: 30 // look back 30 seconds
})

posthog.get_session_id

TypeScript
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

TypeScript
onSessionId(callback: SessionIdChangedCallback): () => 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

ParameterTypeDescription
callbackSessionIdChangedCallbackCalled once a session ID is present or when it or the window ID changes.

Returns

Unsubscribe function.

() => void

Example

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

Error tracking

posthog.captureException

TypeScript
captureException(error: unknown, additionalProperties?: Properties): CaptureResult | undefined;

Captures a caught exception manually.

Parameters

ParameterTypeDescription
errorunknownThe error or exception-like value to capture.
additionalProperties?PropertiesAny additional properties to add to the error event.

Returns

CaptureResult | undefined

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

Examples

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

posthog.startExceptionAutocapture

TypeScript
startExceptionAutocapture(config?: ExceptionAutoCaptureConfig): void;

Turns exception autocapture on and updates the capture_exceptions config option.

Parameters

ParameterTypeDescription
config?ExceptionAutoCaptureConfigoptional configuration option to control the exception autocapture behavior

Examples

JavaScript
// Start with default exception autocapture rules. No-op if already enabled
posthog.startExceptionAutocapture()
JavaScript
// Start and override controls
posthog.startExceptionAutocapture({
capture_unhandled_errors: true,
capture_unhandled_rejections: true,
capture_console_errors: false,
})

posthog.stopExceptionAutocapture

TypeScript
stopExceptionAutocapture(): void;

Turns exception autocapture off by setting capture_exceptions to false.

Example

JavaScript
// Stop capturing exceptions automatically
posthog.stopExceptionAutocapture()

posthog.addExceptionStep

TypeScript
addExceptionStep(message: string, properties?: Properties): void;

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

Parameters

ParameterTypeDescription
messagestringThe step message.
properties?PropertiesAdditional context for this step.

Example

JavaScript
posthog.addExceptionStep('Checkout button clicked', {
checkout_id: 'ch_123',
})

Surveys

posthog.displaySurvey

TypeScript
displaySurvey(surveyId: string, options?: DisplaySurveyOptions): void;

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

Parameters

ParameterTypeDefault valueDescription
surveyIdstringundefinedThe survey ID to display.
options?DisplaySurveyOptionsDEFAULT_DISPLAY_SURVEY_OPTIONSDisplay configuration. Defaults to a popover that respects dashboard conditions and delays.

Examples

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

posthog.getActiveMatchingSurveys

TypeScript
getActiveMatchingSurveys(callback: SurveyCallback, forceReload?: boolean): void;

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

Parameters

ParameterTypeDefault valueDescription
callbackSurveyCallbackundefinedThe callback function will be called when the surveys are loaded or updated.
forceReload?booleanfalseWhether to force a reload of the surveys.

Example

JavaScript
posthog.getActiveMatchingSurveys((surveys) => {
// do something
})

posthog.getSurveys

TypeScript
getSurveys(callback: SurveyCallback, forceReload?: boolean): void;

Get list of all surveys.

Parameters

ParameterTypeDefault valueDescription
callbackSurveyCallbackundefinedFunction that receives the array of surveys.
forceReload?booleanfalseOptional boolean to force an API call for updated surveys.

Example

JavaScript
function callback(surveys, context) {
// do something
}
posthog.getSurveys(callback, false)

posthog.onSurveysLoaded

TypeScript
onSurveysLoaded(callback: SurveyCallback): () => 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

ParameterTypeDescription
callbackSurveyCallbackThe callback function will be called when surveys are loaded or updated.

Returns

A function that can be called to unsubscribe the listener.

() => void

Example

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

posthog.onActiveMatchingSurveysChanged

TypeScript
onActiveMatchingSurveysChanged(callback: SurveyCallback): () => 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

ParameterTypeDescription
callbackSurveyCallbackThe callback to call with active matching surveys.

Returns

A function that can be called to unsubscribe the listener.

() => void

Example

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

posthog.canRenderSurveyAsync

TypeScript
canRenderSurveyAsync(surveyId: string, forceReload?: boolean): Promise<SurveyRenderReason>;

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

Parameters

ParameterTypeDefault valueDescription
surveyIdstringundefinedThe ID of the survey to check.
forceReload?booleanfalseIf 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

JavaScript
posthog.canRenderSurveyAsync(surveyId).then((result) => {
if (result.visible) {
// Survey can be rendered
console.log('Survey can be rendered')
} else {
// Survey cannot be rendered
console.log('Survey cannot be rendered:', result.disabledReason)
}
})

posthog.cancelPendingSurvey

TypeScript
cancelPendingSurvey(surveyId: string): void;

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

Parameters

ParameterTypeDescription
surveyIdstringThe survey ID whose pending display should be cancelled.

posthog.opt_in_capturing

TypeScript
opt_in_capturing(options?: object): void;

Opts the user into data capturing and persistence.

Parameters

ParameterTypeDescription
options?{ captureEventName?: false | EventName | null; captureProperties?: Properties; }A dictionary of opt-in options.
options.captureEventName?false | EventName | nullEvent 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?PropertiesSet of properties to capture along with the opt-in action.

Remarks

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

Examples

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

posthog.opt_out_capturing

TypeScript
opt_out_capturing(): void;

Opts the user out of data capturing and persistence.

Remarks

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

Example

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

posthog.has_opted_in_capturing

TypeScript
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

JavaScript
if (posthog.has_opted_in_capturing()) {
// show analytics features
}

posthog.has_opted_out_capturing

TypeScript
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

JavaScript
if (posthog.has_opted_out_capturing()) {
// disable analytics features
}

posthog.is_capturing

TypeScript
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 SDK is capturing events.

Remarks

Controlled by cookieless_mode, opt_out_persistence_by_default, and respect_dnt.

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

Returns the explicit consent status of the user.

Returns

"granted" | "denied" | "pending"

The current explicit consent status.

Remarks

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

Example

JavaScript
const consentStatus = posthog.get_explicit_consent_status()
if (consentStatus === "granted") {
// user has explicitly opted in
} else if (consentStatus === "denied") {
// user has explicitly opted out
} else if (consentStatus === "pending"){
// user has not made a choice, show consent banner
}

posthog.clear_opt_in_out_capturing

TypeScript
clear_opt_in_out_capturing(): void;

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

SDK utils

sampleByDistinctId

TypeScript
function sampleByDistinctId(percent: number): 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

ParameterTypeDescription
percentnumberFraction of IDs to keep, from 0 (none) to 1 (all).

Returns

BeforeSendFn

Example

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

sampleBySessionId

TypeScript
function sampleBySessionId(percent: number): 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

ParameterTypeDescription
percentnumberFraction of sessions to keep, from 0 (none) to 1 (all).

Returns

BeforeSendFn

Example

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

sampleByEvent

TypeScript
function sampleByEvent(eventNames: string[], percent: number): 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

ParameterTypeDescription
eventNamesstring[]Event names to sample.
percentnumberFraction of matching events to keep, from 0 (none) to 1 (all).

Returns

BeforeSendFn

posthog.on

TypeScript
on(event: "eventCaptured" | "featureFlagsReloading", cb: (...args: any[]) => void): () => 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

ParameterTypeDescription
event"eventCaptured" | "featureFlagsReloading"The event to listen for.
cb(...args: any[]) => voidThe callback function to call when the event is emitted.

Returns

A function that can be called to unsubscribe the listener.

() => void

Examples

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

posthog.getEarlyAccessFeatures

TypeScript
getEarlyAccessFeatures(
callback: EarlyAccessFeatureCallback,
force_reload?: boolean,
stages?: EarlyAccessFeatureStage[]
): void;

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

Parameters

ParameterTypeDefault valueDescription
callbackEarlyAccessFeatureCallbackundefinedThe callback function will be called when the early access features are loaded.
force_reload?booleanfalseWhether to force a reload of the early access features.
stages?EarlyAccessFeatureStage[]undefinedThe stages of the early access features to load.

Example

JavaScript
posthog.getEarlyAccessFeatures((features) => {
const betaFeatures = features.filter((feature) => feature.stage === 'beta')
console.log(betaFeatures)
}, true, ['concept', 'beta'])

posthog.updateEarlyAccessFeatureEnrollment

TypeScript
updateEarlyAccessFeatureEnrollment(
key: string,
isEnrolled: boolean,
stage?: string
): void;

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

Parameters

ParameterTypeDescription
keystringThe key of the feature flag to update.
isEnrolledbooleanWhether the user is enrolled in the feature.
stage?stringThe stage of the feature flag to update.

Example

JavaScript
// Opt in to an early access feature
posthog.updateEarlyAccessFeatureEnrollment('beta-feature', true)
// Opt out
posthog.updateEarlyAccessFeatureEnrollment('beta-feature', false)

posthog.loadToolbar

TypeScript
loadToolbar(params: ToolbarParams): boolean;

Returns whether the toolbar loaded.

Parameters

ParameterTypeDescription
paramsToolbarParamsToolbar parameters.

Returns

boolean

Whether the toolbar loaded.

posthog.getPageViewId

TypeScript
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.flagsEndpointWasHit

TypeScript
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.version

TypeScript
version: string;

The library version.

Configuration

PostHogConfig

Configuration options for the PostHog JavaScript SDK. https://posthog.com/docs/libraries/js/config

Properties

PropertyTypeDescription
addTracingHeaders?string[]Deprecated Use tracing_headers instead. Kept for backwards compatibility.
advanced_disable_decide?booleanDeprecated 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_flagsbooleanWill 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_loadbooleanStops 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?booleanOne 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_metricsbooleanDetermines whether PostHog should disable toolbar metrics. This is our internal instrumentation for our toolbar in your website. Default false
advanced_enable_surveysbooleanWhen 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_sessionbooleanWhen 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_flagsbooleanDetermines 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_hoststringURL of your PostHog instance. Default 'https://us.i.posthog.com'
api_method?stringDeprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons
api_transport?"XHR" | "fetch"The transport method to use for API requests. Default 'fetch'
asset_hoststring | nullOptional 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
autocaptureboolean | AutocaptureConfigDetermines 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
bootstrapBootstrapConfigAn 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 | DeadClicksAutoCaptureConfigDetermines 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 | ExceptionAutoCaptureConfigDetermines whether to capture exceptions. When set, this overrides the project setting. When unset, the project setting applies. See Default undefined
capture_heatmaps?boolean | HeatmapConfigDetermines whether to capture heatmaps. When set, this overrides the project setting. When unset, the project setting applies. When the project limits heatmap capture to a list of URLs, heatmap data is only sent for matching URLs, even when this is set to true. Heatmap data is held until the project's setting is known. See Default undefined
capture_pageleaveboolean | "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_pageviewboolean | 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 | PerformanceCaptureConfigDetermines 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 | WebMCPCaptureConfigCaptures 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_namestring | nullDetermines 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?ConversationsConfigConversations-specific configuration options, such as the support widget theme. Default undefined
cookie_expirationnumberDetermines the number of days to store cookies for. Default 365
cookie_name?stringDeprecated - 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.
cookieWinsOnConflictbooleanIn '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_cookiebooleanDetermines 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_useragentsstring[]Extends the list of user-agent substrings that PostHog blocks from capturing (case-insensitive). posthog-js already blocks Chrome-Lighthouse, but third-party SEO crawlers built on Lighthouse (such as Ahrefs or Semrush) often send an ordinary browser user agent. Add a substring unique to that tool rather than a full browser user-agent string so real visitors aren't blocked. Default []
custom_campaign_paramsstring[]Used to extend the list of campaign parameters that are saved by default (such as utm_source and utm_medium). Default []
custom_personal_data_propertiesstring[]Custom list of personal data properties to mask. E.g. if you added email to this list, then any email property in the URL will be masked. https://www.example.com/login?email=john.doe%40example.com => https://www.example.com/login?email= Default [] See - Must be enabled for this to take effect.
debugbooleanDetermines 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
defaultsConfigDefaultsConfiguration 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?booleanDetect 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?booleanPrevents 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_hashesbooleanDetermines 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_compressionbooleanDetermines whether to disable compression when sending events to the server. WARNING: Should only be used for testing. Could negatively impact performance. Default false
disable_conversationsbooleanDetermines whether PostHog should disable all conversations functionality. Default false
disable_cookie?booleanDeprecated - use disable_persistence instead
disable_external_dependency_loadingbooleanDetermines 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_persistencebooleanDetermines 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_toursbooleanDetermines whether PostHog should disable all product tours functionality. Default false
disable_scroll_properties?booleanDetermines whether to disable scroll properties. These allow you to keep track of how far down someone scrolled in your website. Default false
disable_session_recordingbooleanDetermines whether PostHog should disable session recording. Recording starts only when this option and the project setting both allow it. Default false
disable_surveysbooleanDetermines whether PostHog should disable all surveys functionality. Default false
disable_surveys_automatic_displaybooleanDetermines 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_experimentsbooleanDetermines whether PostHog should disable web experiments. Currently disabled while we're in BETA. It will be toggled to true in a future release. Default true
disableDeviceModel?booleanDisables capturing the $device_model super-property. When capturing is enabled (the default), PostHog resolves the hardware model once during init via navigator.userAgentData.getHighEntropyValues(['model']) and registers it as the raw OEM code (e.g. Pixel 7). This is Chromium-only and only meaningful on Android — it resolves to undefined on Safari/Firefox and to an empty string on desktop, in which cases nothing is registered. This opt-out is offered because getHighEntropyValues is still experimental and Chromium-only (not yet a cross-browser standard); set it to true to skip the call entirely. Default false
enable_heatmaps?booleanDeprecated Use capture_heatmaps instead.
enable_recording_console_log?booleanDetermines 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_trackingErrorTrackingOptionsDetermines 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?numberSets 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_retriesnumberHow 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_msnumberSets timeout for fetching feature flags Default 3000
fetch_options?objectUsed 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 | nullURL 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) => stringOverrides 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) => stringFunction 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?stringVerified 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?stringHMAC-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?booleanDeprecated - NOT USED ANYMORE, kept here for backwards compatibility reasons
inapp_protocol?stringDeprecated - 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 | nullA 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 })
ipbooleanDeprecated - THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. Use a custom transformation or "Discard IP data" project setting instead: See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address.
loaded(posthog_instance: PostHog) => voidA function to be called once the PostHog scripts have loaded successfully.
logs?LogsConfigLogs-specific configuration options. Default undefined
mask_all_element_attributesbooleanPrevent autocapture from capturing any attribute names on elements. Default false
mask_all_textbooleanPrevent autocapture from capturing textContent on elements. Default false
mask_personal_data_propertiesbooleanMask 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?BrowserMetricsConfigMetrics-specific configuration options for the posthog.metrics API. Default undefined
namestringThe name this instance will be identified by. You don't need to set this most of the time, but can be useful if you have several Posthog instances running at the same time. Default 'posthog'
on_request_error?(error: RequestResponse) => voidA function that is called when a request to the PostHog API fails.
on_xhr_error?(failedRequest: XMLHttpRequest) => voidDeprecated - use on_request_error instead
opt_in_site_appsbooleanDetermines if users should be opted in to site apps. Default false
opt_out_capturing_by_defaultbooleanDetermines 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_prefixstring | nullDeprecated 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?booleanDetermines 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_filterbooleanDetermines 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 | nullDisplay 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_namestringThe name for the super properties persistent store Default ''
persistence_save_debounce_ms?numberCoalesce rapid Persistence.save() calls into a single write. Set to a positive number (milliseconds) to debounce writes to localStorage / cookie by that window. The in-memory props object is always updated synchronously so within-tab reads see the latest values immediately. Cross-tab storage events (which carry the full persistence value as a payload) are reduced proportionally to the debounce window. Pending writes are flushed on beforeunload and pagehide so no state is lost on tab close. The cross-tab visibility delay is bounded by the configured window. Defaults to 0 (no debouncing, write synchronously) for backwards compatibility. On pages that capture many events per second, 250 is a reasonable starting point to reduce localStorage write pressure and cross-tab IPC traffic. The 2026-05-30 config default opts into 250 automatically. Default 0
person_profiles?"always" | "never" | "identified_only"You can control whether events from PostHog-js have person processing enabled with the person_profiles config setting. There are three options: - person_profiles: 'always' - we will process persons data for all events - person_profiles: 'never' - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including $identify) will be sent with $process_person_profile: False. - person_profiles: 'identified_only' (default) - we will only process persons when you call posthog.identify, posthog.alias, posthog.setPersonProperties, posthog.unsetPersonProperties, posthog.group, posthog.setPersonPropertiesForFlags or posthog.setGroupPropertiesForFlags Anonymous users won't get person profiles. Default 'identified_only'
prepare_external_dependency_script?(script: HTMLScriptElement) => HTMLScriptElement | nullA function to be called when a script is being loaded. This can be used to modify the script before it is loaded. This is useful for adding a nonce to the script, for example.
prepare_external_dependency_stylesheet?(stylesheet: HTMLStyleElement) => HTMLStyleElement | nullA 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_lengthnumberDetermines 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_denyliststring[]A list of properties that should never be sent with capture calls. Default []
rageclickboolean | RageclickConfigDetermines 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?objectClient 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?numberHow 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?numberThe average number of events per second that should be permitted Default 10
remote_config_refresh_interval_ms?numberControls 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_batchingbooleanDetermines whether PostHog should batch requests to the PostHog API. Default true
request_headersobjectA list of headers that should be sent with requests to the PostHog API. Default {}
request_queue_config?RequestQueueConfigUsed to change the behavior of the request queue. This is an advanced feature and should be used with caution.
require_subresource_integrity?booleanRequires 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_dntbooleanDetermines whether PostHog should respect the Do Not Track header when computing consent in ConsentManager. See ConsentManager Default false
reuseAnonymousId?booleanWhen 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) => URLRewrites the URL used for PostHog API, feature flag, and asset requests. This is intended for customers who use a reverse proxy and need custom paths. The proxy must map the rewritten paths back to the canonical PostHog paths. UI links are not rewritten. Example posthog.init('phc_...', { api_host: 'https://a.example.com', rewriteRequestPath: (url) => { if (url.pathname === '/e/') { url.pathname = '/my-events/' } else if (url.pathname === '/s/') { url.pathname = '/my-replay/' } else if (url.pathname === '/flags/') { url.pathname = '/my-flags/' } return url }, })
sanitize_properties| ((properties: Properties, event_name: string) => Properties) | nullDeprecated - use before_send instead
save_campaign_paramsbooleanDetermines 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_referrerbooleanDetermines 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_cookiebooleanDetermines 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 | SegmentAnalyticsThe 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_secondsnumberDetermines 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_recordingSessionRecordingOptionsDetermines 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?booleanStore 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?booleanDeprecated - Use save_campaign_params instead
strict_script_versioningboolean | "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?SurveyConfigSurvey-specific configuration options. Default undefined
surveys_request_timeout_msnumberSets timeout for fetching surveys Default 10000
tokenstringThe 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_hoststring | nullIf 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
upgradebooleanDetermines 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?booleanDeprecated Use debug instead
xhr_headers?objectDeprecated - use request_headers instead

AutocaptureCompatibleElement

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

Properties

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

BeforeSendFn

TypeScript
type BeforeSendFn = (cr: CaptureResult) => CaptureResult | null;

Parameters

ParameterType
crCaptureResult

Returns

CaptureResult | null

BeforeSendLogFn

TypeScript
type BeforeSendLogFn = (record: CaptureLogOptions) => 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

ParameterType
recordCaptureLogOptions

Returns

CaptureLogOptions | null

Example

Redact secrets from log bodies

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

BootstrapConfig

PropertyTypeDescription
distinctID?string | nullDistinct ID to use before the SDK has loaded persisted identity.
featureFlagPayloads?Record<string, JsonType> | nullFeature flag payloads to use together with bootstrapped featureFlags.
featureFlags?Record<string, string | boolean> | nullFeature flag values to use immediately until the SDK fetches fresh values.
isIdentifiedID?boolean | nullWhether distinctID already identifies a known person profile.
sessionID?string | nullOptionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be: - unique to this user - a valid UUID v7 - the timestamp part must be <= the timestamp of the first event in the session - the timestamp of the last event in the session must be < the timestamp part + 24 hours

CanvasMaskRegion

TypeScript
type CanvasMaskRegion = object;

A rectangle to paint over a recorded canvas frame, in CSS pixels relative to the canvas element.

Properties

PropertyType
heightnumber
widthnumber
xnumber
ynumber

CapturedNetworkRequest

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

Type Declaration

NameType
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

PropertyTypeDescription
attributes?LogAttributesPer-log attributes (request-specific context like order_id, duration_ms)
bodystringThe log message body (required)
level?LogSeverityLevelLog severity level (default: 'info')
span_id?stringSpan ID for correlation — 16 hex chars
trace_flags?numberW3C trace flags (default: 0)
trace_id?stringTrace ID for correlation — 32 hex chars

CapturePageviewOptions

Selects which same-page URL changes automatically capture a $pageview. Each option defaults to false when omitted.

Properties

PropertyTypeDescription
hash?booleanCapture a pageview when location.hash changes, unless disable_capture_url_hashes is enabled.
path?booleanCapture a pageview when location.pathname changes.
search?booleanCapture a pageview when location.search changes.

CaptureResult

PropertyType
$set?Properties
$set_once?Properties
$unset?string[]
eventEventName
propertiesProperties
timestamp?Date
uuidstring

ConfigDefaults

TypeScript
type 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.

DeadClicksAutoCaptureConfig

TypeScript
type DeadClicksAutoCaptureConfig = object & Pick<AutocaptureConfig, "element_attribute_ignorelist">;

Type Declaration

NameTypeDescription
capture_clicks_with_modifier_keys?booleanBy 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?booleanDetermines 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?numberThe 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?numberWe'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?numberWe'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?numberWe'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?numberThe minimum straight-line distance in CSS pixels between where a touch gesture starts and ends for it to be considered a swipe (rather than a tap). Only used when capture_dead_swipes is enabled. Default 30

DomAutocaptureEvents

TypeScript
type DomAutocaptureEvents = "click" | "change" | "submit";

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

PropertyTypeDescriptionInherited from
captureExtensionExceptions?booleanDecide 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?ExceptionStepsConfigControls buffering and payload limits for exception steps added via addExceptionStep.-
exceptionRateLimiterBucketSize?numberADVANCED: 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 10ExceptionRateLimiterConfig.exceptionRateLimiterBucketSize
exceptionRateLimiterRefillRate?numberADVANCED: 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 1ExceptionRateLimiterConfig.exceptionRateLimiterRefillRate
release?| { build?: undefined; id: string; name?: undefined; version?: undefined; } | { build?: string; id?: undefined; name: string; version: string; }Release identity for manual and automatically captured exceptions only. Supply either a PostHog release id, or the name and version of a release that already exists in the project, as given to hog error-tracking through --release-name, --release-version, and optional --build. A Git commit SHA can be used as the version. This option does not create releases. Create the release first, for example with hog error-tracking release. Explicit event, session, or super-property release identity takes precedence over this option, which takes precedence over a build-injected release id. Name/version configuration sends $app_namespace, $app_version, and optional $app_build instead of $release_id. Blank or incomplete configuration is ignored. Values are trimmed. Example error_tracking: { release: { name: 'my-app', version: gitSha } } Default undefined-

EventName

TypeScript
type EventName = KnownUnsafeEditableEvent | KnownEventName | string & object;

ExceptionAutoCaptureConfig

TypeScript
type ExceptionAutoCaptureConfig = object;

Properties

PropertyTypeDescription
capture_console_errors?booleanDetermines whether PostHog should capture console errors. Default false
capture_unhandled_errors?booleanDetermines whether PostHog should capture unhandled errors. Default true
capture_unhandled_rejections?booleanDetermines 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

PropertyTypeDescription
exceptionRateLimiterBucketSize?numberADVANCED: 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?numberADVANCED: 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

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

PropertyTypeDescription
enabled?booleanDetermines whether PostHog should collect exception steps and attach them to the next captured exception. Default true
max_bytes?numberThe maximum UTF-8 byte budget for exception steps buffered in memory. Oldest steps are evicted when the budget is exceeded. Default 32768 (~32KB)

ExternalIntegrationKind

TypeScript
type ExternalIntegrationKind = "intercom" | "crispChat";

Headers

TypeScript
type Headers = Record<string, string>;

Request-related types

HeatmapConfig

PropertyTypeDescription
flush_interval_millisecondsnumberHow often to send batched data in $heatmap_data events If set to 0 or not set, sends using the default interval of 1 second Default 1000

HeatmapsRemoteConfig

PropertyType
captureMode?"all" | "url_allowlist"
urlAllowlist?string[]
urlAllowlistEnforced?boolean

InitiatorType

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

JsonRecord

TypeScript
type JsonRecord = object;

Index Signature

TypeScript
[key: string]: JsonType

JsonType

TypeScript
type JsonType = string | number | boolean | null | undefined | JsonRecord | JsonType[];

KnownEventName

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

These are known PostHog events that can be processed by the before_send hook. PostHog does not rely on receiving 100% of these events for core calculations, so it is safe to sample them to reduce volume.

KnownUnsafeEditableEvent

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

Known events that require extra care when editing in before_send because core PostHog features depend on them.

LogAttributes

TypeScript
type LogAttributes = Record<string, LogAttributeValue>;

LogAttributeValue

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

PropertyTypeDescription
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?stringThe deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'.
flushIntervalMs?numberFlush interval in milliseconds for batched log records. Default 3000
maxBufferSize?numberMaximum 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?numberMaximum 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?LogAttributesAdditional 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?stringThe service name for log records. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service'
serviceVersion?stringThe service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'.

LogsConfig

Logs configuration options

Extends

  • LogCaptureOptions

Properties

PropertyTypeDescriptionInherited 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?booleanAutomatically 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?stringThe deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'.LogCaptureOptions.environment
flushIntervalMs?numberFlush interval in milliseconds for batched log records. Default 3000LogCaptureOptions.flushIntervalMs
maxBufferSize?numberMaximum 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 100LogCaptureOptions.maxBufferSize
maxLogsPerInterval?numberMaximum 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 1000LogCaptureOptions.maxLogsPerInterval
resourceAttributes?LogAttributesAdditional 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?stringThe service name for log records. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service'LogCaptureOptions.serviceName
serviceVersion?stringThe service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'.LogCaptureOptions.serviceVersion

LogSeverityLevel

TypeScript
type LogSeverityLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";

Log capture types

MaskInputOptions

Mask input options for session recording

Properties

PropertyType
color?boolean
date?boolean
datetime-local?boolean
email?boolean
hidden?boolean
month?boolean
number?boolean
password?boolean
range?boolean
search?boolean
select?boolean
tel?boolean
text?boolean
textarea?boolean
time?boolean
url?boolean
week?boolean

PerformanceCaptureConfig

PropertyTypeDescription
network_timing?booleanWorks with session replay to use the browser's native performance observer to capture performance metrics
web_vitals?booleanUse 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?numberWe delay flushing web vitals metrics to reduce the number of events we send This is the maximum time we will wait before sending the metrics Default 5000

Properties

TypeScript
type Properties = Record<string, Property>;

Property

TypeScript
type Property = any;

Common types shared across PostHog SDKs

RageclickConfig

PropertyTypeDescription
click_count?numberNumber 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?booleanExcludes 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?numberMaximum pixel distance between clicks to still be considered a rage click. Default 30
timeout_ms?numberMaximum time window (in milliseconds) between the first and last click. Default 1000

RequestQueueConfig

PropertyTypeDescription
flush_interval_ms?numberADVANCED - 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

PropertyType
error?unknown
json?any
statusCodenumber
text?string

SegmentEnrichmentFilterFn

TypeScript
type SegmentEnrichmentFilterFn = (properties: 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

ParameterType
propertiesProperties

Returns

Properties | null

SegmentIntegrationConfig

TypeScript
type SegmentIntegrationConfig = object;

Configuration for the PostHog Segment integration.

Properties

PropertyTypeDescription
analyticsSegmentAnalyticsThe Segment analytics object.
filterProperties?SegmentEnrichmentFilterFn | SegmentEnrichmentFilterFn[]A function or array of functions called with the properties generated by PostHog before they are added to a Segment event. Return the properties to add, or null to leave the original Segment event unenriched. Original Segment properties are not passed to these functions. They are merged afterward and take precedence over properties returned by this hook. If a function throws, the original Segment event is left unchanged.

SessionRecordingCanvasOptions

TypeScript
type SessionRecordingCanvasOptions = object;

Properties

PropertyTypeDescription
canvasFps?number | nullIf 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 | nullIf 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 | nullIf set, records the canvas Default false

SessionRecordingOptions

PropertyTypeDescription
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 | RegExpDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-no-capture'
blockSelector?string | nullDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default null
canvasCapture?objectTune how canvas frames are captured for replay. Only has any effect when canvas recording is enabled. - resolutionScale: capture canvas frames at a fraction of their display resolution. A number in (0, 1]; 1 is full-resolution capture (the default) and, e.g., 0.6 captures at 60%. Out-of-range or non-finite values are clamped into (0, 1]. Aspect ratio is preserved and replay upscales the frame back to the original display size, so playback dimensions are unchanged, just softer. Resolution is the highest-leverage lever for canvas byte size, since bytes scale with pixel area. - maskRegionsFn: mask regions of a recorded canvas — see its doc comment.
canvasCapture.maskRegionsFn?| ((canvas: HTMLCanvasElement) => CanvasMaskRegion[] | null | undefined) | nullIf 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?SessionRecordingCanvasOptionsAllows local config to override remote canvas recording settings from the flags response. To mask content inside a recorded canvas, see canvasCapture.maskRegionsFn.
captureJsonLd?booleanCaptures 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?booleanDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
compress_events?booleanADVANCED: 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?numberADVANCED: 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 | RegExpDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-ignore-input'
inlineStylesheet?booleanDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default true
inlineStylesheetBudgetRules?numberMax 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?booleanDerived 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?booleanDerived from rrweb.record options. When true (the default) session replay masks the value of every input, except file inputs, whose values are recorded unmasked — block those with ph-no-capture or blockSelector if they hold sensitive data. Set it to false to record input values, which is not recommended for apps that handle sensitive data. A session_recording masking option set in posthog.init takes precedence over the project "Privacy and masking" setting; the SDK warns once when the two differ. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy Default true
maskAttributeFn?| ((name: string, value: string, element?: Element) => string) | nullDerived from rrweb.record options. Called with (name, value, element) for every non-empty string-valued attribute in the final serialized representation so you can mask specific attributes. Returning the original value leaves it visible. Mutually exclusive with maskAllElementAttributes: when both are set that option wins and this callback is ignored, so a callback cannot accidentally unmask what the coarse option hides. See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskCapturedNetworkRequestFn?| ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | nullModify the network request before it is captured. Returning null or undefined stops it being captured. Initial navigation and performance-timing entries are also passed to this function. They have isInitial === true, can have method === undefined, and contain the page URL in name. If the function returns null or undefined for an initial entry, PostHog retains the replay-required timing metadata but omits its URL, headers, and body. Return a modified entry to retain a redacted URL.
maskInputFn?((text: string, element?: HTMLElement) => string) | nullDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskInputOptions?Partial<MaskInputOptions>Derived from rrweb.record options. Selects which input types to mask by input attribute, for use when maskAllInputs is false. Password inputs are always masked by default: the SDK adds password: true to a partial override, so set password: false explicitly if you must record password fields. See - https://github.com/rrweb-io/rrweb/blob/master/guide.md - https://posthog.com/docs/session-replay/privacy
maskNetworkRequestFn?| ((data: NetworkRequest) => NetworkRequest | null | undefined) | nullDeprecated - use maskCapturedNetworkRequestFn instead
maskTextClass?string | RegExpDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default 'ph-mask'
maskTextFn?((text: string, element?: HTMLElement) => string) | nullDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md
maskTextSelector?string | nullDerived 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?booleanDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
recordCrossOriginIframes?booleanDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
recordHeaders?booleanDerived from rrweb.record options See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default false
sampleRate?numberThe 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?SessionRecordingSamplingConfigDerived from rrweb.record options. Controls how often certain event types are captured within an already-recorded session, e.g. { mousemove: false } stops recording mouse movement. Not to be confused with sampleRate below, which controls whether a session is recorded at all, or with posthog.startSessionRecording({ sampling: true }), which overrides that session-level sample rate. NB disabled event types no longer count as user activity for replay idle detection (session_idle_threshold_ms). For example, with mousemove: false pure mouse movement no longer keeps a session active, while clicks, scrolls, and inputs still do. See https://github.com/rrweb-io/rrweb/blob/master/guide.md Default undefined
selectMaskingFn?(element: HTMLSelectElement) => "masked" | "unmasked"Opt in to explicit select selection masking, overriding the select category setting. Masked selects use maskInputFn for replacement text but omit selection identity metadata. Returning original text from maskInputFn still records that text, even when this policy returns 'masked'. The callback is responsible for sanitizing its output. Unmasked selects retain their choices, including duplicate-valued options. Masked native <selectedcontent> clones are omitted. Static option labels remain visible. Pointer events are not covered: clicks on options in listbox-style selects (multiple, size > 1 or a customizable picker) still record the clicked option and position. Block selects whose choices must stay private, for example with ph-no-capture. Omit this option to preserve legacy maskInputFn behavior. Use a pure policy. It is evaluated for input events, select subtree mutations and snapshots; changes to external state take effect at the next such capture. Keep the callback reference stable. Replacing it restarts recording and discards queued old-policy data; changing its return value does not require a restart. Pending buffers are not carried across page loads with this option, because callback compatibility cannot be verified across pages. Invalid return values and exceptions resolve to masked. Recording does not start if the loaded recorder or driver does not support this option. Policy transitions also require a matching replay player.
session_idle_threshold_ms?numberADVANCED: 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?booleanWhen 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?booleanWhen 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?numberADVANCED: controls how much recent replay data is kept in memory while session recording waits for a conditional trigger. The recorder periodically takes a full snapshot and discards older buffered events, so increasing this interval retains more pre-trigger history but can increase memory usage and CPU usage. Performance impacts on your site can start to be visible to users with larger values. Values must be between 1,000 ms and 3,600,000 ms (1 hour, inclusive); values outside this range, or non-finite values, are ignored. Default 1000 * 60 (1 minute)

SessionRecordingSamplingConfig

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

Properties

PropertyTypeDescription
mouseInteraction?booleanWhen 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 | booleanControls capture of mouse movement within a recorded session. false disables capture entirely; NB this also disables touchmove and drag capture. A number throttles capture so that positions are captured at most once every N milliseconds. When undefined (or true), rrweb's default applies: capture throttled to every 50ms. Default undefined

SlimDOMOptions

Slim DOM options for session recording

Properties

PropertyType
comment?boolean
headFavicon?boolean
headMetaAuthorship?boolean
headMetaDescKeywords?boolean
headMetaHttpEquiv?boolean
headMetaRobots?boolean
headMetaSocial?boolean
headMetaVerification?boolean
headTitleMutations?boolean
headWhitespace?boolean
script?boolean

SupportedWebVitalsMetrics

TypeScript
type SupportedWebVitalsMetrics = "LCP" | "CLS" | "FCP" | "INP";

SurveyConfig

PropertyTypeDescription
autoSubmitDelay?numberDeprecated No longer used. Pre-filled responses are now sent immediately when partial responses are enabled, or all required questions have been pre-filled.
autoSubmitIfComplete?booleanDeprecated 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?booleanPrefill survey responses from matching URL parameters. Default undefined

WebMCPCaptureConfig

Selects the WebMCP metadata that PostHog captures. Options are applied when a tool registers. Re-register a tool after changing these options.

Properties

PropertyTypeDescription
intent?booleanCaptures the agent's reason for the tool call. Enabled by default.
model?booleanCaptures the model identifier that the agent reports. Enabled by default.

Types

ActionStepStringMatching

TypeScript
type ActionStepStringMatching = "contains" | "exact" | "regex";

ActionStepType

PropertyTypeDescription
event?string | null-
href?string | null-
href_matching?ActionStepStringMatching | nullDefault StringMatching.Exact
properties?object[]Property filters for action step matching.
selector?string | null-
selector_regex?string | nullPre-compiled regex pattern for matching selector against $elements_chain.
tag_name?stringDeprecated Only selector should be used now.
text?string | null-
text_matching?ActionStepStringMatching | nullDefault StringMatching.Exact
url?string | null-
url_matching?ActionStepStringMatching | nullDefault StringMatching.Contains

BasicSurveyQuestion

  • SurveyQuestionBase

Properties

PropertyTypeInherited from
branching?| NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranchingSurveyQuestionBase.branching
buttonText?stringSurveyQuestionBase.buttonText
description?string | nullSurveyQuestionBase.description
descriptionContentType?SurveyQuestionDescriptionContentTypeSurveyQuestionBase.descriptionContentType
id?stringSurveyQuestionBase.id
optional?booleanSurveyQuestionBase.optional
questionstringSurveyQuestionBase.question
translations?Record<string, SurveyQuestionTranslation>SurveyQuestionBase.translations
type"open"-
validation?SurveyValidationRule[]SurveyQuestionBase.validation

CaptureOptions

PropertyTypeDescription
$set?PropertiesUsed when $identify is called Will set person properties overriding previous values
$set_once?PropertiesUsed 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?booleanIf 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?booleanIf set, skips the client side rate limiting
timestamp?DateIf 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?stringIf set, overrides the auto-generated event uuid. The value must be a valid UUID; invalid values are ignored and a new UUID is generated. Useful for cross-source idempotency (e.g. a server webhook and a browser success page both firing for the same business transaction): emit both events with the same deterministic uuid so storage can eventually deduplicate them. Capture itself does not deduplicate resent events, and PostHog does not guarantee strict immediate deduplication.

Compression

TypeScript
type Compression = typeof Compression[keyof typeof Compression];

DisplaySurveyInlineOptions

  • DisplaySurveyOptionsBase

Properties

PropertyTypeDescriptionOverridesInherited from
displayType"inline"How the survey should be displayed. Default DisplaySurveyType.PopoverDisplaySurveyOptionsBase.displayType-
ignoreConditionsbooleanWhether to bypass the survey's targeting and display conditions. Default false-DisplaySurveyOptionsBase.ignoreConditions
ignoreDelaybooleanWhether 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?PropertiesAdditional properties to include in all survey events (shown, sent, dismissed).-DisplaySurveyOptionsBase.properties
selectorstringCSS selector for the element where the inline survey should render.--

DisplaySurveyOptions

TypeScript
type DisplaySurveyOptions = DisplaySurveyPopoverOptions | DisplaySurveyInlineOptions;

Options for posthog.displaySurvey().

DisplaySurveyOptionsBase

  • DisplaySurveyPopoverOptions
  • DisplaySurveyInlineOptions

Properties

PropertyTypeDescription
displayTypeDisplaySurveyTypeHow the survey should be displayed. Default DisplaySurveyType.Popover
ignoreConditionsbooleanWhether to bypass the survey's targeting and display conditions. Default false
ignoreDelaybooleanWhether 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?PropertiesAdditional properties to include in all survey events (shown, sent, dismissed).

DisplaySurveyPopoverOptions

Options for displaying a survey as a popover.

Extends

  • DisplaySurveyOptionsBase

Properties

PropertyTypeDescriptionOverridesInherited from
displayType"popover"How the survey should be displayed. Default DisplaySurveyType.PopoverDisplaySurveyOptionsBase.displayType-
ignoreConditionsbooleanWhether to bypass the survey's targeting and display conditions. Default false-DisplaySurveyOptionsBase.ignoreConditions
ignoreDelaybooleanWhether 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?SurveyPositionOverride the survey's configured position.--
properties?PropertiesAdditional properties to include in all survey events (shown, sent, dismissed).-DisplaySurveyOptionsBase.properties
selector?stringCSS selector for the element to position the survey next to (when position is NextToTrigger).--
skipShownEvent?booleanWhen true, survey shown events will not be emitted automatically.--

DisplaySurveyType

TypeScript
type DisplaySurveyType = typeof DisplaySurveyType[keyof typeof DisplaySurveyType];

EarlyAccessFeature

A feature that isn't publicly available yet.

Properties

PropertyTypeDescription
descriptionstring-
documentationUrlstring | null-
flagKeystring | null-
imageUrl?string | nullURL of an image that shows the feature, such as a screenshot. Empty when the feature has no image.
namestring-
payloadJsonType-
stage"concept" | "alpha" | "beta"-

EarlyAccessFeatureCallback

TypeScript
type EarlyAccessFeatureCallback = (earlyAccessFeatures: EarlyAccessFeature[]) => void;

Parameters

ParameterType
earlyAccessFeaturesEarlyAccessFeature[]

EarlyAccessFeatureResponse

PropertyType
earlyAccessFeaturesEarlyAccessFeature[]

EarlyAccessFeatureStage

TypeScript
type EarlyAccessFeatureStage = "concept" | "alpha" | "beta" | "general-availability";

EndBranching

PropertyType
type"end"

ErrorEventArgs

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

ErrorTrackingSuppressionRule

PropertyType
type"AND" | "OR"
valuesErrorTrackingSuppressionRuleValue[]

ErrorTrackingSuppressionRuleValue

PropertyType
key"$exception_types" | "$exception_values"
operatorSurveyMatchType
typestring
valuestring | string[]

EvaluationReason

TypeScript
type EvaluationReason = object;

Properties

PropertyType
codestring
condition_indexnumber | undefined
descriptionstring | undefined

EventHandler

TypeScript
type EventHandler = (event: Event) => boolean | void;

Parameters

ParameterType
eventEvent

Returns

boolean | void

FeatureFlagDetail

TypeScript
type FeatureFlagDetail = object;

Properties

PropertyType
enabledboolean
failed?boolean
keystring
metadataFeatureFlagMetadata | undefined
original_enabled?boolean
original_variant?string
reasonEvaluationReason | undefined
variantstring | undefined

FeatureFlagMetadata

TypeScript
type FeatureFlagMetadata = object;

Properties

PropertyTypeDescription
descriptionstring | undefined-
has_experiment?booleanWhether the flag is linked to an experiment. Absent when the server does not report it.
idnumber-
original_payload?JsonType-
payloadJsonType | undefined-
versionnumber | undefined-

FeatureFlagOptions

TypeScript
type FeatureFlagOptions = object;

Options for feature flag lookup methods (getFeatureFlag, isFeatureEnabled, getFeatureFlagResult).

Properties

PropertyTypeDescription
fresh?booleanIf 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?booleanWhether to send a $feature_flag_called event. Defaults to true.

FeatureFlagOverrideOptions

TypeScript
type FeatureFlagOverrideOptions = object;

Properties

PropertyType
flags?boolean | string[] | FeatureFlagOverrides
payloads?FeatureFlagPayloadOverrides
suppressWarning?boolean

FeatureFlagOverrides

TypeScript
type FeatureFlagOverrides = object;

Index Signature

TypeScript
[flagName: string]: string | boolean

FeatureFlagPayloadOverrides

TypeScript
type FeatureFlagPayloadOverrides = object;

Index Signature

TypeScript
[flagName: string]: JsonType

FeatureFlagResult

TypeScript
type FeatureFlagResult = object;

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

Properties

PropertyModifierTypeDescription
enabledreadonlybooleanWhether the returned feature flag evaluation is enabled. false is a conclusive off result.
keyreadonlystringThe key of the feature flag
payloadreadonlyJsonType | undefinedThe JSON payload associated with this flag, if any
variantreadonlystring | undefinedThe variant key if this is a multivariate flag, undefined for boolean flags

FeatureFlagsCallback

TypeScript
type FeatureFlagsCallback = (flags: string[], variants: Record<string, string | boolean>, context?: object) => void;

Parameters

ParameterType
flagsstring[]
variantsRecord<string, string | boolean>
context?{ errorsLoading?: boolean; }
context.errorsLoading?boolean

FlagVariant

TypeScript
type FlagVariant = object;

Properties

PropertyType
flagstring
variantstring

IsFeatureEnabledOptions

TypeScript
type IsFeatureEnabledOptions = FeatureFlagOptions & object;

Options for isFeatureEnabled.

Type Declaration

NameTypeDescription
defaultValue?booleanValue to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists.

LinkSurveyQuestion

  • SurveyQuestionBase

Properties

PropertyTypeInherited from
branching?| NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranchingSurveyQuestionBase.branching
buttonText?stringSurveyQuestionBase.buttonText
description?string | nullSurveyQuestionBase.description
descriptionContentType?SurveyQuestionDescriptionContentTypeSurveyQuestionBase.descriptionContentType
id?stringSurveyQuestionBase.id
link?string | null-
optional?booleanSurveyQuestionBase.optional
questionstringSurveyQuestionBase.question
translations?Record<string, SurveyQuestionTranslation>SurveyQuestionBase.translations
type"link"-
validation?SurveyValidationRule[]SurveyQuestionBase.validation

Logger

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

Example

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

Methods

debug()
TypeScript
debug(body: string, attributes?: LogAttributes): void;

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

Parameters
ParameterType
bodystring
attributes?LogAttributes
error()
TypeScript
error(body: string, attributes?: LogAttributes): void;

Error. Operation failed; the app may continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
fatal()
TypeScript
fatal(body: string, attributes?: LogAttributes): void;

Fatal. Operation failed; the app likely cannot continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
info()
TypeScript
info(body: string, attributes?: LogAttributes): void;

Informational. Normal app events worth recording.

Parameters
ParameterType
bodystring
attributes?LogAttributes
trace()
TypeScript
trace(body: string, attributes?: LogAttributes): void;

Lowest severity. Trace-level diagnostic detail.

Parameters
ParameterType
bodystring
attributes?LogAttributes
warn()
TypeScript
warn(body: string, attributes?: LogAttributes): void;

Warning. Something unexpected but non-fatal.

Parameters
ParameterType
bodystring
attributes?LogAttributes

MultipleSurveyQuestion

  • SurveyQuestionBase

Properties

PropertyTypeInherited from
branching?| NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranchingSurveyQuestionBase.branching
buttonText?stringSurveyQuestionBase.buttonText
choicesstring[]-
description?string | nullSurveyQuestionBase.description
descriptionContentType?SurveyQuestionDescriptionContentTypeSurveyQuestionBase.descriptionContentType
hasOpenChoice?boolean-
id?stringSurveyQuestionBase.id
optional?booleanSurveyQuestionBase.optional
questionstringSurveyQuestionBase.question
shuffleOptions?boolean-
skipSubmitButton?boolean-
translations?Record<string, SurveyQuestionTranslation>SurveyQuestionBase.translations
type"multiple_choice" | "single_choice"-
validation?SurveyValidationRule[]SurveyQuestionBase.validation

NetworkRecordOptions

TypeScript
type NetworkRecordOptions = object;

Properties

PropertyTypeDescription
initiatorTypes?InitiatorType[]-
maskRequestFn?(data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined-
payloadHostDenyList?string[]some domains we should never record the payload for example other companies session replay ingestion payloads aren't super useful but are gigantic if this isn't provided we use a default list if this is provided - we add the provided list to the default list i.e. we never record the payloads on the default deny list
payloadSizeLimitBytesnumberthe maximum size of the request/response body to record NB this will be at most 1MB even if set larger
performanceEntryTypeToObservestring[]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?booleanwhether to record PerformanceEntry events for network requests
streamNetworkBody?booleanwhen true, read bodies through a streaming reader that stops at payloadSizeLimitBytes instead of buffering the whole body and then enforcing the limit. Reads only a clone of the body, so it never consumes the stream the page itself reads. Default false

NextQuestionBranching

PropertyType
type"next_question"

OverrideFeatureFlagsOptions

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

PropertyFilters

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

PropertyMatchType

TypeScript
type PropertyMatchType = SurveyMatchType;

PropertyOperator

TypeScript
type PropertyOperator = PropertyMatchType | "gt" | "lt";

RatingSurveyQuestion

  • SurveyQuestionBase

Properties

PropertyTypeInherited from
branching?| NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranchingSurveyQuestionBase.branching
buttonText?stringSurveyQuestionBase.buttonText
description?string | nullSurveyQuestionBase.description
descriptionContentType?SurveyQuestionDescriptionContentTypeSurveyQuestionBase.descriptionContentType
display"number" | "emoji"-
id?stringSurveyQuestionBase.id
lowerBoundLabelstring-
optional?booleanSurveyQuestionBase.optional
questionstringSurveyQuestionBase.question
scale2 | 3 | 5 | 7 | 10-
skipSubmitButton?boolean-
translations?Record<string, SurveyQuestionTranslation>SurveyQuestionBase.translations
type"rating"-
upperBoundLabelstring-
validation?SurveyValidationRule[]SurveyQuestionBase.validation

RemoteConfigFeatureFlagCallback

TypeScript
type RemoteConfigFeatureFlagCallback = (payload: JsonType) => void;

Parameters

ParameterType
payloadJsonType

RequestCallback

TypeScript
type RequestCallback = (response: RequestResponse) => void;

Parameters

ParameterType
responseRequestResponse

ResetOptions

PropertyTypeDescription
bootstrap?BootstrapConfigIdentity, feature flag, and session values to apply after resetting.
resetDeviceID?booleanWhether to generate a new device ID as well as a new distinct ID. Default false

ResponseBasedBranching

PropertyType
responseValuesRecord<string, any>
type"response_based"

SessionIdChangedCallback

TypeScript
type SessionIdChangedCallback = (sessionId: string, windowId: string | null | undefined, changeReason?: object) => void;

Parameters

ParameterTypeDescription
sessionIdstring-
windowIdstring | null | undefined-
changeReason?{ activityTimeout: boolean; crossTabAdoption?: boolean; noSessionId: boolean; sessionPastMaximumLength: boolean; }-
changeReason.activityTimeoutboolean-
changeReason.crossTabAdoption?booleanThis tab picked up a session rotation another tab had already written to storage, instead of minting its own.
changeReason.noSessionIdboolean-
changeReason.sessionPastMaximumLengthboolean-

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

PropertyType
namestring
properties?SessionRecordingTriggerPropertyFilter[]

SessionRecordingTriggerGroup

V2 Trigger Group - represents a single trigger group with its own conditions and sample rate

Properties

PropertyType
conditionsobject
conditions.events?SessionRecordingEventTrigger[]
conditions.flag?string | FlagVariant
conditions.matchType"all" | "any"
conditions.properties?SessionRecordingTriggerPropertyFilter[]
conditions.urls?SessionRecordingUrlTrigger[]
idstring
minDurationMs?number
namestring
sampleRatenumber

SessionRecordingTriggerPropertyFilter

PropertyType
keystring
operator?| "regex" | "not_regex" | "exact" | "is_not" | "icontains" | "not_icontains" | "gt" | "lt"
type"event" | "person"
value?string | number | boolean | string[]

SessionRecordingUrlTrigger

PropertyType
matching"regex"
urlstring

SessionStartReason

TypeScript
type SessionStartReason =
| "sampling_overridden"
| "recording_initialized"
| "linked_flag_matched"
| "linked_flag_overridden"
| "sampled"
| "session_id_changed"
| "url_trigger_matched"
| "event_trigger_matched";

Why session recording started for the current session.

SeverityLevel

TypeScript
type SeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug";

SpecificQuestionBranching

PropertyType
indexnumber
type"specific_question"

Survey

A survey definition returned as part of browser remote config.

Properties

PropertyType
appearanceSurveyAppearance | 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_iterationnumber | null
current_iteration_start_datestring | null
description?string
enable_partial_responses?boolean | null
end_datestring | null
feature_flag_keysobject[] | null
idstring
internal_targeting_flag_keystring | null
linked_flag_keystring | null
namestring
questionsSurveyQuestion[]
schedule?SurveySchedule | null
start_datestring | null
targeting_flag_keystring | null
translations?Record<string, SurveyTranslation>
typeSurveyType

SurveyActionType

PropertyType
idnumber
namestring | null
steps?ActionStepType[]

SurveyAppearance

Browser survey appearance, including browser-only placement and rendering options.

Extends

  • Omit<SurveyAppearance, "position" | "widgetType">

Properties

PropertyTypeDescriptionOverridesInherited from
allowGoBack?boolean--Omit.allowGoBack
autoDisappear?boolean--Omit.autoDisappear
backButtonText?string--Omit.backButtonText
backgroundColor?string--Omit.backgroundColor
borderColor?string--Omit.borderColor
boxPadding?string---
descriptionTextColor?stringDeprecated Not currently used.--
disableAutofocus?boolean---
disabledButtonOpacity?string---
displayIntroScreen?boolean--Omit.displayIntroScreen
displayThankYouMessage?boolean--Omit.displayThankYouMessage
fontFamily?string-Omit.fontFamily-
hideCancelButton?boolean---
inputBackground?string--Omit.inputBackground
inputBackgroundColor?stringDeprecated Use inputBackground instead.--
inputTextColor?string--Omit.inputTextColor
introScreenButtonText?string--Omit.introScreenButtonText
introScreenDescription?string--Omit.introScreenDescription
introScreenDescriptionContentType?SurveyQuestionDescriptionContentType--Omit.introScreenDescriptionContentType
introScreenHeader?string--Omit.introScreenHeader
maxWidth?string---
placeholder?string--Omit.placeholder
position?SurveyPosition---
ratingButtonActiveColor?string--Omit.ratingButtonActiveColor
ratingButtonColor?string--Omit.ratingButtonColor
ratingButtonHoverColor?string---
shuffleQuestions?boolean--Omit.shuffleQuestions
submitButtonColor?string--Omit.submitButtonColor
submitButtonText?string--Omit.submitButtonText
submitButtonTextColor?string--Omit.submitButtonTextColor
surveyPopupDelaySeconds?number--Omit.surveyPopupDelaySeconds
tabPosition?SurveyTabPosition---
textColor?string--Omit.textColor
thankYouMessageCloseButtonText?string--Omit.thankYouMessageCloseButtonText
thankYouMessageDescription?string--Omit.thankYouMessageDescription
thankYouMessageDescriptionContentType?SurveyQuestionDescriptionContentType--Omit.thankYouMessageDescriptionContentType
thankYouMessageHeader?string--Omit.thankYouMessageHeader
whiteLabel?boolean---
widgetColor?string--Omit.widgetColor
widgetLabel?string--Omit.widgetLabel
widgetSelector?string--Omit.widgetSelector
widgetType?SurveyWidgetType---
zIndex?string---

SurveyCallback

TypeScript
type SurveyCallback = (surveys: Survey[], context?: object) => void;

Parameters

ParameterType
surveysSurvey[]
context?{ error?: string; isLoaded: boolean; }
context.error?string
context.isLoadedboolean

SurveyElement

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

TypeScript
type SurveyEventName = typeof SurveyEventName[keyof typeof SurveyEventName];

SurveyEventProperties

TypeScript
type SurveyEventProperties = typeof SurveyEventProperties[keyof typeof SurveyEventProperties];

SurveyEventType

TypeScript
type SurveyEventType = typeof SurveyEventType[keyof typeof SurveyEventType];

SurveyEventWithFilters

PropertyType
namestring
propertyFilters?PropertyFilters

SurveyMatchType

TypeScript
type SurveyMatchType = typeof SurveyMatchType[keyof typeof SurveyMatchType];

SurveyPosition

TypeScript
type SurveyPosition = typeof SurveyPosition[keyof typeof SurveyPosition];

SurveyQuestion

TypeScript
type SurveyQuestion =
| BasicSurveyQuestion
| LinkSurveyQuestion
| RatingSurveyQuestion
| MultipleSurveyQuestion;

SurveyQuestionBase

  • BasicSurveyQuestion
  • LinkSurveyQuestion
  • RatingSurveyQuestion
  • MultipleSurveyQuestion

Properties

PropertyType
branching?| NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching
buttonText?string
description?string | null
descriptionContentType?SurveyQuestionDescriptionContentType
id?string
optional?boolean
questionstring
translations?Record<string, SurveyQuestionTranslation>
validation?SurveyValidationRule[]

SurveyQuestionBranchingType

TypeScript
type SurveyQuestionBranchingType = typeof SurveyQuestionBranchingType[keyof typeof SurveyQuestionBranchingType];

SurveyQuestionDescriptionContentType

TypeScript
type SurveyQuestionDescriptionContentType = "html" | "text";

SurveyQuestionTranslation

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

SurveyQuestionType

TypeScript
type SurveyQuestionType = typeof SurveyQuestionType[keyof typeof SurveyQuestionType];

SurveyRenderReason

Represents the result of checking if a survey can be rendered.

Properties

PropertyTypeDescription
disabledReason?stringThe reason why the survey cannot be rendered, if applicable
visiblebooleanWhether the survey is visible/can be rendered

SurveyResponseValue

TypeScript
type SurveyResponseValue = string | number | string[] | null;

SurveySchedule

TypeScript
type SurveySchedule = typeof SurveySchedule[keyof typeof SurveySchedule];

SurveyTabPosition

TypeScript
type SurveyTabPosition = typeof SurveyTabPosition[keyof typeof SurveyTabPosition];

SurveyTranslation

PropertyType
backButtonText?string
introScreenButtonText?string
introScreenDescription?string
introScreenHeader?string
name?string
submitButtonText?string
thankYouMessageCloseButtonText?string
thankYouMessageDescription?string
thankYouMessageHeader?string

SurveyType

TypeScript
type SurveyType = typeof SurveyType[keyof typeof SurveyType];

SurveyValidationRule

PropertyType
errorMessage?string
typeSurveyValidationType
value?number

SurveyValidationType

TypeScript
type SurveyValidationType = typeof SurveyValidationType[keyof typeof SurveyValidationType];

SurveyWidgetType

TypeScript
type SurveyWidgetType = typeof SurveyWidgetType[keyof typeof SurveyWidgetType];

SurveyWithTypeAndAppearance

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

ToolbarParams

Parameters for loading the PostHog toolbar

Properties

PropertyTypeDescription
actionId?numberAction ID to edit
dataAttributes?string[]Data attributes to capture
distinctId?stringDistinct ID of the user
featureFlags?Record<string, string | boolean>Feature flags
instrument?booleanWhether to instrument
source?ToolbarSourceSource of the toolbar params
temporaryToken?stringPrivate temporary user token
token?stringPublic posthog-js token
toolbarVersion?"toolbar"Toolbar version
userEmail?stringEmail of the user
userIntent?ToolbarUserIntentUser intent for the toolbar

ToolbarSource

TypeScript
type ToolbarSource = "url" | "localstorage";

ToolbarUserIntent

TypeScript
type ToolbarUserIntent = "add-action" | "edit-action";

Toolbar types

ToolbarVersion

TypeScript
type ToolbarVersion = "toolbar";

Was this page useful?