> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
# PostHog JavaScript Web SDK
Canonical URL: https://posthog.com/docs/libraries/js/reference
> **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host), and use `https://eu.posthog.com` instead of `https://us.posthog.com` or `https://app.posthog.com` (app host for links).
## On this page
- [Getting started](#getting-started)
- [Setup](#setup)
- [Capture](#capture)
- [Identify](#identify)
- [Logs](#logs)
- [Alias](#alias)
- [Capture AI](#capture-ai)
- [Capture exception](#capture-exception)
- [Create person profile](#create-person-profile)
- [Debug](#debug)
- [Exception steps](#exception-steps)
- [Get distinct ID](#get-distinct-id)
- [Get feature flag](#get-feature-flag)
- [Get feature flag payload](#get-feature-flag-payload)
- [Get feature flag result](#get-feature-flag-result)
- [Get feature flags](#get-feature-flags)
- [Get session ID](#get-session-id)
- [Group](#group)
- [Is feature enabled](#is-feature-enabled)
- [Is opt out](#is-opt-out)
- [Is session replay active](#is-session-replay-active)
- [On feature flags](#on-feature-flags)
- [Opt in](#opt-in)
- [Register](#register)
- [Reload feature flags](#reload-feature-flags)
- [Reset](#reset)
- [Reset group properties for flags](#reset-group-properties-for-flags)
- [Reset person properties for flags](#reset-person-properties-for-flags)
- [Set group properties for flags](#set-group-properties-for-flags)
- [Set person properties](#set-person-properties)
- [Set person properties for flags](#set-person-properties-for-flags)
- [Shutdown](#shutdown)
- [Start session recording](#start-session-recording)
- [Stop session recording](#stop-session-recording)
- [Unregister](#unregister)
- [Consent gating](#consent-gating)
- [Surveys](#surveys)
- [SDK utils](#sdk-utils)
- [Types](#types)
## Getting started
The JavaScript Web SDK runs in the browser.
To send your first event, add the HTML snippet to your site, or install `posthog-js` and call `posthog.init` once. Both take your project token and host from your [project settings](https://app.posthog.com/project/settings).
After `init`, PostHog captures pageviews and clicks by itself, so loading a page sends your first event to the Activity page in PostHog. Use `capture` for your own events.
For server-side JavaScript, use the Node.js SDK.
### Install with the HTML snippet
The snippet is the quickest way to add PostHog to a website. Paste it inside your site's `
` tags, just before ``, so PostHog loads on every page. Replace the project token and host with your own.
The snippet loads the latest SDK from PostHog and calls `init`, so you can skip the next two steps.
```html
```
### Install with a package manager
```bash
npm install posthog-js
```
### Initialize
```typescript
import posthog from 'posthog-js'
posthog.init('', { api_host: 'https://us.i.posthog.com' })
```
### Capture an event
```typescript
posthog.capture('signed_up', { plan: 'pro' })
```
### Identify a user
```typescript
posthog.identify('user_123', { email: 'user@example.com' })
```
## Setup
### `new PostHog(...)`
> **new PostHog**(): `PostHog`
Creates an uninitialized PostHog instance.
#### Returns
`PostHog`
#### Remarks
Most browser applications should use the default exported singleton and call `posthog.init()`. Construct a new instance only when you need to manage a separate SDK instance manually.
#### Example
```javascript
const instance = new PostHog()
instance.init('', { api_host: 'https://us.i.posthog.com' })
```
### `PostHog.init`
> **init**(`token`, `config?`, `name?`): `PostHog`
Initializes a new instance of the PostHog capturing object.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `token` | `string` | Your PostHog API token |
| `config?` | `Partial`<`PostHogConfig`\> | A dictionary of config options to override |
| `name?` | `string` | The name for the new posthog instance that you want created |
#### Returns
`PostHog`
The newly initialized PostHog instance
#### Remarks
All new instances are added to the main posthog object as sub properties (such as `posthog.library_name`) and also returned by this function. [Learn more about configuration options](https://posthog.com/docs/libraries/js/config)
#### Examples
```javascript
// basic initialization
posthog.init('', {
api_host: 'https://us.i.posthog.com'
})
```
```javascript
// multiple instances
posthog.init('', {}, 'project1')
posthog.init('', {}, 'project2')
```
### `PostHog.set_config`
> **set\_config**(`config`): `void`
Updates the configuration of the PostHog instance.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `config` | `Partial`<`PostHogConfig`\> | A dictionary of new configuration values to update |
#### Returns
`void`
### `posthog`
> `const` **posthog**: `PostHog`
The default PostHog JavaScript Web SDK singleton instance.
## Capture
### `PostHog.capture`
> **capture**(`event_name`, `properties?`, `options?`): `CaptureResult` | `undefined`
Captures an event with optional properties and configuration.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `event_name` | `EventName` | The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase') |
| `properties?` | `Properties` \| `null` | Properties to include with the event describing the user or event details |
| `options?` | `CaptureOptions` | Optional configuration for the capture request |
#### Returns
`CaptureResult` | `undefined`
The capture result containing event data, or undefined if capture failed
#### Remarks
You can capture arbitrary object-like values as events. [Learn about capture best practices](https://posthog.com/docs/product-analytics/capture-events.md)
#### Example
```javascript
// basic event capture
posthog.capture('cta-button-clicked', {
button_name: 'Get Started',
page: 'homepage'
})
```
## Identify
### `PostHog.clearIdentity`
> **clearIdentity**(): `void`
Clear HMAC-based identity verification, reverting to anonymous mode.
#### Returns
`void`
#### Example
```javascript
posthog.clearIdentity()
```
### `PostHog.identify`
> **identify**(`new_distinct_id?`, `userPropertiesToSet?`, `userPropertiesToSetOnce?`): `void`
Associates a user with a unique identifier instead of an auto-generated ID. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify.md)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `new_distinct_id?` | `string` | A non-empty string that uniquely identifies a user. |
| `userPropertiesToSet?` | `Properties` | Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet. |
| `userPropertiesToSetOnce?` | `Properties` | Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. |
#### Returns
`void`
#### Remarks
By default, PostHog assigns each user a randomly generated `distinct_id`. Use this method to replace that ID with your own unique identifier (like a user ID from your database).
#### Examples
```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.setIdentity`
> **setIdentity**(`distinctId`, `hash`): `void`
Set HMAC-based identity verification.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `distinctId` | `string` | The verified user distinct\_id |
| `hash` | `string` | HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings |
#### Returns
`void`
#### Remarks
When set, products like conversations use server-verified identity (distinct\_id + HMAC hash) instead of anonymous session identifiers. The hash should be computed server-side as HMAC-SHA256 of the distinct\_id, signed with the Secret API key from Support settings. Project secret API keys (project settings) and personal API keys are rejected. Any additional signed identity claims are cleared because they are bound to the previously configured distinct\_id.
#### Example
```javascript
posthog.setIdentity('user_123', 'a1b2c3d4e5f6...')
```
## Logs
### `PostHog.logger`
> **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`
> **captureLog**(`options`): `void`
Capture a log entry and send it to the PostHog logs endpoint.
Note: logs are not subject to the user agent (bot) filter that drops events, so they are still sent from sessions whose events are dropped.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `options` | `CaptureLogOptions` | The log entry options |
#### Returns
`void`
#### Example
```javascript
posthog.captureLog({
body: 'checkout completed',
level: 'info',
attributes: { order_id: 'ord_789', amount_cents: 4999 },
})
```
## Alias
### `PostHog.alias`
> **alias**(`alias`, `original?`): `number` | `void` | `CaptureResult`
Creates an alias linking two distinct user identifiers. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify.md)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `alias` | `string` | A unique identifier that you want to use for this user in the future. |
| `original?` | `string` | The current identifier being used for this user. |
#### Returns
`number` | `void` | `CaptureResult`
The `$create_alias` capture result, `-1` if alias matches the current distinct ID, `-2` if aliasing would duplicate a People user, or void if person processing is disabled.
#### Remarks
PostHog will use this to link two distinct\_ids going forward (not retroactively). Call this when a user signs up to connect their anonymous session with their account.
#### Examples
```javascript
// link anonymous user to account on signup
posthog.alias('user_12345')
```
```javascript
// explicit alias with original ID
posthog.alias('user_12345', 'anonymous_abc123')
```
## Capture AI
### `PostHog.captureTraceFeedback`
> **captureTraceFeedback**(`traceId`, `userFeedback`): `void`
Capture written user feedback for a LLM trace. Numeric values are converted to strings.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `traceId` | `string` \| `number` | The trace ID to capture feedback for. |
| `userFeedback` | `string` | The feedback to capture. |
#### Returns
`void`
### `PostHog.captureTraceMetric`
> **captureTraceMetric**(`traceId`, `metricName`, `metricValue`): `void`
Capture a metric for a LLM trace. Numeric values are converted to strings.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `traceId` | `string` \| `number` | The trace ID to capture the metric for. |
| `metricName` | `string` | The name of the metric to capture. |
| `metricValue` | `string` \| `number` \| `boolean` | The value of the metric to capture. |
#### Returns
`void`
## Capture exception
### `PostHog.captureException`
> **captureException**(`error`, `additionalProperties?`): `CaptureResult` | `undefined`
Capture a caught exception manually
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `error` | `unknown` | The error or exception-like value to capture. |
| `additionalProperties?` | `Properties` | Any additional properties to add to the error event. |
#### Returns
`CaptureResult` | `undefined`
The result of the capture, or undefined if exception capture is unavailable.
#### Examples
```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`
> **startExceptionAutocapture**(`config?`): `void`
turns exception autocapture on, and updates the config option `capture_exceptions` to the provided config (or `true`)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `config?` | `ExceptionAutoCaptureConfig` | optional configuration option to control the exception autocapture behavior |
#### Returns
`void`
#### Examples
```javascript
// Start with default exception autocapture rules. No-op if already enabled
posthog.startExceptionAutocapture()
```
```javascript
// Start and override controls
posthog.startExceptionAutocapture({
// you don't have to send all of these (unincluded values will use the default)
capture_unhandled_errors: true || false,
capture_unhandled_rejections: true || false,
capture_console_errors: true || false
})
```
### `PostHog.stopExceptionAutocapture`
> **stopExceptionAutocapture**(): `void`
turns exception autocapture off by updating the config option `capture_exceptions` to `false`
#### Returns
`void`
#### Example
```javascript
// Stop capturing exceptions automatically
posthog.stopExceptionAutocapture()
```
## Create person profile
### `PostHog.createPersonProfile`
> **createPersonProfile**(): `void`
Creates a person profile for the current user, if they don't already have one and config.person\_profiles is set to 'identified\_only'. Produces a warning and does not create a profile if config.person\_profiles is set to 'never'. Learn more about [person profiles](https://posthog.com/docs/product-analytics/identify.md)
#### Returns
`void`
#### Example
```javascript
posthog.createPersonProfile()
```
## Debug
### `PostHog.debug`
> **debug**(`debug?`): `void`
Enables or disables debug mode for detailed logging.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `debug?` | `boolean` | If true, will enable debug mode. |
#### Returns
`void`
#### Remarks
Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding `?__posthog_debug=true` to the URL.
#### Examples
```javascript
// enable debug mode
posthog.debug(true)
```
```javascript
// disable debug mode
posthog.debug(false)
```
## Exception steps
### `PostHog.addExceptionStep`
> **addExceptionStep**(`message`, `properties?`): `void`
Add a breadcrumb-like step that will be attached to the next captured exception.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `message` | `string` | The step message. |
| `properties?` | `Properties` | Additional context for this step. |
#### Returns
`void`
#### Example
```javascript
posthog.addExceptionStep('Checkout button clicked', {
checkout_id: 'ch_123',
})
```
## Get distinct ID
### `PostHog.get_distinct_id`
> **get\_distinct\_id**(): `string`
Returns the current distinct ID for the user.
#### Returns
`string`
The current distinct ID
#### Remarks
This is either the auto-generated ID or the ID set via `identify()`. The distinct ID is used to associate events with users in PostHog.
#### Examples
```javascript
// get the current user ID
const userId = posthog.get_distinct_id()
console.log('Current user:', userId)
```
```javascript
// use in loaded callback
posthog.init('token', {
loaded: (posthog) => {
const id = posthog.get_distinct_id()
// use the ID
}
})
```
## Get feature flag
### `PostHog.getFeatureFlag`
> **getFeatureFlag**(`key`, `options?`): `string` | `boolean` | `undefined`
Gets the value of a feature flag for the current user.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | Key of the feature flag. |
| `options?` | `FeatureFlagOptions` | Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. |
#### Returns
`string` | `boolean` | `undefined`
The feature flag value, or undefined if the flag is unavailable.
#### Remarks
Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values. An evaluated boolean flag returns `true` or `false`; `undefined` means no current evaluation is available for the key. Globally inactive flags are omitted from the remote `/flags` response, so after that response loads they are unavailable rather than represented by a `false` result.
#### Examples
```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
}
```
## Get feature flag payload
### `PostHog.getFeatureFlagPayload`
> **getFeatureFlagPayload**(`key`): `JsonType`
Get feature flag payload value matching key for user (supports multivariate flags).
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | Key of the feature flag. |
#### Returns
`JsonType`
The feature flag payload.
#### Example
```javascript
const betaFeature = posthog.getFeatureFlagResult('beta-feature')
if (betaFeature?.variant === 'some-value') {
const someValue = betaFeature?.payload
// do something
}
```
#### Deprecated
Use `getFeatureFlagResult()` instead
## Get feature flag result
### `PostHog.getFeatureFlagResult`
> **getFeatureFlagResult**(`key`, `options?`): `FeatureFlagResult` | `undefined`
Get a feature flag evaluation result including both the flag value and payload.
A result with `enabled: false` is a conclusive off evaluation. `undefined` means no current evaluation is available for the key. This includes globally inactive flags, which are omitted from the remote `/flags` response.
By default, this method emits the `$feature_flag_called` event.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | Key of the feature flag. |
| `options?` | `FeatureFlagOptions` | Options for the feature flag lookup. |
#### Returns
`FeatureFlagResult` | `undefined`
The feature flag result including key, enabled, variant, and payload.
#### Examples
```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)
}
```
## Get feature flags
### `PostHog.getAllFeatureFlags`
> **getAllFeatureFlags**(): `FeatureFlagResult`\[\]
Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of the flags from the last load (no network request); call `reloadFeatureFlags()` first to refresh. Conclusive off evaluations are included with `enabled: false`; keys omitted from the response, including globally inactive flags, are absent. Unlike `getFeatureFlag()`, this method does not send a `$feature_flag_called` event.
#### Returns
`FeatureFlagResult`\[\]
All loaded flags, or an empty array if none are loaded.
## Get session ID
### `PostHog.get_session_id`
> **get\_session\_id**(): `string`
Returns the current session\_id.
#### Returns
`string`
The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.
#### Remarks
This should only be used for informative purposes. Any actual internal use case for the session\_id should be handled by the sessionManager.
### `PostHog.onSessionId`
> **onSessionId**(`callback?`): () => `void`
Register an event listener that runs whenever the session id or window id change. If there is already a session id, the listener is called immediately in addition to being called on future changes.
Can be used, for example, to sync the PostHog session id with a backend session.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `callback?` | `SessionIdChangedCallback` | The callback function will be called once a session id is present or when it or the window id are updated. |
#### Returns
A function that can be called to unsubscribe the listener. E.g. Used by `useEffect` when the component unmounts.
() => `void`
#### Example
```javascript
posthog.onSessionId(function(sessionId, windowId) { // do something })
```
## Group
### `PostHog.getGroups`
> **getGroups**(): `Record`<`string`, `any`\>
Returns the current groups.
#### Returns
`Record`<`string`, `any`\>
The current groups
### `PostHog.group`
> **group**(`groupType`, `groupKey`, `groupPropertiesToSet?`): `void`
Associates the user with a group for group-based analytics. Learn more about [groups](https://posthog.com/docs/product-analytics/group-analytics.md)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `groupType` | `string` | Group type (example: 'organization') |
| `groupKey` | `string` | Group key (example: 'org::5') |
| `groupPropertiesToSet?` | `Properties` | Optional properties to set for group |
#### Returns
`void`
#### Remarks
Groups allow you to analyze users collectively (e.g., by organization, team, or account). This sets the group association for all subsequent events and reloads feature flags.
#### Examples
```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.resetGroups`
> **resetGroups**(): `void`
Resets only the group properties of the user currently logged in. Learn more about [groups](https://posthog.com/docs/product-analytics/group-analytics.md)
#### Returns
`void`
#### Example
```javascript
posthog.resetGroups()
```
## Is feature enabled
### `PostHog.isFeatureEnabled`
> **isFeatureEnabled**(`key`, `options?`): `boolean`
Checks if a feature flag is enabled for the current user.
##### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | Key of the feature flag. |
| `options?` | `FeatureFlagOptions` & `object` & `object` | Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. If `{ defaultValue: false }`, we return that value instead of undefined when the flag has no value. |
##### Returns
`boolean`
Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
##### Remarks
Returns `true` or `false` when the flag has an evaluation value. A `false` result means the value evaluated off; it does not mean the SDK observed the flag's global active setting. Returns `undefined` when no current evaluation is available, unless `defaultValue` is given. Globally inactive flags are omitted from the remote `/flags` response and therefore have no value. This is a convenience method that treats any truthy value as enabled.
##### Examples
```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
}
```
#### Call Signature
> **isFeatureEnabled**(`key`, `options?`): `boolean` | `undefined`
Checks if a feature flag is enabled for the current user.
##### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | Key of the feature flag. |
| `options?` | `IsFeatureEnabledOptions` | Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. If `{ defaultValue: false }`, we return that value instead of undefined when the flag has no value. |
##### Returns
`boolean` | `undefined`
Whether the feature flag is enabled; when the flag has no value, defaultValue if given, otherwise undefined.
##### Remarks
Returns `true` or `false` when the flag has an evaluation value. A `false` result means the value evaluated off; it does not mean the SDK observed the flag's global active setting. Returns `undefined` when no current evaluation is available, unless `defaultValue` is given. Globally inactive flags are omitted from the remote `/flags` response and therefore have no value. This is a convenience method that treats any truthy value as enabled.
##### Examples
```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
}
```
## Is opt out
### `PostHog.has_opted_in_capturing`
> **has\_opted\_in\_capturing**(): `boolean`
Checks if the user has opted into data capturing.
#### Returns
`boolean`
current opt-in status
#### Remarks
Returns the current consent status for event tracking and data persistence.
#### Example
```javascript
if (posthog.has_opted_in_capturing()) {
// show analytics features
}
```
### `PostHog.has_opted_out_capturing`
> **has\_opted\_out\_capturing**(): `boolean`
Checks if the user has opted out of data capturing.
#### Returns
`boolean`
current opt-out status
#### Remarks
Returns the current consent status for event tracking and data persistence.
In cookieless `'always'` mode this returns `true`, because the SDK does not store data for the user. Events are still captured in this mode. To check if the SDK captures events, use `is_capturing()`.
#### Example
```javascript
if (posthog.has_opted_out_capturing()) {
// disable analytics features
}
```
### `PostHog.is_capturing`
> **is\_capturing**(): `boolean`
Checks whether the PostHog library is currently capturing events.
Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by some config options.
Additionally, if the cookieless\_mode is set to `'on_reject'`, we will capture events in cookieless mode if the user has opted out or been defaulted to opt-out.
#### Returns
`boolean`
whether the posthog library is capturing events
#### See
## Is session replay active
### `PostHog.sessionRecordingStarted`
> **sessionRecordingStarted**(): `boolean`
returns a boolean indicating whether session recording is currently running
#### Returns
`boolean`
Whether session recording is currently running.
#### Example
```javascript
// Stop session recording if it's running
if (posthog.sessionRecordingStarted()) {
posthog.stopSessionRecording()
}
```
## On feature flags
### `PostHog.onFeatureFlags`
> **onFeatureFlags**(`callback`): () => `void`
Register an event listener that runs when feature flags become available or when they change. If there are flags, the listener is called immediately in addition to being called on future changes. Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser, including when another open tab of your site stores new flags. Do not call `reloadFeatureFlags()` inside this callback: each reload in one tab triggers the callback in the other tabs, which can send flag requests in a loop.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `callback` | `FeatureFlagsCallback` | The callback function will be called once the feature flags are ready or when they are updated. It'll return a list of feature flags enabled for the user, the variants, and also a context object indicating whether we succeeded to fetch the flags or not. |
#### Returns
A function that can be called to unsubscribe the listener. Used by `useEffect` when the component unmounts.
() => `void`
#### Example
```javascript
posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
// do something
})
```
## Opt in
### `PostHog.clear_opt_in_out_capturing`
> **clear\_opt\_in\_out\_capturing**(): `void`
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
#### Returns
`void`
### `PostHog.opt_in_capturing`
> **opt\_in\_capturing**(`options?`): `void`
Opts the user into data capturing and persistence.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `options?` | { `captureEventName?`: `false` \| `EventName` \| `null`; `captureProperties?`: `Properties`; } | A dictionary of opt-in options. |
| `options.captureEventName?` | `false` \| `EventName` \| `null` | Event name to use for capturing the opt-in action. Set to `null` or `false` to skip capturing the opt-in event. Defaults to `$opt_in`. |
| `options.captureProperties?` | `Properties` | Set of properties to capture along with the opt-in action. |
#### Returns
`void`
#### Remarks
Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an `$opt_in` event unless disabled. The event is only captured when the user was not already opted in, so calling this on every page load (for example from a consent tool callback that re-applies stored consent) sends it once per user rather than once per page.
#### Examples
```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`
> **opt\_out\_capturing**(): `void`
Opts the user out of data capturing and persistence.
#### Returns
`void`
#### Remarks
Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance. If `opt_out_persistence_by_default` is true, SDK persistence will also be disabled.
#### Example
```javascript
// opt user out (e.g., on privacy settings page)
posthog.opt_out_capturing()
```
## Register
### `PostHog.get_property`
> **get\_property**(`property_name`): `any`
Returns the value of a super property. Returns undefined if the property doesn't exist.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `property_name` | `string` | The name of the super property you want to retrieve |
#### Returns
`any`
The stored property value, or undefined if it is not set.
#### Remarks
get\_property() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.
#### Example
```javascript
// grab value for '$user_id' after the posthog library has loaded
posthog.init('', {
loaded: function(posthog) {
user_id = posthog.get_property('$user_id');
}
});
```
### `PostHog.getSessionProperty`
> **getSessionProperty**(`property_name`): `any`
Returns the value of the session super property named property\_name. If no such property is set, getSessionProperty() will return the undefined value.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `property_name` | `string` | The name of the session super property you want to retrieve |
#### Returns
`any`
The stored session property value, or undefined if it is not set.
#### Remarks
This is based on browser-level `sessionStorage`, NOT the PostHog session. getSessionProperty() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.
#### Example
```javascript
// grab value for 'user_id' after the posthog library has loaded
posthog.init('YOUR PROJECT TOKEN', {
loaded: function(posthog) {
user_id = posthog.getSessionProperty('user_id');
}
});
```
### `PostHog.register`
> **register**(`properties`, `days?`): `void`
Registers super properties that are included with all events.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `properties` | `Properties` | properties to store about the user |
| `days?` | `number` | How many days since the user's last visit to store the super properties |
#### Returns
`void`
#### Remarks
Super properties are stored in persistence and automatically added to every event you capture. These values will overwrite any existing super properties with the same keys.
#### Examples
```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_for_session`
> **register\_for\_session**(`properties`): `void`
Registers super properties for the current session only.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `properties` | `Properties` | An associative array of properties to store about the user |
#### Returns
`void`
#### Remarks
Session super properties are automatically added to all events during the current browser session. Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage.
#### Examples
```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.register_once`
> **register\_once**(`properties`, `default_value?`, `days?`): `void`
Registers super properties only if they haven't been set before.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `properties` | `Properties` | An associative array of properties to store about the user |
| `default_value?` | `any` | Value to override if already set in super properties (ex: 'False') Default: 'None' |
| `days?` | `number` | How many days since the users last visit to store the super properties |
#### Returns
`void`
#### Remarks
Unlike `register()`, this method will not overwrite existing super properties. Use this for properties that should only be set once, like signup date or initial referrer.
#### Examples
```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'
)
```
## Reload feature flags
### `PostHog.reloadFeatureFlags`
> **reloadFeatureFlags**(): `void`
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
#### Returns
`void`
#### Example
```javascript
posthog.reloadFeatureFlags()
```
## Reset
### `PostHog.reset`
> **reset**(`options?`): `void`
Resets all user data and starts a fresh session.
⚠️ **Warning**: Only call this when a user logs out. Calling at the wrong time can cause split sessions.
This clears:
- Session ID and super properties
- User identification (sets new random distinct\_id)
- Cached data and consent settings
⚠️ **Warning**: because consent is cleared, `reset()` returns the instance to the default consent state. With `opt_out_capturing_by_default` that default is opted out, so calling `reset()` *after* `opt_in_capturing()` silently stops capturing. Always `reset()` first, then opt in.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `options?` | `boolean` \| `ResetOptions` | Boolean to reset the device ID (legacy), or reset options including bootstrap values. |
#### Returns
`void`
#### Examples
```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()
```
## Reset group properties for flags
### `PostHog.resetGroupPropertiesForFlags`
> **resetGroupPropertiesForFlags**(`group_type?`): `void`
Resets the group properties for feature flags.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `group_type?` | `string` | Optional group type to reset. If omitted, all group properties are reset. |
#### Returns
`void`
#### Example
```javascript
posthog.resetGroupPropertiesForFlags()
```
## Reset person properties for flags
### `PostHog.resetPersonPropertiesForFlags`
> **resetPersonPropertiesForFlags**(`reloadFeatureFlags?`): `void`
Resets the person properties for feature flags.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags. |
#### Returns
`void`
#### Examples
```javascript
posthog.resetPersonPropertiesForFlags()
```
```javascript
// Reset properties without reloading
posthog.resetPersonPropertiesForFlags(false)
```
## Set group properties for flags
### `PostHog.setGroupPropertiesForFlags`
> **setGroupPropertiesForFlags**(`properties`, `reloadFeatureFlags?`): `void`
Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `properties` | {\[`type`: `string`\]: `Properties`; } | `undefined` | The properties to override, the key of which is the group type. |
| `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags. |
#### Returns
`void`
#### Examples
```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)
```
## Set person properties
### `PostHog.setInternalOrTestUser`
> **setInternalOrTestUser**(): `void`
Marks the current user as a test user by setting the `$internal_or_test_user` person property to `true`. This also enables person processing for the current user.
This is useful for using in a cohort your internal/test filters for your posthog org.
#### Returns
`void`
#### See
[https://posthog.com/tutorials/filter-internal-users](https://posthog.com/tutorials/filter-internal-users) Create a cohort with `$internal_or_test_user` IS SET, and set your internal test filters to be NOT IN that cohort.
#### Example
```javascript
// Manually mark as test user
posthog.setInternalOrTestUser()
// Or use internal_or_test_user_hostname config for automatic detection
posthog.init('token', { internal_or_test_user_hostname: 'localhost' })
```
### `PostHog.setPersonProperties`
> **setPersonProperties**(`userPropertiesToSet?`, `userPropertiesToSetOnce?`): `void`
Sets properties on the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify.md)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `userPropertiesToSet?` | `Properties` | Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet. |
| `userPropertiesToSetOnce?` | `Properties` | Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. |
#### Returns
`void`
#### Remarks
Updates user properties that are stored with the person profile in PostHog. If `person_profiles` is set to `identified_only` and no profile exists, this will create one.
#### Examples
```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`
> **unsetPersonProperties**(`propertyNames`): `void`
Removes properties from the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify.md)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `propertyNames` | `string` \| `string`\[\] | The name (or names) of the person properties to remove. |
#### Returns
`void`
#### Remarks
Deletes the given person properties from the person profile in PostHog. This is the counterpart to setPersonProperties — instead of hand-passing `$unset` inside a `capture()` call, you can remove properties with a dedicated method. If `person_profiles` is set to `never`, this call is ignored.
`$fbc` and `$fbp` read by the SDK are unset for this call only. `save_campaign_params: false` stops the reads.
#### Examples
```javascript
// remove a single property
posthog.unsetPersonProperties('plan')
```
```javascript
// remove multiple properties
posthog.unsetPersonProperties(['plan', 'email'])
```
## Set person properties for flags
### `PostHog.setPersonPropertiesForFlags`
> **setPersonPropertiesForFlags**(`properties`, `reloadFeatureFlags?`): `void`
Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `properties` | `Properties` | `undefined` | The properties to override. |
| `reloadFeatureFlags?` | `boolean` | `true` | Whether to reload feature flags. |
#### Returns
`void`
#### Examples
```javascript
// Set properties
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})
```
```javascript
// Set properties without reloading
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)
```
## Shutdown
### `PostHog.shutdown`
> **shutdown**(`_shutdownTimeoutMs?`): `Promise`<`void`\>
Flushes any queued events and resolves once teardown is complete.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `_shutdownTimeoutMs?` | `number` | Retained for parity with the Node.js SDK; ignored in browsers. |
#### Returns
`Promise`<`void`\>
A promise that resolves once best-effort cleanup and queue flushing complete.
#### Remarks
This exists primarily for parity with the server-side [Node.js SDK](https://posthog.com/docs/libraries/node.md), 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()
```
## Start session recording
### `PostHog.startSessionRecording`
> **startSessionRecording**(`override?`): `void`
turns session recording on, and updates the config option `disable_session_recording` to false
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `override?` | `true` \| { `event_trigger?`: `true`; `linked_flag?`: `boolean`; `sampling?`: `boolean`; `url_trigger?`: `true`; } | optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked\_flag config. `true` is shorthand for { sampling: true, linked\_flag: true } |
#### Returns
`void`
#### Examples
```javascript
// Start and ignore controls
posthog.startSessionRecording(true)
```
```javascript
// Start and override controls
posthog.startSessionRecording({
// you don't have to send all of these
sampling: true || false,
linked_flag: true || false,
url_trigger: true || false,
event_trigger: true || false
})
```
## Stop session recording
### `PostHog.stopSessionRecording`
> **stopSessionRecording**(): `void`
turns session recording off, and updates the config option disable\_session\_recording to true
#### Returns
`void`
#### Example
```javascript
// Stop session recording
posthog.stopSessionRecording()
```
## Unregister
### `PostHog.unregister`
> **unregister**(`property`): `void`
Removes a super property from persistent storage.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `property` | `string` | The name of the super property to remove |
#### Returns
`void`
#### Remarks
This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile.
#### Example
```javascript
// remove a super property
posthog.unregister('plan_type')
```
### `PostHog.unregister_for_session`
> **unregister\_for\_session**(`property`): `void`
Removes a session super property from the current session.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `property` | `string` | The name of the session super property to remove |
#### Returns
`void`
#### Remarks
This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.
#### Example
```javascript
// remove a session property
posthog.unregister_for_session('current_flow')
```
## Consent gating
### `PostHog.get_explicit_consent_status`
> **get\_explicit\_consent\_status**(): `"pending"` | `"granted"` | `"denied"`
Returns the explicit consent status of the user.
#### Returns
`"pending"` | `"granted"` | `"denied"`
The current explicit consent status.
#### Remarks
This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not take the default config options into account, only whether the user has made an explicit choice, so this can be used to determine whether to show an initial cookie banner or not.
#### Example
```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
}
```
## Surveys
### `PostHog.cancelPendingSurvey`
> **cancelPendingSurvey**(`surveyId`): `void`
Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `surveyId` | `string` | The survey ID whose pending display should be cancelled. |
#### Returns
`void`
### `PostHog.canRenderSurvey`
> **canRenderSurvey**(`surveyId`): `SurveyRenderReason` | `null`
Checks the feature flags associated with this Survey to see if the survey can be rendered. This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded. Use `canRenderSurveyAsync` instead.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `surveyId` | `string` | The ID of the survey to check. |
#### Returns
`SurveyRenderReason` | `null`
A SurveyRenderReason object indicating if the survey can be rendered.
#### Deprecated
### `PostHog.canRenderSurveyAsync`
> **canRenderSurveyAsync**(`surveyId`, `forceReload?`): `Promise`<`SurveyRenderReason`\>
Checks the feature flags associated with this Survey to see if the survey can be rendered.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `surveyId` | `string` | `undefined` | The ID of the survey to check. |
| `forceReload?` | `boolean` | `false` | If true, the survey will be reloaded from the server, Default: false |
#### Returns
`Promise`<`SurveyRenderReason`\>
A SurveyRenderReason object indicating if the survey can be rendered.
#### Example
```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.displaySurvey`
> **displaySurvey**(`surveyId`, `options?`): `void`
Display a survey programmatically as either a popover or inline element.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `surveyId` | `string` | `undefined` | The survey ID to display. |
| `options?` | `DisplaySurveyOptions` | `DEFAULT_DISPLAY_SURVEY_OPTIONS` | Display configuration. Defaults to a popover that respects dashboard conditions and delays. |
#### Returns
`void`
#### Examples
```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`
> **getActiveMatchingSurveys**(`callback`, `forceReload?`): `void`
Get surveys that should be enabled for the current user. See [fetching surveys documentation](https://posthog.com/docs/surveys/implementing-custom-surveys.md#fetching-surveys-manually) for more details.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `callback` | `SurveyCallback` | `undefined` | The callback function will be called when the surveys are loaded or updated. |
| `forceReload?` | `boolean` | `false` | Whether to force a reload of the surveys. |
#### Returns
`void`
#### Example
```javascript
posthog.getActiveMatchingSurveys((surveys) => {
// do something
})
```
### `PostHog.getSurveys`
> **getSurveys**(`callback`, `forceReload?`): `void`
Get list of all surveys.
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `callback` | `SurveyCallback` | `undefined` | Function that receives the array of surveys. |
| `forceReload?` | `boolean` | `false` | Optional boolean to force an API call for updated surveys. |
#### Returns
`void`
#### Example
```javascript
function callback(surveys, context) {
// do something
}
posthog.getSurveys(callback, false)
```
### `PostHog.onActiveMatchingSurveysChanged`
> **onActiveMatchingSurveysChanged**(`callback`): () => `void`
Register an event listener that runs when the set of active matching surveys changes. The listener receives the initial matching set and updates after event/action triggers, cancellation, consumption, session expiry, definitions refresh, captured pageviews, feature-flag updates, marking a survey as seen, and reset. Unchanged results are suppressed.
URL conditions are re-evaluated on captured `$pageview` events, including automatic SPA pageviews when `capture_pageview` is `'history_change'`. With automatic pageviews disabled, capture `$pageview` after navigation. This does not observe arbitrary DOM mutations or time passing; selector, device and wait-period conditions are checked on the supported updates.
The optional callback context distinguishes load errors from a successfully loaded empty result. New subscribers receive the current snapshot without replaying earlier errors: a settled unavailable state is `([], { isLoaded: false })`, while usable cached definitions are evaluated normally. An initial load already in progress delivers when it resolves. Recoverable load failures keep the subscription alive. Unsubscribing prevents any further delivery, including callbacks from an outstanding initial request.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `callback` | `SurveyCallback` | The callback to call with active matching surveys. |
#### Returns
A function that can be called to unsubscribe the listener.
() => `void`
#### Example
```javascript
const unsubscribe = posthog.onActiveMatchingSurveysChanged((surveys) => {
// respond to changes in currently matching surveys
})
```
### `PostHog.onSurveysLoaded`
> **onSurveysLoaded**(`callback`): () => `void`
Register an event listener that runs when surveys are loaded.
Callback parameters:
- surveys: Survey\[\]: An array containing all survey objects fetched from PostHog using the getSurveys method
- context: { isLoaded: boolean, error?: string }: An object indicating if the surveys were loaded successfully
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `callback` | `SurveyCallback` | The callback function will be called when surveys are loaded or updated. |
#### Returns
A function that can be called to unsubscribe the listener.
() => `void`
#### Example
```javascript
posthog.onSurveysLoaded((surveys, context) => { // do something })
```
### `PostHog.renderSurvey`
> **renderSurvey**(`surveyId`, `selector`): `void`
Although we recommend using popover surveys and display conditions, if you want to show surveys programmatically without setting up all the extra logic needed for API surveys, you can render surveys programmatically with the renderSurvey method.
This takes a survey ID and an HTML selector to render an unstyled survey.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `surveyId` | `string` | The ID of the survey to render. |
| `selector` | `string` | The selector of the HTML element to render the survey on. |
#### Returns
`void`
#### Example
```javascript
posthog.renderSurvey(coolSurveyID, '#survey-container')
```
#### Deprecated
Use displaySurvey instead - it's more complete and also supports popover surveys.
### `DisplaySurveyType`
> `const` **DisplaySurveyType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Inline` | `"inline"` |
| `Popover` | `"popover"` |
### `SurveyEventName`
> `const` **SurveyEventName**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `ABANDONED` | `"survey abandoned"` |
| `DISMISSED` | `"survey dismissed"` |
| `SENT` | `"survey sent"` |
| `SHOWN` | `"survey shown"` |
### `SurveyEventProperties`
> `const` **SurveyEventProperties**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `PRODUCT_TOUR_ID` | `"$product_tour_id"` |
| `SURVEY_COMPLETED` | `"$survey_completed"` |
| `SURVEY_ID` | `"$survey_id"` |
| `SURVEY_ITERATION` | `"$survey_iteration"` |
| `SURVEY_ITERATION_START_DATE` | `"$survey_iteration_start_date"` |
| `SURVEY_LANGUAGE` | `"$survey_language"` |
| `SURVEY_LAST_SEEN_DATE` | `"$survey_last_seen_date"` |
| `SURVEY_NAME` | `"$survey_name"` |
| `SURVEY_PARTIALLY_COMPLETED` | `"$survey_partially_completed"` |
| `SURVEY_QUESTIONS` | `"$survey_questions"` |
| `SURVEY_RESPONSE` | `"$survey_response"` |
| `SURVEY_SUBMISSION_ID` | `"$survey_submission_id"` |
### `SurveyEventType`
> `const` **SurveyEventType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Activation` | `"events"` |
| `Cancellation` | `"cancelEvents"` |
### `SurveyPosition`
> `const` **SurveyPosition**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Center` | `"center"` |
| `Left` | `"left"` |
| `MiddleCenter` | `"middle_center"` |
| `MiddleLeft` | `"middle_left"` |
| `MiddleRight` | `"middle_right"` |
| `NextToTrigger` | `"next_to_trigger"` |
| `Right` | `"right"` |
| `TopCenter` | `"top_center"` |
| `TopLeft` | `"top_left"` |
| `TopRight` | `"top_right"` |
### `SurveyQuestionBranchingType`
> `const` **SurveyQuestionBranchingType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `End` | `"end"` |
| `NextQuestion` | `"next_question"` |
| `ResponseBased` | `"response_based"` |
| `SpecificQuestion` | `"specific_question"` |
### `SurveyQuestionType`
> `const` **SurveyQuestionType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Link` | `"link"` |
| `MultipleChoice` | `"multiple_choice"` |
| `Open` | `"open"` |
| `Rating` | `"rating"` |
| `SingleChoice` | `"single_choice"` |
### `SurveySchedule`
> `const` **SurveySchedule**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Always` | `"always"` |
| `Once` | `"once"` |
| `Recurring` | `"recurring"` |
### `SurveyTabPosition`
> `const` **SurveyTabPosition**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Bottom` | `"bottom"` |
| `Left` | `"left"` |
| `Right` | `"right"` |
| `Top` | `"top"` |
### `SurveyType`
> `const` **SurveyType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `API` | `"api"` |
| `ExternalSurvey` | `"external_survey"` |
| `Popover` | `"popover"` |
| `Widget` | `"widget"` |
### `SurveyWidgetType`
> `const` **SurveyWidgetType**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Button` | `"button"` |
| `Selector` | `"selector"` |
| `Tab` | `"tab"` |
## SDK utils
### `PostHog.featureFlags`
> **featureFlags**: `TreeShakeable`<`PostHogFeatureFlags`\>
The feature flags instance. Provides access to feature flag override methods.
### `PostHog.version`
> **version**: `string` = `Config.LIB_VERSION`
The library version.
### `PostHog.flagsEndpointWasHit`
> **get** **flagsEndpointWasHit**(): `boolean`
Whether feature flags have been initialized for this instance.
##### Remarks
Despite the name, this is a proxy for processed feature flag values. It may be true for bootstrapped flags before a network request completes.
##### Returns
`boolean`
True once the SDK has processed feature flag values.
### `PostHog.get_session_replay_url`
> **get\_session\_replay\_url**(`options?`): `string`
Returns the Replay url for the current session.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `options?` | { `timestampLookBack?`: `number`; `withTimestamp?`: `boolean`; } | Options for the URL. |
| `options.timestampLookBack?` | `number` | How many seconds to look back for the timestamp. |
| `options.withTimestamp?` | `boolean` | Whether to include the timestamp in the URL. |
#### Returns
`string`
The URL for the current session replay, or an empty string if sessions are unavailable.
#### Examples
```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.getEarlyAccessFeatures`
> **getEarlyAccessFeatures**(`callback`, `force_reload?`, `stages?`): `void`
Get the list of early access features. To check enrollment status, use `isFeatureEnabled`. [Learn more in the docs](https://posthog.com/docs/feature-flags/early-access-feature-management.md#option-2-custom-implementation)
#### Parameters
| Parameter | Type | Default value | Description |
| --- | --- | --- | --- |
| `callback` | `EarlyAccessFeatureCallback` | `undefined` | The callback function will be called when the early access features are loaded. |
| `force_reload?` | `boolean` | `false` | Whether to force a reload of the early access features. |
| `stages?` | `EarlyAccessFeatureStage`\[\] | `undefined` | The stages of the early access features to load. |
#### Returns
`void`
#### Example
```javascript
const posthog = usePostHog()
const activeFlags = useActiveFeatureFlags()
const [activeBetas, setActiveBetas] = useState([])
const [inactiveBetas, setInactiveBetas] = useState([])
const [comingSoonFeatures, setComingSoonFeatures] = useState([])
useEffect(() => {
posthog.getEarlyAccessFeatures((features) => {
// Filter features by stage
const betaFeatures = features.filter(feature => feature.stage === 'beta')
const conceptFeatures = features.filter(feature => feature.stage === 'concept')
setComingSoonFeatures(conceptFeatures)
if (!activeFlags || activeFlags.length === 0) {
setInactiveBetas(betaFeatures)
return
}
const activeBetas = betaFeatures.filter(
beta => activeFlags.includes(beta.flagKey)
);
const inactiveBetas = betaFeatures.filter(
beta => !activeFlags.includes(beta.flagKey)
);
setActiveBetas(activeBetas)
setInactiveBetas(inactiveBetas)
}, true, ['concept', 'beta'])
}, [activeFlags])
```
### `PostHog.getPageViewId`
> **getPageViewId**(): `string` | `undefined`
Returns the current page view ID.
#### Returns
`string` | `undefined`
The current page view ID, or undefined if no page view has been captured.
### `PostHog.loadToolbar`
> **loadToolbar**(`params`): `boolean`
returns a boolean indicating whether the [toolbar](https://posthog.com/docs/toolbar.md) loaded
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `params` | `ToolbarParams` | Toolbar parameters. |
#### Returns
`boolean`
Whether the toolbar loaded.
### `PostHog.on`
> **on**(`event`, `cb`): () => `void`
Exposes a set of events that PostHog will emit. e.g. `eventCaptured` is emitted immediately before trying to send an event
Unlike `onFeatureFlags` and `onSessionId` these are not called when the listener is registered, the first callback will be the next event *after* registering a listener
Available events:
- `eventCaptured`: Emitted immediately before trying to send an event
- `featureFlagsReloading`: Emitted when feature flags are being reloaded (e.g. after `identify()`, `group()`, or `reloadFeatureFlags()`)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `event` | `"eventCaptured"` \| `"featureFlagsReloading"` | The event to listen for. |
| `cb` | (...`args`) => `void` | The callback function to call when the event is emitted. |
#### Returns
A function that can be called to unsubscribe the listener.
() => `void`
#### Examples
```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.updateEarlyAccessFeatureEnrollment`
> **updateEarlyAccessFeatureEnrollment**(`key`, `isEnrolled`, `stage?`): `void`
Opt the user in or out of an early access feature. [Learn more in the docs](https://posthog.com/docs/feature-flags/early-access-feature-management.md#option-2-custom-implementation)
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `key` | `string` | The key of the feature flag to update. |
| `isEnrolled` | `boolean` | Whether the user is enrolled in the feature. |
| `stage?` | `string` | The stage of the feature flag to update. |
#### Returns
`void`
#### Example
```javascript
const toggleBeta = (betaKey) => {
if (activeBetas.some(
beta => beta.flagKey === betaKey
)) {
posthog.updateEarlyAccessFeatureEnrollment(
betaKey,
false
)
setActiveBetas(
prevActiveBetas => prevActiveBetas.filter(
item => item.flagKey !== betaKey
)
);
return
}
posthog.updateEarlyAccessFeatureEnrollment(
betaKey,
true
)
setInactiveBetas(
prevInactiveBetas => prevInactiveBetas.filter(
item => item.flagKey !== betaKey
)
);
}
const registerInterest = (featureKey) => {
posthog.updateEarlyAccessFeatureEnrollment(
featureKey,
true
)
// Update UI to show user has registered
}
```
### `PostHog.updateFlags`
> **updateFlags**(`flags`, `payloads?`, `options?`): `void`
Manually update feature flag values without making a network request.
This is useful when you have feature flag values from an external source (e.g., server-side evaluation, edge middleware) and want to inject them into the client SDK.
#### Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| `flags` | `Record`<`string`, `boolean` \| `string`\> | An object mapping flag keys to their values (boolean or string variant) |
| `payloads?` | `Record`<`string`, `JsonType`\> | Optional object mapping flag keys to their JSON payloads |
| `options?` | { `merge?`: `boolean`; } | Optional settings. Use `{ merge: true }` to merge with existing flags instead of replacing. |
| `options.merge?` | `boolean` | \- |
#### Returns
`void`
#### Example
```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' } }
)
```
### `Compression`
> `const` **Compression**: `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `Base64` | `"base64"` |
| `GZipJS` | `"gzip-js"` |
### `DEFAULT_PRODUCT_TOUR_APPEARANCE`
> `const` **DEFAULT\_PRODUCT\_TOUR\_APPEARANCE**: `Required`<`ProductTourAppearance`\>
### `ProductTourEventName`
> `const` **ProductTourEventName**: `object`
#### Type Declaration
| Name | Type | Default value |
| --- | --- | --- |
| `BANNER_ACTION_CLICKED` | `"product tour banner action clicked"` | `'product tour banner action clicked'` |
| `BANNER_CONTAINER_SELECTOR_FAILED` | `"product tour banner container selector failed"` | `'product tour banner container selector failed'` |
| `BUTTON_CLICKED` | `"product tour button clicked"` | `'product tour button clicked'` |
| `COMPLETED` | `"product tour completed"` | `'product tour completed'` |
| `DISMISSED` | `"product tour dismissed"` | `'product tour dismissed'` |
| `SHOWN` | `"product tour shown"` | `'product tour shown'` |
| `STEP_COMPLETED` | `"product tour step completed"` | `'product tour step completed'` |
| `STEP_SELECTOR_FAILED` | `"product tour step selector failed"` | `'product tour step selector failed'` |
| `STEP_SHOWN` | `"product tour step shown"` | `'product tour step shown'` |
### `ProductTourEventProperties`
> `const` **ProductTourEventProperties**: `object`
#### Type Declaration
| Name | Type | Default value |
| --- | --- | --- |
| `INFERENCE_DATA_PRESENT` | `"$inference_data_present"` | `'$inference_data_present'` |
| `TOUR_BANNER_SELECTOR` | `"$product_tour_banner_selector"` | `'$product_tour_banner_selector'` |
| `TOUR_BUTTON_ACTION` | `"$product_tour_button_action"` | `'$product_tour_button_action'` |
| `TOUR_BUTTON_LINK` | `"$product_tour_button_link"` | `'$product_tour_button_link'` |
| `TOUR_BUTTON_TEXT` | `"$product_tour_button_text"` | `'$product_tour_button_text'` |
| `TOUR_BUTTON_TOUR_ID` | `"$product_tour_button_tour_id"` | `'$product_tour_button_tour_id'` |
| `TOUR_DISMISS_REASON` | `"$product_tour_dismiss_reason"` | `'$product_tour_dismiss_reason'` |
| `TOUR_ERROR` | `"$product_tour_error"` | `'$product_tour_error'` |
| `TOUR_FAILURE_PHASE` | `"$product_tour_failure_phase"` | `'$product_tour_failure_phase'` |
| `TOUR_ID` | `"$product_tour_id"` | `'$product_tour_id'` |
| `TOUR_ITERATION` | `"$product_tour_iteration"` | `'$product_tour_iteration'` |
| `TOUR_LAST_SEEN_DATE` | `"$product_tour_last_seen_date"` | `'$product_tour_last_seen_date'` |
| `TOUR_LINKED_SURVEY_ID` | `"$product_tour_linked_survey_id"` | `'$product_tour_linked_survey_id'` |
| `TOUR_MATCHES_COUNT` | `"$product_tour_matches_count"` | `'$product_tour_matches_count'` |
| `TOUR_NAME` | `"$product_tour_name"` | `'$product_tour_name'` |
| `TOUR_RENDER_REASON` | `"$product_tour_render_reason"` | `'$product_tour_render_reason'` |
| `TOUR_STEP_ELEMENT_CLASSES` | `"$product_tour_step_element_classes"` | `'$product_tour_step_element_classes'` |
| `TOUR_STEP_ELEMENT_ID` | `"$product_tour_step_element_id"` | `'$product_tour_step_element_id'` |
| `TOUR_STEP_ELEMENT_TAG` | `"$product_tour_step_element_tag"` | `'$product_tour_step_element_tag'` |
| `TOUR_STEP_ELEMENT_TEXT` | `"$product_tour_step_element_text"` | `'$product_tour_step_element_text'` |
| `TOUR_STEP_ID` | `"$product_tour_step_id"` | `'$product_tour_step_id'` |
| `TOUR_STEP_ORDER` | `"$product_tour_step_order"` | `'$product_tour_step_order'` |
| `TOUR_STEP_SELECTOR` | `"$product_tour_step_selector"` | `'$product_tour_step_selector'` |
| `TOUR_STEP_SELECTOR_FOUND` | `"$product_tour_step_selector_found"` | `'$product_tour_step_selector_found'` |
| `TOUR_STEP_TYPE` | `"$product_tour_step_type"` | `'$product_tour_step_type'` |
| `TOUR_STEPS_COUNT` | `"$product_tour_steps_count"` | `'$product_tour_steps_count'` |
| `TOUR_TYPE` | `"$product_tour_type"` | `'$product_tour_type'` |
| `TOUR_WAIT_DURATION_MS` | `"$product_tour_wait_duration_ms"` | `'$product_tour_wait_duration_ms'` |
| `TOUR_WAITED_FOR_ELEMENT` | `"$product_tour_waited_for_element"` | `'$product_tour_waited_for_element'` |
| `USE_MANUAL_SELECTOR` | `"$use_manual_selector"` | `'$use_manual_selector'` |
### `severityLevels`
> `const` **severityLevels**: readonly \[`"fatal"`, `"error"`, `"warning"`, `"log"`, `"info"`, `"debug"`\]
## Types
### `ActionStepStringMatching`
> **ActionStepStringMatching** = `"contains"` | `"exact"` | `"regex"`
Sync with plugin-server/src/types.ts.
### `ActionStepType`
| Property | Type | Description |
| --- | --- | --- |
| `event?` | `string` \| `null` | \- |
| `href?` | `string` \| `null` | \- |
| `href_matching?` | `ActionStepStringMatching` \| `null` | **Default** `StringMatching.Exact` |
| `properties?` | `object`\[\] | Property filters for action step matching. |
| `selector?` | `string` \| `null` | \- |
| `selector_regex?` | `string` \| `null` | Pre-compiled regex pattern for matching selector against `$elements_chain`. |
| `tag_name?` | `string` | **Deprecated** Only `selector` should be used now. |
| `text?` | `string` \| `null` | \- |
| `text_matching?` | `ActionStepStringMatching` \| `null` | **Default** `StringMatching.Exact` |
| `url?` | `string` \| `null` | \- |
| `url_matching?` | `ActionStepStringMatching` \| `null` | **Default** `StringMatching.Contains` |
### `ApiResponse`
A minimal response from Client.sendRequest.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `error?` | `unknown` | The transport error when the request failed before receiving an HTTP response. |
| `json?` | `unknown` | The response body parsed as JSON when available. |
| `statusCode` | `number` | The HTTP status code returned by the transport, or a client-defined best-effort status for sendBeacon sends. |
| `text?` | `string` | The response body as text when available. |
### `AutocaptureCompatibleElement`
> **AutocaptureCompatibleElement** = `"a"` | `"button"` | `"form"` | `"input"` | `"select"` | `"textarea"` | `"label"`
### `AutocaptureConfig`
If an array is passed for an allowlist, autocapture events will only be sent for elements matching at least one of the elements in the array. Multiple allowlists can be used
#### Extended by
- `AutocaptureConfig`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `capture_copied_text?` | `boolean` | When true, autocapture captures cut, copy, and paste interactions. Paste events do not contain pasted text. |
| `capture_value_css_selector_allowlist?` | `string`\[\] \| ((`element`) => `boolean`) | CSS selectors or a predicate opting individual native fields into value capture on change events. Selectors match the field itself, not its ancestors. An empty array disables value capture. String values are sent in $input\_value and may be edited in before\_send. Values are not automatically redacted; only opt in fields whose contents you intend to collect. Password fields, no-capture markers, sensitive-field exclusions, and mask\_all\_text still apply. **Default** `['[data-ph-capture-value]']` |
| `css_selector_allowlist?` | `string`\[\] | List of CSS selectors to allow autocapture on e.g. \['\[ph-capture\]'\] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and allow list config `['[id]']` we will capture the click if the click-target or its parents has any id Everything is allowed when there's no allowlist |
| `css_selector_ignorelist?` | `string`\[\] | List of CSS selectors to ignore autocapture on e.g. \['\[data-ph-no-autocapture\]'\] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > button > svg and ignore list config `['[id]']` we will ignore the click if the click-target or its parents has any id Nothing is ignored when there's an empty ignorelist, e.g. \[\] If no ignorelist is set, we default to ignoring .ph-no-autocapture and \[data-ph-no-autocapture\] Note: providing any custom list fully replaces the defaults — include .ph-no-autocapture and \[data-ph-no-autocapture\] explicitly if you still want them honoured. |
| `dom_event_allowlist?` | `DomAutocaptureEvents`\[\] | List of DOM events to allow autocapture on e.g. \['click', 'change', 'submit'\] |
| `element_allowlist?` | `AutocaptureCompatibleElement`\[\] | List of DOM elements to allow autocapture on e.g. \['a', 'button', 'form', 'input', 'select', 'textarea', 'label'\] We consider the tree of elements from the root to the target element of the click event so for the tree `div > div > button > svg` if the allowlist has `button` then we allow the capture when the `button` or the `svg` is the click target but not if either of the `div`s 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](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](https://example.com)', 'test.com/.\*'\] this is useful when you want to autocapture on most pages but not some specific ones if you set both url\_allowlist and url\_ignorelist, we check the allowlist first and then the ignorelist. the ignorelist can override the allowlist |
### `BasicSurveyQuestion`
- `SurveyQuestionBase`
#### Properties
| Property | Type | Inherited from |
| --- | --- | --- |
| `branching?` | `NextQuestionBranching` \| `EndBranching` \| `ResponseBasedBranching` \| `SpecificQuestionBranching` | `SurveyQuestionBase`.`branching` |
| `buttonText?` | `string` | `SurveyQuestionBase`.`buttonText` |
| `description?` | `string` \| `null` | `SurveyQuestionBase`.`description` |
| `descriptionContentType?` | `SurveyQuestionDescriptionContentType` | `SurveyQuestionBase`.`descriptionContentType` |
| `id?` | `string` | `SurveyQuestionBase`.`id` |
| `optional?` | `boolean` | `SurveyQuestionBase`.`optional` |
| `question` | `string` | `SurveyQuestionBase`.`question` |
| `translations?` | `Record`<`string`, `SurveyQuestionTranslation`\> | `SurveyQuestionBase`.`translations` |
| `type` | `"open"` | \- |
| `validation?` | `SurveyValidationRule`\[\] | `SurveyQuestionBase`.`validation` |
### `BeforeSendFn`
> **BeforeSendFn** = (`cr`) => `CaptureResult` | `null`
#### Parameters
| Parameter | Type |
| --- | --- |
| `cr` | `CaptureResult` |
#### Returns
`CaptureResult` | `null`
### `BeforeSendLogFn`
> **BeforeSendLogFn** = (`record`) => `CaptureLogOptions` | `null`
Pre-send filter. Inspect, mutate, or drop a captured log record before it enters the rate cap or the buffer. Return the (possibly transformed) record to keep it; return `null` to drop it.
Configure as a single function or an array. Arrays form a left-to-right chain: each function receives the previous function's return value, and a `null` from any link short-circuits the chain and drops the record. A function that throws also drops the record (the error is logged).
#### Parameters
| Parameter | Type |
| --- | --- |
| `record` | `CaptureLogOptions` |
#### Returns
`CaptureLogOptions` | `null`
#### Example
**Redact secrets from log bodies**
```typescript
logs: { beforeSend: (record) => ({ ...record, body: record.body.replace(/token=\S+/g, 'token=[REDACTED]') }) }
```
### `BeforeSendMetricFn`
> **BeforeSendMetricFn** = (`sample`) => `MetricSample` | `null`
Pre-aggregation filter. Return the (possibly transformed) sample to keep it; return `null` to drop it. Configure as a single function or an array forming a left-to-right chain; a `null` from any link drops the sample and a thrown error also drops it (the error is logged).
#### Parameters
| Parameter | Type |
| --- | --- |
| `sample` | `MetricSample` |
#### Returns
`MetricSample` | `null`
#### Example
**Drop debug metrics in production**
```typescript
metrics: { beforeSend: (m) => (m.name.startsWith('debug_') ? null : m) }
```
### `BootstrapConfig`
| Property | Type | Description |
| --- | --- | --- |
| `distinctID?` | `string` \| `null` | Distinct ID to use before the SDK has loaded persisted identity. |
| `featureFlagPayloads?` | `Record`<`string`, `JsonType`\> \| `null` | Feature flag payloads to use together with bootstrapped `featureFlags`. |
| `featureFlags?` | `Record`<`string`, `string` \| `boolean`\> \| `null` | Feature flag values to use immediately until the SDK fetches fresh values. |
| `isIdentifiedID?` | `boolean` \| `null` | Whether `distinctID` already identifies a known person profile. |
| `sessionID?` | `string` \| `null` | Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be: - unique to this user - a valid UUID v7 - the timestamp part must be <= the timestamp of the first event in the session - the timestamp of the last event in the session must be < the timestamp part + 24 hours |
### `BrowserMetricsConfig`
Metrics configuration options for the browser SDK. Adds the options that only the browser SDK implements to the shared metrics options.
#### Extends
- `MetricsConfig`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `beforeSend?` | `BeforeSendMetricFn` \| `BeforeSendMetricFn`\[\] | Pre-aggregation filter for metric samples, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a sample (return `null` to drop) before it is aggregated. | `MetricsConfig`.`beforeSend` |
| `environment?` | `string` | The deployment environment for metric series (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. | `MetricsConfig`.`environment` |
| `flags?` | `boolean` | **`Experimental`** EXPERIMENTAL: Record the round trip of every `/flags` HTTP attempt as the histogram `posthog.flags.request.duration`, in milliseconds. Each retry is a separate sample. The timer starts when the SDK hands the request to the transport, so the duration includes compressing the request body. Samples carry the server host, the response status or error type, and the browser's IANA timezone as `client.timezone`. Requests that the SDK drops before they reach the network are not recorded. An attempt that gets a response also splits that duration into three histograms with the same attributes: `posthog.flags.request.pre_send_duration` (until the request starts), `posthog.flags.request.network_duration` (until the last byte of the response arrives, from the request's Resource Timing entry) and `posthog.flags.request.main_thread_duration` (until the SDK's callback runs). The attempt records them only when the browser reports a Resource Timing entry within 5 seconds of the callback that no other `/flags` request from this copy of the SDK to the same URL can own. This option, the metric names, and their attributes may change or be removed in any release. **Default** `undefined @experimental` | \- |
| `flushIntervalMs?` | `number` | How often the aggregated window is flushed, in milliseconds. Samples are folded into per-series aggregates in memory between flushes — one data point per series per window, no matter how many calls. The browser SDK defaults to 60000: every tab of an app writes to the same series, so a longer window keeps busy series under the backend's per-series point limit. **Default** `10000 (60000 in the browser)` | `MetricsConfig`.`flushIntervalMs` |
| `maxSeriesPerFlush?` | `number` | Cardinality guardrail: maximum distinct series (name + type + unit + attribute combination) held per flush window. Samples for series beyond the cap are dropped with a single warning per window. **Default** `1000` | `MetricsConfig`.`maxSeriesPerFlush` |
| `network?` | `boolean` \| `NetworkMetricsConfig` | Record the duration of every HTTP or HTTPS `fetch` and `XMLHttpRequest` as a histogram. `true` uses the defaults. Requests to PostHog itself, URLs with other protocols, and server-sent event streams (`text/event-stream` responses) are not recorded. Long-polling requests look like ordinary requests; skip them with a `name` function that returns `null`. Each transport is measured to the boundary its API exposes: a `fetch` to its response headers, an `XMLHttpRequest` to the end of its response body. **Default** `undefined` | \- |
| `resourceAttributes?` | `MetricAttributes` | Additional resource attributes applied to every metrics batch. These describe the service/deployment, not individual series. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. **Example** `{ 'host.name': 'web-01', 'cloud.region': 'us-east-1' }` | `MetricsConfig`.`resourceAttributes` |
| `serviceName?` | `string` | The service name for metric series. Maps to the OTel resource attribute 'service.name'. **Default** `'unknown_service'` | `MetricsConfig`.`serviceName` |
| `serviceVersion?` | `string` | The service version for metric series (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. | `MetricsConfig`.`serviceVersion` |
### `CanvasMaskRegion`
> **CanvasMaskRegion** = `object`
A rectangle to paint over a recorded canvas frame, in CSS pixels relative to the canvas element.
#### Properties
| Property | Type |
| --- | --- |
| `height` | `number` |
| `width` | `number` |
| `x` | `number` |
| `y` | `number` |
### `CapturedEventInfo`
A captured event, as observed by `onEvent`.
#### Properties
| Property | Modifier | Type | Description |
| --- | --- | --- | --- |
| `event` | `readonly` | `string` | The finalized captured event name. |
| `properties` | `readonly` | `object` | The final event properties after client defaults and dynamic properties are applied. |
### `CapturedNetworkRequest`
> **CapturedNetworkRequest** = `Writable`<`Omit`<`PerformanceEntry`, `"toJSON"`\>> & `object`
#### Type Declaration
| Name | Type |
| --- | --- |
| `endTime?` | `number` |
| `initiatorType?` | `InitiatorType` |
| `isInitial?` | `boolean` |
| `method?` | `string` |
| `requestBody?` | `string` \| `null` |
| `requestHeaders?` | `Headers` |
| `responseBody?` | `string` \| `null` |
| `responseHeaders?` | `Headers` |
| `startTime?` | `number` |
| `status?` | `number` |
| `timeOrigin?` | `number` |
| `timestamp?` | `number` |
### `CaptureLogOptions`
| Property | Type | Description |
| --- | --- | --- |
| `attributes?` | `LogAttributes` | Per-log attributes (request-specific context like order\_id, duration\_ms) |
| `body` | `string` | The log message body (required) |
| `level?` | `LogSeverityLevel` | Log severity level (default: 'info') |
| `span_id?` | `string` | Span ID for correlation — 16 hex chars |
| `trace_flags?` | `number` | W3C trace flags (default: 0) |
| `trace_id?` | `string` | Trace ID for correlation — 32 hex chars |
### `CaptureMetricOptions`
Options accepted by `posthog.metrics.count/gauge/histogram`.
#### Extended by
- `HistogramOptions`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `attributes?` | `MetricAttributes` | Low-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series. |
| `unit?` | `string` | Unit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series. |
### `CaptureOptions`
| Property | Type | Description |
| --- | --- | --- |
| `$set?` | `Properties` | Used when `$identify` is called Will set person properties overriding previous values |
| `$set_once?` | `Properties` | Used when `$identify` is called Will set person properties but only once, it will NOT override previous values |
| `$unset?` | `string`\[\] | Used to unset person properties |
| `send_instantly?` | `boolean` | If set, sends the event immediately instead of adding it to the batched queue. The batched queue drains with `sendBeacon` when the page hides, and an immediate send does not use that queue. On an active page, the SDK keeps its normal transport so failed requests can be retried. By default this is `fetch`, which keeps small requests alive across a navigation, or XHR when `fetch` is unavailable. Once PostHog's own `pagehide` handler (or `unload` fallback) marks the page as unloading, the SDK prefers `sendBeacon`, unless an explicit transport, a required response, or `request_headers` prevent it. Captures from `beforeunload` or `pagehide` listeners that run before PostHog's handler still use their normal transport. This is best effort, not a guarantee: XHR and requests too large for `fetch` keepalive can be cancelled by navigation. To always use a beacon, set `{ transport: 'sendBeacon' }`, but note that accepted beacons cannot report server failures to the SDK for retries. |
| `skip_client_rate_limiting?` | `boolean` | If set, skips the client side rate limiting |
| `timestamp?` | `Date` | If set, overrides the current timestamp. UTC is preferred; non-UTC input is converted to UTC. |
| `transport?` | `"XHR"` \| `"fetch"` \| `"sendBeacon"` | If set, overrides the desired transport method |
| `uuid?` | `string` | If set, overrides the auto-generated event uuid. The value must be a valid UUID; invalid values are ignored and a new UUID is generated. Useful for cross-source idempotency (e.g. a server webhook and a browser success page both firing for the same business transaction): emit both events with the same deterministic uuid so storage can eventually deduplicate them. Capture itself does not deduplicate resent events, and PostHog does not guarantee strict immediate deduplication. |
### `CaptureOptions`
Per-call capture overrides, mirroring the client's public capture options.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `delivery?` | `"unload"` | Send immediately without batching, using best-effort unload-safe delivery. |
| `set?` | `Record`<`string`, `unknown`\> | Person properties to set, emitted as `$set`. |
| `setOnce?` | `Record`<`string`, `unknown`\> | Person properties to set if unset, emitted as `$set_once`. |
| `timestamp?` | `Date` | Override the event timestamp sent to PostHog. UTC is preferred; non-UTC input is converted to UTC. |
| `uuid?` | `string` | Override the event UUID used for de-duplication. |
### `CapturePageviewOptions`
Selects which same-page URL changes automatically capture a `$pageview`. Each option defaults to `false` when omitted.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `hash?` | `boolean` | Capture a pageview when `location.hash` changes, unless `disable_capture_url_hashes` is enabled. |
| `path?` | `boolean` | Capture a pageview when `location.pathname` changes. |
| `search?` | `boolean` | Capture a pageview when `location.search` changes. |
### `CaptureResult`
| Property | Type |
| --- | --- |
| `$set?` | `Properties` |
| `$set_once?` | `Properties` |
| `$unset?` | `string`\[\] |
| `event` | `EventName` |
| `properties` | `Properties` |
| `timestamp?` | `Date` |
| `uuid` | `string` |
### `Client`
The host SDK surface handed to an extension in `setup`. A conforming host provides it as an adapter over its own analytics, transport, persistence, event, and remote-config internals.
#### Properties
| Property | Modifier | Type | Description |
| --- | --- | --- | --- |
| `anonymousId` | `readonly` | `string` | The anonymous device id carried across identify calls. |
| `canCapture` | `readonly` | `boolean` | Whether the host currently permits data capture. |
| `deviceId` | `readonly` | `string` \| `undefined` | The actual persisted device id, absent in cookieless contexts. |
| `distinctId` | `readonly` | `string` | The id events are currently attributed to. |
| `groups` | `readonly` | `object` | Active group memberships attached to events as `$groups`. |
| `initialPersonProperties` | `readonly` | `object` | Initial person properties used for feature evaluation. |
| `isOptedOut` | `readonly` | `boolean` | Effective consent opt-out state. Cookieless capture may still be permitted while opted out. |
| `isRateLimited?` | `readonly` | `boolean` | Whether the client rate limit drops an event captured now. Reading it must not use a token. |
| `kv` | `readonly` | `KeyValueStore` | Initializable, synchronously buffered key-value storage backed by the host client's persistence. |
| `library` | `readonly` | `object` | Live host SDK metadata. |
| `library.name` | `readonly` | `string` | \- |
| `library.version` | `readonly` | `string` | \- |
| `logger` | `readonly` | `Logger` | Logger that follows the host client's debug/noise policy. |
| `onEvent` | `readonly` | `Listener`<`CapturedEventInfo`\> | Fires for every captured event through a deeply readonly view. |
| `onRemoteConfig` | `readonly` | `Listener`<{ `config`: { `analytics?`: { `endpoint?`: `string`; }; `autocapture_opt_out?`: `boolean`; `autocaptureExceptions?`: `boolean` \| { `endpoint?`: `string`; }; `captureDeadClicks?`: `boolean`; `capturePerformance?`: `boolean` \| { `__preview_web_vitals_soft_navs?`: `boolean`; `__web_vitals_max_value?`: `number`; `network_timing?`: `boolean`; `web_vitals?`: `boolean`; `web_vitals_allowed_metrics?`: readonly `SupportedWebVitalsMetrics`\[\]; `web_vitals_attribution?`: `boolean` \| readonly `SupportedWebVitalsMetrics`\[\]; `web_vitals_delayed_flush_ms?`: `number`; }; `conversations?`: `boolean` \| { `collectName?`: `boolean`; `color?`: `string`; `domains?`: readonly `string`\[\]; `enabled`: `boolean`; `greetingText?`: `string`; `identificationFormDescription?`: `string`; `identificationFormTitle?`: `string`; `placeholderText?`: `string`; `requireEmail?`: `boolean`; `token`: `string`; `widgetEnabled?`: `boolean`; `widgetPosition?`: `WidgetPosition`; }; `defaultIdentifiedOnly?`: `boolean`; `editorParams?`: { `actionId?`: `number`; `dataAttributes?`: readonly `string`\[\]; `distinctId?`: `string`; `featureFlags?`: {\[`key`: `string`\]: `string` \| `boolean`; }; `instrument?`: `boolean`; `source?`: `ToolbarSource`; `temporaryToken?`: `string`; `token?`: `string`; `toolbarVersion?`: `"toolbar"`; `userEmail?`: `string`; `userIntent?`: `ToolbarUserIntent`; }; `elementsChainAsString?`: `boolean`; `errorTracking?`: { `autocaptureExceptions?`: `boolean`; `captureExtensionExceptions?`: `boolean`; `suppressionRules?`: readonly `object`\[\]; }; `hasFeatureFlags?`: `boolean`; `heatmaps?`: `boolean`; `isAuthenticated`: `boolean`; `logs?`: { `captureConsoleLogs?`: `boolean`; }; `productTours?`: `boolean`; `sessionRecording?`: `false` \| { `canvasFps?`: `number` \| `null`; `canvasQuality?`: `string` \| `null`; `consoleLogRecordingEnabled?`: `boolean`; `endpoint?`: `string`; `eventTriggers?`: readonly `string`\[\]; `linkedFlag?`: `string` \| { `flag`: `string`; `variant`: `string`; } \| `null`; `masking?`: { `blockSelector?`: `string` \| `null`; `maskAllElementAttributes?`: `boolean`; `maskAllInputs?`: `boolean`; `maskTextSelector?`: `string` \| `null`; }; `minimumDurationMilliseconds?`: `number`; `networkPayloadCapture?`: { `recordBody?`: `boolean` \| readonly `string`\[\] \| { `request`: ... \| ... \| ...; `response`: ... \| ... \| ...; }; `recordHeaders?`: `boolean` \| { `request`: `boolean`; `response`: `boolean`; }; }; `recordCanvas?`: `boolean` \| `null`; `sampleRate?`: `string` \| `null`; `scriptConfig?`: { `script?`: `string`; }; `triggerGroups?`: readonly `object`\[\]; `triggerMatchType?`: `"all"` \| `"any"`; `urlBlocklist?`: readonly `object`\[\]; `urlTriggers?`: readonly `object`\[\]; `version?`: `1` \| `2`; }; `siteApps`: readonly `object`\[\]; `supportedCompression`: readonly `Compression`\[\]; `surveys?`: `boolean` \| readonly `object`\[\]; `toolbarParams`: { `actionId?`: `number`; `dataAttributes?`: readonly `string`\[\]; `distinctId?`: `string`; `featureFlags?`: {\[`key`: `string`\]: `string` \| `boolean`; }; `instrument?`: `boolean`; `source?`: `ToolbarSource`; `temporaryToken?`: `string`; `token?`: `string`; `toolbarVersion?`: `"toolbar"`; `userEmail?`: `string`; `userIntent?`: `ToolbarUserIntent`; }; `toolbarVersion`: `"toolbar"`; }; `ok`: `true`; } \| { `ok`: `false`; }> | Replays the latest available remote-config outcome and fires subsequent outcomes when the host makes them available. |
| `onSession` | `readonly` | `Listener`<`string`\> | Observes session IDs through the host's session notifications, without creating a session. May replay an existing session on subscription. |
| `projectToken` | `readonly` | `string` | Public project token used to authenticate endpoint-specific requests. |
| `session` | `readonly` | `SessionContext` \| `undefined` | The current session, if one exists. Reading it need not create one. |
#### Methods
##### capture()
> **capture**(`event`, `properties?`, `options?`): `boolean`
Synchronously admits an analytics event to the client's normal pipeline. Returns `false` when the client rate limit dropped the event, so the caller can send it again later. An event that is dropped for another reason, for example by `before_send`, returns `true`.
###### Parameters
| Parameter | Type |
| --- | --- |
| `event` | `string` |
| `properties?` | `Properties` \| `null` |
| `options?` | `CaptureOptions` |
###### Returns
`boolean`
##### getExtension()
###### Call Signature
> **getExtension**<`T`\>(`token`): `T` | `undefined`
Returns the extension registered under a typed stable name, or `undefined` when it is not installed.
###### Type Parameters
| Type Parameter |
| --- |
| `T` *extends* `Extension`<`Client`\> |
###### Parameters
| Parameter | Type |
| --- | --- |
| `token` | `ExtensionToken`<`T`\> |
###### Returns
`T` | `undefined`
###### Call Signature
> **getExtension**<`T`\>(`name`): `T` | `undefined`
Returns the extension registered under a stable name, or `undefined` when it is not installed.
###### Type Parameters
| Type Parameter | Default type |
| --- | --- |
| `T` *extends* `Extension`<`Client`\> | `Extension`<`Client`\> |
###### Parameters
| Parameter | Type |
| --- | --- |
| `name` | `string` |
###### Returns
`T` | `undefined`
##### registerDynamicEventProperties()
> **registerDynamicEventProperties**(`producer`): `Disposable`
Registers a synchronous producer of properties merged into every captured event.
###### Parameters
| Parameter | Type |
| --- | --- |
| `producer` | () => `Record`<`string`, `unknown`\> |
###### Returns
`Disposable`
##### sendRequest()
> **sendRequest**(`path`, `init?`): `Promise`<`ApiResponse`\>
Sends a request through the host SDK's transport.
###### Parameters
| Parameter | Type |
| --- | --- |
| `path` | `string` |
| `init?` | `SendRequestInit` |
###### Returns
`Promise`<`ApiResponse`\>
### `Compression`
> **Compression** = *typeof* `Compression`\[keyof *typeof* `Compression`\]
### `ConfigDefaults`
> **ConfigDefaults** = `"latest"` | *typeof* `CONFIG_DEFAULTS_DATES`\[`number`\] | `"unset"`
Configuration defaults snapshot used by `PostHogConfig.defaults`. Later dates include all earlier default changes. `latest` includes all changes in the loaded SDK version.
### `ConversationsConfig`
Conversations configuration options
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `theme?` | `ConversationsTheme` | Theme of the support widget. Change it after init with `posthog.conversations.setTheme()`. **Example** `posthog.init('phc_...', { conversations: { theme: { colorScheme: 'auto', primary: '#111827', dark: { primary: '#f9fafb' } }, }, })` |
### `ConversationsRemoteConfig`
Remote configuration for conversations from the PostHog server.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `collectName?` | `boolean` | Whether to show the name field in the identification form. |
| `color?` | `string` | Primary color for the widget UI. |
| `domains?` | `string`\[\] | Domains where the widget may be shown. |
| `enabled` | `boolean` | Whether conversations are enabled for this team. |
| `greetingText?` | `string` | Greeting text to show when the widget is first opened. |
| `identificationFormDescription?` | `string` | Description for the identification form. |
| `identificationFormTitle?` | `string` | Title for the identification form. |
| `placeholderText?` | `string` | Placeholder text for the message input. |
| `requireEmail?` | `boolean` | Whether to require an email address before starting a conversation. |
| `token` | `string` | Public token for authenticating conversations API requests. |
| `widgetEnabled?` | `boolean` | Whether the widget UI should be shown. |
| `widgetPosition?` | `WidgetPosition` | Position of the widget on the screen. |
### `ConversationsTheme`
Theme of the conversations widget. The top-level colors are the light colors; `dark` holds the dark ones.
Values are applied as `--ph-conv-*` CSS custom properties (`--ph-conv-primary`, `--ph-conv-on-primary`, `--ph-conv-bg`, `--ph-conv-surface`, `--ph-conv-text`, `--ph-conv-muted`, `--ph-conv-border`, `--ph-conv-agent-bubble`, `--ph-conv-font`, `--ph-conv-radius`, `--ph-conv-launcher-shadow`, `--ph-conv-window-shadow`). Rules in your own stylesheet that set them on `#ph-conversations-widget-container` take precedence over the theme.
#### Extends
- `ConversationsThemeColors`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `agentBubble?` | `string` | Background of messages from your team. | `ConversationsThemeColors`.`agentBubble` |
| `background?` | `string` | Window, message list and input background. | `ConversationsThemeColors`.`background` |
| `border?` | `string` | Borders and dividers. | `ConversationsThemeColors`.`border` |
| `borderRadius?` | `string` | Corner radius of the chat window, e.g. `'16px'`. | \- |
| `colorScheme?` | `"auto"` \| `"light"` \| `"dark"` | Which colors to use. `'auto'` follows the visitor's `prefers-color-scheme`. **Default** `'light'` | \- |
| `dark?` | `ConversationsThemeColors` | Colors used when the dark scheme is active. Unset values fall back to built-in dark colors, except `primary` and `primaryText`, which fall back to the light ones. | \- |
| `fontFamily?` | `string` | Font family of the widget. | \- |
| `launcherShadow?` | `string` | CSS `filter` applied to the launcher button, e.g. `'none'` or `'drop-shadow(0 2px 8px rgba(0,0,0,0.2))'`. | \- |
| `mutedText?` | `string` | Secondary text: timestamps, author names, descriptions. | `ConversationsThemeColors`.`mutedText` |
| `primary?` | `string` | Launcher, header, customer messages and buttons. Overrides the color set in project settings. | `ConversationsThemeColors`.`primary` |
| `primaryText?` | `string` | Text and icons drawn on `primary`. Computed from `primary` when it is a hex color and this is unset. | `ConversationsThemeColors`.`primaryText` |
| `surface?` | `string` | Secondary background: identification form, unread tickets, code blocks. | `ConversationsThemeColors`.`surface` |
| `text?` | `string` | Main text color. | `ConversationsThemeColors`.`text` |
| `windowShadow?` | `string` | CSS `box-shadow` of the chat window. | \- |
### `ConversationsThemeColors`
Colors of the conversations widget. Any CSS color value is accepted.
#### Extended by
- `ConversationsTheme`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `agentBubble?` | `string` | Background of messages from your team. |
| `background?` | `string` | Window, message list and input background. |
| `border?` | `string` | Borders and dividers. |
| `mutedText?` | `string` | Secondary text: timestamps, author names, descriptions. |
| `primary?` | `string` | Launcher, header, customer messages and buttons. Overrides the color set in project settings. |
| `primaryText?` | `string` | Text and icons drawn on `primary`. Computed from `primary` when it is a hex color and this is unset. |
| `surface?` | `string` | Secondary background: identification form, unread tickets, code blocks. |
| `text?` | `string` | Main text color. |
### `ConversationsTraits`
User traits to send with messages
#### Indexable
> \[`key`: `string`\]: `string` | `number` | `boolean` | `null` | `undefined`
#### Properties
| Property | Type |
| --- | --- |
| `email?` | `string` \| `null` |
| `name?` | `string` \| `null` |
### `ConversationsUnavailableReason`
> **ConversationsUnavailableReason** = `"disabled_by_config"` | `"consent_opted_out"` | `"disabled_for_toolbar"` | `"remote_config_pending"` | `"remote_config_failed"` | `"disabled_in_project"` | `"missing_token"` | `"extensions_unavailable"` | `"load_failed"` | `"initializing"` | `"not_loaded"`
### `ConversationsWidgetState`
> **ConversationsWidgetState** = `"open"` | `"closed"`
Visual state of the conversations widget
### `DeadClickCandidate`
| Property | Type |
| --- | --- |
| `absoluteDelayMs?` | `number` |
| `focusChangedDelayMs?` | `number` |
| `mutationDelayMs?` | `number` |
| `node` | `Element` |
| `originalEvent` | `MouseEvent` \| `TouchEvent` |
| `scrollDelayMs?` | `number` |
| `selectionChangedDelayMs?` | `number` |
| `swipeDirection?` | `"left"` \| `"right"` \| `"up"` \| `"down"` |
| `swipeDistancePx?` | `number` |
| `timestamp` | `number` |
| `type?` | `"click"` \| `"swipe"` |
| `visibilityChangedDelayMs?` | `number` |
### `DeadClicksAutoCaptureConfig`
> **DeadClicksAutoCaptureConfig** = `object` & `Pick`<`AutocaptureConfig`, `"element_attribute_ignorelist"`\>
#### Type Declaration
| Name | Type | Description |
| --- | --- | --- |
| `__onCapture()?` | (`click`, `properties`) => `void` | Allows setting behavior for when a dead click is captured. For e.g. to support capture to heatmaps If not provided the default behavior is to auto-capture dead click events Only intended to be provided by our own SDK |
| `capture_clicks_with_modifier_keys?` | `boolean` | By default, clicks with modifier keys (ctrl, shift, alt, meta/cmd) held down are not considered dead clicks, since these typically indicate intentional actions like "open in new tab". Set this to true to capture dead clicks even when modifier keys are held. **Default** `false` |
| `capture_dead_swipes?` | `boolean` | Determines whether PostHog should also detect "dead swipes" — touch swipe gestures (typically on mobile/touch devices) that produce no observable screen change (no scroll, mutation or selection change while the gesture is in progress, and no scroll, mutation, selection or visibility change afterwards). These usually indicate a failed navigation, e.g. swiping to go back or to move a carousel with nothing happening. Dead swipes are captured as `$dead_swipe` events. This only applies to the dead-click autocapture path, not the heatmaps path. Swipes over surfaces whose response cannot be observed — canvas, video and other media/plugin elements under the finger — are never captured, and capture is limited per page load (see `max_dead_swipes_per_page_load`). **Default** `true` |
| `css_selector_ignorelist?` | `string`\[\] | List of CSS selectors to ignore dead clicks on e.g. \['.my-download-link'\] we consider the tree of elements from the root to the target element of the click event so for the tree div > div > a > svg and ignore list config `['[download]']` we will ignore the dead click if the click-target or its parents has any download attribute Nothing is ignored when there's an empty ignorelist, e.g. \[\] If no ignorelist is set, we default to ignoring .ph-no-deadclick and .ph-no-capture A custom ignorelist fully replaces the default — include .ph-no-capture if you want it to suppress dead-click capture as well |
| `max_dead_swipes_per_page_load?` | `number` | The maximum number of dead swipes captured per page load. Swipe gestures are plentiful on touch devices, so a page whose responses the detector cannot see is capped rather than allowed to flood events. Only used when `capture_dead_swipes` is enabled. **Default** `10` |
| `mutation_threshold_ms?` | `number` | We'll not consider a click to be a dead click, if it's followed by a mutation within `mutation_threshold_ms` milliseconds **Default** `2500` |
| `scroll_threshold_ms?` | `number` | We'll not consider a click to be a dead click, if it's followed by a scroll within `scroll_threshold_ms` milliseconds **Default** `100` |
| `selection_change_threshold_ms?` | `number` | We'll not consider a click to be a dead click if it selects/unselects text or moves a caret in editable content during its mouse gesture, regardless of how long the button is held. Selection changes outside a matching gesture suppress the click when they occur within `selection_change_threshold_ms` milliseconds immediately before or after it. When a closed shadow root hides whether a caret belongs to editable content, only the timed window applies. A value of 0 disables selection-based suppression. **Default** `100` |
| `swipe_threshold_px?` | `number` | The minimum straight-line distance in CSS pixels between where a touch gesture starts and ends for it to be considered a swipe (rather than a tap). Only used when `capture_dead_swipes` is enabled. **Default** `30` |
### `DisplaySurveyInlineOptions`
- `DisplaySurveyOptionsBase`
#### Properties
| Property | Type | Description | Overrides | Inherited from |
| --- | --- | --- | --- | --- |
| `displayType` | `"inline"` | How the survey should be displayed. **Default** `DisplaySurveyType.Popover` | `DisplaySurveyOptionsBase`.`displayType` | \- |
| `ignoreConditions` | `boolean` | Whether to bypass the survey's targeting and display conditions. **Default** `false` | \- | `DisplaySurveyOptionsBase`.`ignoreConditions` |
| `ignoreDelay` | `boolean` | Whether to bypass the survey's configured popup delay. **Default** `false` | \- | `DisplaySurveyOptionsBase`.`ignoreDelay` |
| `initialResponses?` | `Record`<`number`, `SurveyResponseValue`\> | Pre-filled responses by question index (0-based). Only supported for popover surveys. | \- | `DisplaySurveyOptionsBase`.`initialResponses` |
| `properties?` | `Properties` | Additional properties to include in all survey events (shown, sent, dismissed). | \- | `DisplaySurveyOptionsBase`.`properties` |
| `selector` | `string` | CSS selector for the element where the inline survey should render. | \- | \- |
### `DisplaySurveyOptions`
> **DisplaySurveyOptions** = `DisplaySurveyPopoverOptions` | `DisplaySurveyInlineOptions`
Options for `posthog.displaySurvey()`.
### `DisplaySurveyOptionsBase`
- `DisplaySurveyPopoverOptions`
- `DisplaySurveyInlineOptions`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `displayType` | `DisplaySurveyType` | How the survey should be displayed. **Default** `DisplaySurveyType.Popover` |
| `ignoreConditions` | `boolean` | Whether to bypass the survey's targeting and display conditions. **Default** `false` |
| `ignoreDelay` | `boolean` | Whether to bypass the survey's configured popup delay. **Default** `false` |
| `initialResponses?` | `Record`<`number`, `SurveyResponseValue`\> | Pre-filled responses by question index (0-based). Only supported for popover surveys. |
| `properties?` | `Properties` | Additional properties to include in all survey events (shown, sent, dismissed). |
### `DisplaySurveyPopoverOptions`
Options for displaying a survey as a popover.
#### Extends
- `DisplaySurveyOptionsBase`
#### Properties
| Property | Type | Description | Overrides | Inherited from |
| --- | --- | --- | --- | --- |
| `displayType` | `"popover"` | How the survey should be displayed. **Default** `DisplaySurveyType.Popover` | `DisplaySurveyOptionsBase`.`displayType` | \- |
| `ignoreConditions` | `boolean` | Whether to bypass the survey's targeting and display conditions. **Default** `false` | \- | `DisplaySurveyOptionsBase`.`ignoreConditions` |
| `ignoreDelay` | `boolean` | Whether to bypass the survey's configured popup delay. **Default** `false` | \- | `DisplaySurveyOptionsBase`.`ignoreDelay` |
| `initialResponses?` | `Record`<`number`, `SurveyResponseValue`\> | Pre-filled responses by question index (0-based). Only supported for popover surveys. | \- | `DisplaySurveyOptionsBase`.`initialResponses` |
| `position?` | `SurveyPosition` | Override the survey's configured position. | \- | \- |
| `properties?` | `Properties` | Additional properties to include in all survey events (shown, sent, dismissed). | \- | `DisplaySurveyOptionsBase`.`properties` |
| `selector?` | `string` | CSS selector for the element to position the survey next to (when position is NextToTrigger). | \- | \- |
| `skipShownEvent?` | `boolean` | When true, `survey shown` events will not be emitted automatically. | \- | \- |
### `DisplaySurveyType`
> **DisplaySurveyType** = *typeof* `DisplaySurveyType`\[keyof *typeof* `DisplaySurveyType`\]
### `Disposable`
A resource handle with idempotent, best-effort cleanup.
#### Methods
##### dispose()
> **dispose**(): `void`
Release resources owned by this object.
###### Returns
`void`
### `DomAutocaptureEvents`
> **DomAutocaptureEvents** = `"click"` | `"change"` | `"submit"`
### `EarlyAccessFeature`
A feature that isn't publicly available yet.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `description` | `string` | \- |
| `documentationUrl` | `string` \| `null` | \- |
| `flagKey` | `string` \| `null` | \- |
| `imageUrl?` | `string` \| `null` | URL of an image that shows the feature, such as a screenshot. Empty when the feature has no image. |
| `name` | `string` | \- |
| `payload` | `JsonType` | \- |
| `stage` | `"concept"` \| `"alpha"` \| `"beta"` | \- |
### `EarlyAccessFeatureCallback`
> **EarlyAccessFeatureCallback** = (`earlyAccessFeatures`) => `void`
#### Parameters
| Parameter | Type |
| --- | --- |
| `earlyAccessFeatures` | `EarlyAccessFeature`\[\] |
#### Returns
`void`
### `EarlyAccessFeatureResponse`
| Property | Type |
| --- | --- |
| `earlyAccessFeatures` | `EarlyAccessFeature`\[\] |
### `EarlyAccessFeatureStage`
> **EarlyAccessFeatureStage** = `"concept"` | `"alpha"` | `"beta"` | `"general-availability"`
### `EndBranching`
| Property | Type |
| --- | --- |
| `type` | `"end"` |
### `ErrorEventArgs`
> **ErrorEventArgs** = \[`event`: `string` | `Event`, `source?`: `string` | `undefined`, `lineno?`: `number` | `undefined`, `colno?`: `number` | `undefined`, `error?`: `Error` | `undefined`\]
### `ErrorTrackingOptions`
Shared configuration for the error tracking burst-protection rate limiter.
Burst protection is scoped **per exception type** — the limiter is keyed by exception type, so each distinct `$exception` type gets its own token bucket and there is no aggregate cap across all types. It applies only to autocaptured exceptions; manual `captureException` calls are never rate limited. These options let customers with high-cardinality exception types tune the per-type allowance, and are shared between the browser and Node SDKs.
#### Extends
- `ExceptionRateLimiterConfig`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `__capturePostHogExceptions?` | `boolean` | UNSTABLE: determines whether exception caused by the PostHog SDK will be captured **Default** `false` | \- |
| `__exceptionRateLimiterBucketSize?` | `number` | **Deprecated** Use ExceptionRateLimiterConfig.exceptionRateLimiterBucketSize instead. Still honoured as a fallback, but will be removed in a future major version. | \- |
| `__exceptionRateLimiterRefillRate?` | `number` | **Deprecated** Use ExceptionRateLimiterConfig.exceptionRateLimiterRefillRate instead. Still honoured as a fallback, but will be removed in a future major version. | \- |
| `captureExtensionExceptions?` | `boolean` | Decide whether exceptions thrown by browser extensions or by scripts injected by the browser itself (for example Firefox for iOS and Chrome for iOS user scripts) should be captured. When false, both categories are dropped before capture. **Default** `false` | \- |
| `exception_steps?` | `ExceptionStepsConfig` | Controls buffering and payload limits for exception steps added via `addExceptionStep`. | \- |
| `exceptionRateLimiterBucketSize?` | `number` | ADVANCED: alters the bucket size for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. **Default** `10` | `ExceptionRateLimiterConfig`.`exceptionRateLimiterBucketSize` |
| `exceptionRateLimiterRefillRate?` | `number` | ADVANCED: alters the refill rate for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. **Default** `1` | `ExceptionRateLimiterConfig`.`exceptionRateLimiterRefillRate` |
### `ErrorTrackingSuppressionRule`
| Property | Type |
| --- | --- |
| `type` | `"AND"` \| `"OR"` |
| `values` | `ErrorTrackingSuppressionRuleValue`\[\] |
### `ErrorTrackingSuppressionRuleValue`
| Property | Type |
| --- | --- |
| `key` | `"$exception_types"` \| `"$exception_values"` |
| `operator` | `SurveyMatchType` |
| `type` | `string` |
| `value` | `string` \| `string`\[\] |
### `EvaluationReason`
> **EvaluationReason** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `code` | `string` |
| `condition_index` | `number` \| `undefined` |
| `description` | `string` \| `undefined` |
### `EventHandler`
> **EventHandler** = (`event`) => `boolean` | `void`
#### Parameters
| Parameter | Type |
| --- | --- |
| `event` | `Event` |
#### Returns
`boolean` | `void`
### `EventName`
> **EventName** = `KnownUnsafeEditableEvent` | `KnownEventName` | `string` & `object`
### `ExceptionAutoCaptureConfig`
> **ExceptionAutoCaptureConfig** = `object`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `capture_console_errors?` | `boolean` | Determines whether PostHog should capture console errors. **Default** `false` |
| `capture_unhandled_errors?` | `boolean` | Determines whether PostHog should capture unhandled errors. **Default** `true` |
| `capture_unhandled_rejections?` | `boolean` | Determines whether PostHog should capture unhandled promise rejections. **Default** `true` |
### `ExceptionRateLimiterConfig`
Shared configuration for the error tracking burst-protection rate limiter.
Burst protection is scoped **per exception type** — the limiter is keyed by exception type, so each distinct `$exception` type gets its own token bucket and there is no aggregate cap across all types. It applies only to autocaptured exceptions; manual `captureException` calls are never rate limited. These options let customers with high-cardinality exception types tune the per-type allowance, and are shared between the browser and Node SDKs.
#### Extended by
- `ErrorTrackingOptions`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `exceptionRateLimiterBucketSize?` | `number` | ADVANCED: alters the bucket size for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. **Default** `10` |
| `exceptionRateLimiterRefillRate?` | `number` | ADVANCED: alters the refill rate for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. **Default** `1` |
### `ExceptionStepsConfig`
> **ExceptionStepsConfig** = `object`
Controls buffering and payload limits for exception steps added via `addExceptionStep`.
NOTE: This type is also defined in `@posthog/core` (exception-steps.ts). Keep both in sync.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `enabled?` | `boolean` | Determines whether PostHog should collect exception steps and attach them to the next captured exception. **Default** `true` |
| `max_bytes?` | `number` | The maximum UTF-8 byte budget for exception steps buffered in memory. Oldest steps are evicted when the budget is exceeded. **Default** `32768 (~32KB)` |
### `Extension`
A shared browser extension. The client calls `setup(client)` once to start it and optional `dispose()` once for final best-effort resource cleanup. Everything an extension consumes flows through its host, Client by default.
`setup` may be async so an extension can read async KV state or remote config before it is ready. Async extensions must guard work after each `await` so cleanup cannot be followed by late listener, timer, or patch installation. The disposables an extension creates in setup are its own to release.
An extension that exposes app-facing controls extends `Extension` with named methods that share its state, e.g.:
```typescript
interface SessionReplayExtension extends Extension {
startRecording(): void
stopRecording(): void
isActive(): boolean
}
```
#### Type Parameters
| Type Parameter | Default type |
| --- | --- |
| `Host` | `Client` |
#### Properties
| Property | Modifier | Type | Description |
| --- | --- | --- | --- |
| `bindings?` | `readonly` | `Readonly`<`Record`<`string`, `Extension`<`Client`\>>> | Additional lookup targets whose lifecycle belongs to this extension. |
| `name` | `readonly` | `string` | Stable extension name used for diagnostics and de-duplication within a client instance. |
#### Methods
##### dispose()?
> `optional` **dispose**(): `void`
Release final resources synchronously. Feature-level start/stop remains extension-owned.
###### Returns
`void`
##### flush()?
> `optional` **flush**(`reason?`): `Promise`<`void`\>
Flush buffered work. Shutdown awaits this within the host's timeout before disposal.
###### Parameters
| Parameter | Type |
| --- | --- |
| `reason?` | `"shutdown"` \| `"flush"` |
###### Returns
`Promise`<`void`\>
##### setup()
> **setup**(`client`): `void` | `Promise`<`void`\>
Start the extension with the host client's capability surface. Called once after construction; return a promise when setup needs asynchronous state.
###### Parameters
| Parameter | Type |
| --- | --- |
| `client` | `Host` |
###### Returns
`void` | `Promise`<`void`\>
### `ExtensionToken`
> **ExtensionToken**<`T`\> = `string` & `object`
A typed stable name for resolving an installed extension.
Tokens are plain strings at runtime, so independently compiled scripts can share them without a registry or object-identity contract. The generic brand lets `Client.getExtension` infer the extension type. A token's string value must match an installed extension's stable `name` or one of its `bindings` keys.
#### Type Parameters
| Type Parameter |
| --- |
| `T` |
#### Type Declaration
| Name | Type |
| --- | --- |
| `[extensionTokenType]` | `T` |
### `ExternalIntegrationKind`
> **ExternalIntegrationKind** = `"intercom"` | `"crispChat"`
### `FeatureFlagDetail`
> **FeatureFlagDetail** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `enabled` | `boolean` |
| `failed?` | `boolean` |
| `key` | `string` |
| `metadata` | `FeatureFlagMetadata` \| `undefined` |
| `original_enabled?` | `boolean` |
| `original_variant?` | `string` |
| `reason` | `EvaluationReason` \| `undefined` |
| `variant` | `string` \| `undefined` |
### `FeatureFlagMetadata`
> **FeatureFlagMetadata** = `object`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `description` | `string` \| `undefined` | \- |
| `has_experiment?` | `boolean` | Whether the flag is linked to an experiment. Absent when the server does not report it. |
| `id` | `number` | \- |
| `original_payload?` | `JsonType` | \- |
| `payload` | `JsonType` \| `undefined` | \- |
| `version` | `number` \| `undefined` | \- |
### `FeatureFlagOptions`
> **FeatureFlagOptions** = `object`
Options for feature flag lookup methods (getFeatureFlag, isFeatureEnabled, getFeatureFlagResult).
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `fresh?` | `boolean` | If true, only return values loaded from the server, not cached localStorage values. Returns undefined if flags haven't been loaded from the server yet. Defaults to false. |
| `send_event?` | `boolean` | Whether to send a $feature\_flag\_called event. Defaults to true. |
### `FeatureFlagOverrideOptions`
> **FeatureFlagOverrideOptions** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `flags?` | `boolean` \| `string`\[\] \| `FeatureFlagOverrides` |
| `payloads?` | `FeatureFlagPayloadOverrides` |
| `suppressWarning?` | `boolean` |
### `FeatureFlagOverrides`
> **FeatureFlagOverrides** = `object`
#### Index Signature
\[`flagName`: `string`\]: `string` | `boolean`
### `FeatureFlagPayloadOverrides`
> **FeatureFlagPayloadOverrides** = `object`
#### Index Signature
\[`flagName`: `string`\]: `JsonType`
### `FeatureFlagResult`
> **FeatureFlagResult** = `object`
Result of evaluating a feature flag, including both the flag value and its payload.
#### Properties
| Property | Modifier | Type | Description |
| --- | --- | --- | --- |
| `enabled` | `readonly` | `boolean` | Whether the returned feature flag evaluation is enabled. `false` is a conclusive off result. |
| `key` | `readonly` | `string` | The key of the feature flag |
| `payload` | `readonly` | `JsonType` \| `undefined` | The JSON payload associated with this flag, if any |
| `variant` | `readonly` | `string` \| `undefined` | The variant key if this is a multivariate flag, undefined for boolean flags |
### `FeatureFlagsCallback`
> **FeatureFlagsCallback** = (`flags`, `variants`, `context?`) => `void`
#### Parameters
| Parameter | Type |
| --- | --- |
| `flags` | `string`\[\] |
| `variants` | `Record`<`string`, `string` \| `boolean`\> |
| `context?` | { `errorsLoading?`: `boolean`; } |
| `context.errorsLoading?` | `boolean` |
#### Returns
`void`
### `FeatureFlagsConfig`
| Property | Modifier | Type |
| --- | --- | --- |
| `bootstrap` | `readonly` | `object` |
| `bootstrap.featureFlagPayloads?` | `readonly` | `Readonly`<`Record`<`string`, `JsonType`\>> |
| `bootstrap.featureFlags?` | `readonly` | `Readonly`<`Record`<`string`, `string` \| `boolean`\>> |
| `cacheTtlMs?` | `readonly` | `number` |
| `compression?` | `readonly` | `Compression` \| `"best-available"` |
| `deduplicateCallsPerSession` | `readonly` | `boolean` |
| `evaluationContexts` | `readonly` | readonly `string`\[\] |
| `featureFlagsDisabled` | `readonly` | `boolean` |
| `flagKeys?` | `readonly` | readonly `string`\[\] |
| `idleRefreshBackoff` | `readonly` | `boolean` |
| `onlyEvaluateSurveyFeatureFlags` | `readonly` | `boolean` |
| `refreshIntervalMs?` | `readonly` | `number` |
| `remoteRequestsDisabled` | `readonly` | `boolean` |
| `requestMaxRetries?` | `readonly` | `number` |
| `requestTimeoutMs` | `readonly` | `number` |
### `FeatureFlagsConfigSource`
##### get()
> **get**(): `Readonly`<`FeatureFlagsConfig`\>
###### Returns
`Readonly`<`FeatureFlagsConfig`\>
### `FeatureFlagsReloadResult`
| Property | Type | Description |
| --- | --- | --- |
| `status` | `"loaded"` \| `"error"` \| `"skipped"` \| `"cancelled"` | loaded: evaluation completed; error: request/evaluation failed; skipped: evaluation unavailable; cancelled: reset/disposal. |
### `FlagsResponse`
Flags returns feature flags and their payloads
#### Extends
- `RemoteConfig`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `analytics?` | `object` | Custom endpoint configuration for analytics events. | `RemoteConfig`.`analytics` |
| `analytics.endpoint?` | `string` | \- | \- |
| `autocapture_opt_out?` | `boolean` | If true, disables autocapture. When absent or not a boolean, the SDK keeps the last known server value; a visitor with no stored value keeps autocapture off until a response containing the field arrives. | `RemoteConfig`.`autocapture_opt_out` |
| `autocaptureExceptions?` | `boolean` \| { `endpoint?`: `string`; } | Exception autocapture configuration. | `RemoteConfig`.`autocaptureExceptions` |
| `captureDeadClicks?` | `boolean` | Whether to capture dead clicks. | `RemoteConfig`.`captureDeadClicks` |
| `capturePerformance?` | `boolean` \| `PerformanceCaptureConfig` | Performance capture configuration shared by replay and web vitals. | `RemoteConfig`.`capturePerformance` |
| `conversations?` | `boolean` \| `ConversationsRemoteConfig` | Conversations widget configuration. | `RemoteConfig`.`conversations` |
| `defaultIdentifiedOnly?` | `boolean` | Whether to capture only identified users by default. | `RemoteConfig`.`defaultIdentifiedOnly` |
| `editorParams?` | `ToolbarParams` | **Deprecated** Renamed to `toolbarParams`; still present on older API responses. | `RemoteConfig`.`editorParams` |
| `elementsChainAsString?` | `boolean` | Whether `$elements_chain` is sent as a string rather than an array. | `RemoteConfig`.`elementsChainAsString` |
| `errorsWhileComputingFlags` | `boolean` | \- | \- |
| `errorTracking?` | `object` | Error tracking configuration. | `RemoteConfig`.`errorTracking` |
| `errorTracking.autocaptureExceptions?` | `boolean` | \- | \- |
| `errorTracking.captureExtensionExceptions?` | `boolean` | \- | \- |
| `errorTracking.suppressionRules?` | `ErrorTrackingSuppressionRule`\[\] | \- | \- |
| `evaluatedAt?` | `number` | \- | \- |
| `featureFlagPayloads` | `Record`<`string`, `JsonType`\> | \- | \- |
| `featureFlags` | `Record`<`string`, `string` \| `boolean`\> | \- | \- |
| `flags` | `Record`<`string`, `FeatureFlagDetail`\> | \- | \- |
| `hasFeatureFlags?` | `boolean` | Whether the team has any feature flags enabled. | `RemoteConfig`.`hasFeatureFlags` |
| `heatmaps?` | `boolean` | Whether heatmaps are enabled. | `RemoteConfig`.`heatmaps` |
| `isAuthenticated` | `boolean` | Whether the current user is authenticated. | `RemoteConfig`.`isAuthenticated` |
| `logs?` | `object` | Log capture configuration. | `RemoteConfig`.`logs` |
| `logs.captureConsoleLogs?` | `boolean` | \- | \- |
| `minimalFlagCalledEvents?` | `boolean` | Server-controlled gate for minimal `$feature_flag_called` events. `true` only when the project opted in; omitted otherwise. Absence always means full events. | \- |
| `productTours?` | `boolean` | Whether product tours are enabled. | `RemoteConfig`.`productTours` |
| `requestId?` | `string` | \- | \- |
| `sessionRecording?` | `false` \| `SessionRecordingRemoteConfig` | Session recording configuration. | `RemoteConfig`.`sessionRecording` |
| `siteApps` | `object`\[\] | Site apps available to the client. | `RemoteConfig`.`siteApps` |
| `supportedCompression` | `Compression`\[\] | Supported compression algorithms. | `RemoteConfig`.`supportedCompression` |
| `surveys?` | `boolean` \| `Survey`\[\] | Whether surveys are enabled, optionally including their definitions. | `RemoteConfig`.`surveys` |
| `toolbarParams` | `ToolbarParams` | Parameters for the toolbar. | `RemoteConfig`.`toolbarParams` |
| `toolbarVersion` | `"toolbar"` | **Deprecated** Moved to `toolbarParams`. | `RemoteConfig`.`toolbarVersion` |
### `FlagVariant`
> **FlagVariant** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `flag` | `string` |
| `variant` | `string` |
### `GetMessagesResponse`
Response from fetching messages
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `has_more` | `boolean` | Whether there are more messages to fetch |
| `messages` | `Message`\[\] | Array of messages |
| `ticket_id` | `string` | ID of the ticket |
| `ticket_status` | `TicketStatus` | Current status of the ticket |
| `unread_count` | `number` | Number of unread messages from the team |
### `GetTicketsOptions`
Options for fetching tickets list
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `limit?` | `number` | Number of tickets to return (default: 20) |
| `offset?` | `number` | Pagination offset (default: 0) |
| `status?` | `string` | Filter by ticket status (e.g., 'open', 'closed') |
### `GetTicketsResponse`
Response from fetching tickets list
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `count` | `number` | Total count of tickets |
| `results` | `Ticket`\[\] | Array of tickets |
### `Headers`
> **Headers** = `Record`<`string`, `string`\>
Request-related types
### `HeatmapConfig`
| Property | Type | Description |
| --- | --- | --- |
| `flush_interval_milliseconds` | `number` | How often to send batched data in `$heatmap_data` events If set to 0 or not set, sends using the default interval of 1 second **Default** `1000` |
### `HistogramOptions`
Options accepted by `posthog.metrics.histogram`.
#### Extends
- `CaptureMetricOptions`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `attributes?` | `MetricAttributes` | Low-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series. | `CaptureMetricOptions`.`attributes` |
| `bounds?` | `number`\[\] | Upper bucket boundaries, finite and strictly increasing. A value lands in the first bucket whose boundary is greater than or equal to it, and values above the last boundary land in an overflow bucket. Defaults to the OpenTelemetry defaults `[0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]`. The first sample of a histogram (name and unit) fixes its bounds until the client resets. A later sample that passes different bounds is recorded in the fixed buckets and logs a warning, once per flush window. A sample with invalid bounds is dropped with a warning. The client fixes the bounds of at most `maxSeriesPerFlush` histograms. Past that limit, the client drops samples of a new histogram that pass bounds other than the defaults, and logs one warning. Each client fixes bounds on its own. PostHog stores one set of bounds per histogram series and reads every client's counts against it. Every client must therefore pass the same bounds for the same histogram. | \- |
| `unit?` | `string` | Unit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series. | `CaptureMetricOptions`.`unit` |
### `InferredSelector`
| Property | Type |
| --- | --- |
| `autoData` | `string` |
| `excludeText?` | `boolean` |
| `precision?` | `number` |
| `text` | `string` \| `null` |
### `InitiatorType`
> **InitiatorType** = `"audio"` | `"beacon"` | `"body"` | `"css"` | `"early-hint"` | `"embed"` | `"fetch"` | `"frame"` | `"iframe"` | `"icon"` | `"image"` | `"img"` | `"input"` | `"link"` | `"navigation"` | `"object"` | `"ping"` | `"script"` | `"track"` | `"video"` | `"xmlhttprequest"`
### `IsFeatureEnabledOptions`
> **IsFeatureEnabledOptions** = `FeatureFlagOptions` & `object`
Options for isFeatureEnabled.
#### Type Declaration
| Name | Type | Description |
| --- | --- | --- |
| `defaultValue?` | `boolean` | Value to return when the flag has no value, e.g. flags have not loaded yet or no flag with that key exists. |
### `JSONContent`
| Property | Type |
| --- | --- |
| `attrs?` | `Record`<`string`, `any`\> |
| `content?` | `JSONContent`\[\] |
| `marks?` | `object`\[\] |
| `text?` | `string` |
| `type?` | `string` |
### `JsonRecord`
> **JsonRecord** = `object`
#### Index Signature
\[`key`: `string`\]: `JsonType`
### `JsonType`
> **JsonType** = `string` | `number` | `boolean` | `null` | `undefined` | `JsonRecord` | `JsonType`\[\]
### `KeyValueStore`
Key-value store for small extension state. A host may initialize an asynchronous backend before exposing synchronous operations over its in-memory buffer. Writes must update that buffer before returning; ordered durable flushing remains the host's responsibility. Reads treat `undefined` values as absent.
Keys map verbatim to the host client's shared persistence. In browser-v1, unknown keys are normally included as event properties, collisions overwrite host/core state, and reset clears them. Every SDK-owned key therefore needs an explicit event/hidden/derived exposure policy in each host, and sensitive data must not be stored unless its transmission is approved. Values must be JSON-serializable.
#### Methods
##### get()
###### Call Signature
> **get**<`T`\>(`keys`): `Partial`<`T`\>
Read several initialized values in one operation. Missing keys are omitted.
###### Type Parameters
| Type Parameter |
| --- |
| `T` *extends* `object` |
###### Parameters
| Parameter | Type |
| --- | --- |
| `keys` | readonly (keyof `T` & `string`)\[\] |
###### Returns
`Partial`<`T`\>
###### Call Signature
> **get**<`T`\>(`key`): `T` | `undefined`
Read one initialized value by key, returning `undefined` when it is missing.
###### Type Parameters
| Type Parameter | Default type |
| --- | --- |
| `T` | `unknown` |
###### Parameters
| Parameter | Type |
| --- | --- |
| `key` | `string` |
###### Returns
`T` | `undefined`
##### initialize()
> **initialize**(): `void` | `Promise`<`void`\>
Populate the in-memory buffer from durable storage. Calls are idempotent.
###### Returns
`void` | `Promise`<`void`\>
##### remove()
> **remove**(`keyOrKeys`): `void`
Remove one or several values from the initialized buffer in one operation.
###### Parameters
| Parameter | Type |
| --- | --- |
| `keyOrKeys` | `string` \| readonly `string`\[\] |
###### Returns
`void`
##### set()
###### Call Signature
> **set**(`key`, `value`): `void`
Immediately update the initialized buffer. `null` is durable; `undefined` is accepted for compatibility but treated as absent by reads and is not portable.
###### Parameters
| Parameter | Type |
| --- | --- |
| `key` | `string` |
| `value` | `unknown` |
###### Returns
`void`
###### Call Signature
> **set**(`values`): `void`
Coherently update several related values in the initialized buffer.
###### Parameters
| Parameter | Type |
| --- | --- |
| `values` | `Record`<`string`, `unknown`\> |
###### Returns
`void`
### `KnownEventName`
> **KnownEventName** = `"$heatmaps_data"` | `"$opt_in"` | `"$exception"` | `"$$heatmap"` | `"$web_vitals"` | `"$dead_click"` | `"$dead_swipe"` | `"$autocapture"` | `"$copy_autocapture"` | `"$rageclick"`
These are known events PostHog events that can be processed by the `beforeCapture` function That means PostHog functionality does not rely on receiving 100% of these for calculations So, it is safe to sample them to reduce the volume of events sent to PostHog
### `KnownUnsafeEditableEvent`
> **KnownUnsafeEditableEvent** = *typeof* `knownUnsafeEditableEvent`\[`number`\]
These events can be processed by the `beforeCapture` function but can cause unexpected confusion in data.
Some features of PostHog rely on receiving 100% of these events
### `KnownUnsafeEditableEvent`
> **KnownUnsafeEditableEvent** = `"$set"` | `"$pageview"` | `"$pageleave"` | `"$identify"` | `"$groupidentify"` | `"$create_alias"` | `"$feature_flag_called"`
Known events that can be safely edited in beforeCapture without breaking PostHog functionality
### `LinkSurveyQuestion`
- `SurveyQuestionBase`
#### Properties
| Property | Type | Inherited from |
| --- | --- | --- |
| `branching?` | `NextQuestionBranching` \| `EndBranching` \| `ResponseBasedBranching` \| `SpecificQuestionBranching` | `SurveyQuestionBase`.`branching` |
| `buttonText?` | `string` | `SurveyQuestionBase`.`buttonText` |
| `description?` | `string` \| `null` | `SurveyQuestionBase`.`description` |
| `descriptionContentType?` | `SurveyQuestionDescriptionContentType` | `SurveyQuestionBase`.`descriptionContentType` |
| `id?` | `string` | `SurveyQuestionBase`.`id` |
| `link?` | `string` \| `null` | \- |
| `optional?` | `boolean` | `SurveyQuestionBase`.`optional` |
| `question` | `string` | `SurveyQuestionBase`.`question` |
| `translations?` | `Record`<`string`, `SurveyQuestionTranslation`\> | `SurveyQuestionBase`.`translations` |
| `type` | `"link"` | \- |
| `validation?` | `SurveyValidationRule`\[\] | `SurveyQuestionBase`.`validation` |
### `Listener`
> **Listener**<`T`\> = (`handler`) => `Disposable`
Call it with a handler to start listening; dispose the returned Disposable to stop. There is one `Listener` per event type, so every event carries its own payload type. The handler is called synchronously, and stateful listeners may replay their current value during registration when documented. The returned disposable unregisters it from future payloads.
#### Type Parameters
| Type Parameter |
| --- |
| `T` |
#### Parameters
| Parameter | Type |
| --- | --- |
| `handler` | (`payload`) => `void` |
#### Returns
`Disposable`
### `LogAttributes`
> **LogAttributes** = `Record`<`string`, `LogAttributeValue`\>
### `LogAttributeValue`
> **LogAttributeValue** = `string` | `number` | `boolean` | `null` | `undefined` | `unknown`\[\] | `Record`<`string`, `unknown`\>
### `LogCaptureOptions`
Options for the captureLog API and posthog.logger convenience methods.
#### Extended by
- `LogsConfig`
- `BrowserLogsConfig`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `beforeSend?` | `BeforeSendLogFn` \| `BeforeSendLogFn`\[\] | Pre-send filter for log records, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a record (return `null` to drop) before it enters the rate cap or the buffer. |
| `environment?` | `string` | The deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. |
| `flushIntervalMs?` | `number` | Flush interval in milliseconds for batched log records. **Default** `3000` |
| `maxBufferSize?` | `number` | Maximum number of log records to buffer before forcing a flush. The queue may grow beyond this while a flush is in flight (e.g. during a synchronous burst) and is bounded separately by the per-interval rate cap. **Default** `100` |
| `maxLogsPerInterval?` | `number` | Maximum number of log records accepted per flush interval. Subsequent calls within the same window are dropped with a single warning, protecting against runaway loggers flooding the network. Also sizes the in-memory buffer's eviction backstop, so a window's worth of records is held while a flush is in flight; raising it raises the worst-case in-memory footprint. **Default** `1000` |
| `resourceAttributes?` | `LogAttributes` | Additional resource attributes applied to all log records. These describe the service/deployment, not individual log entries. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. **Example** `{ 'host.name': 'web-01', 'cloud.region': 'us-east-1' }` |
| `serviceName?` | `string` | The service name for log records. Maps to the OTel resource attribute 'service.name'. **Default** `'unknown_service'` |
| `serviceVersion?` | `string` | The service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. |
### `Logger`
Per-level convenience logger. Each method captures a structured log record at the corresponding severity, equivalent to `posthog.captureLog({ body, level, attributes })`.
#### Example
```typescript
posthog.logger.info('checkout completed', { order_id: 'ord_789' })
posthog.logger.error('payment failed', { code: 'E001' })
```
#### Methods
##### debug()
> **debug**(`body`, `attributes?`): `void`
Debug-level detail. Verbose, only useful while diagnosing.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
##### error()
> **error**(`body`, `attributes?`): `void`
Error. Operation failed; the app may continue.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
##### fatal()
> **fatal**(`body`, `attributes?`): `void`
Fatal. Operation failed; the app likely cannot continue.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
##### info()
> **info**(`body`, `attributes?`): `void`
Informational. Normal app events worth recording.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
##### trace()
> **trace**(`body`, `attributes?`): `void`
Lowest severity. Trace-level diagnostic detail.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
##### warn()
> **warn**(`body`, `attributes?`): `void`
Warning. Something unexpected but non-fatal.
###### Parameters
| Parameter | Type |
| --- | --- |
| `body` | `string` |
| `attributes?` | `LogAttributes` |
###### Returns
`void`
### `Logger`
> **Logger** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `createLogger` | (`prefix`) => `Logger` |
| `critical` | (...`args`) => `void` |
| `debug` | (...`args`) => `void` |
| `error` | (...`args`) => `void` |
| `info` | (...`args`) => `void` |
| `warn` | (...`args`) => `void` |
### `LogsConfig`
Logs configuration options
#### Extends
- `LogCaptureOptions`
#### Properties
| Property | Type | Description | Inherited from |
| --- | --- | --- | --- |
| `beforeSend?` | `BeforeSendLogFn` \| `BeforeSendLogFn`\[\] | Pre-send filter for log records, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a record (return `null` to drop) before it enters the rate cap or the buffer. | `LogCaptureOptions`.`beforeSend` |
| `captureConsoleLogs?` | `boolean` | Automatically capture `console.*` calls as structured log records. Review console output before enabling, as messages can include sensitive values written by your code or by third-party libraries. **Default** `undefined` | \- |
| `environment?` | `string` | The deployment environment for log records (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. | `LogCaptureOptions`.`environment` |
| `flushIntervalMs?` | `number` | Flush interval in milliseconds for batched log records. **Default** `3000` | `LogCaptureOptions`.`flushIntervalMs` |
| `maxBufferSize?` | `number` | Maximum number of log records to buffer before forcing a flush. The queue may grow beyond this while a flush is in flight (e.g. during a synchronous burst) and is bounded separately by the per-interval rate cap. **Default** `100` | `LogCaptureOptions`.`maxBufferSize` |
| `maxLogsPerInterval?` | `number` | Maximum number of log records accepted per flush interval. Subsequent calls within the same window are dropped with a single warning, protecting against runaway loggers flooding the network. Also sizes the in-memory buffer's eviction backstop, so a window's worth of records is held while a flush is in flight; raising it raises the worst-case in-memory footprint. **Default** `1000` | `LogCaptureOptions`.`maxLogsPerInterval` |
| `resourceAttributes?` | `LogAttributes` | Additional resource attributes applied to all log records. These describe the service/deployment, not individual log entries. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. **Example** `{ 'host.name': 'web-01', 'cloud.region': 'us-east-1' }` | `LogCaptureOptions`.`resourceAttributes` |
| `serviceName?` | `string` | The service name for log records. Maps to the OTel resource attribute 'service.name'. **Default** `'unknown_service'` | `LogCaptureOptions`.`serviceName` |
| `serviceVersion?` | `string` | The service version for log records (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. | `LogCaptureOptions`.`serviceVersion` |
### `LogSdkContext`
SDK-internal context the host SDK passes to `buildOtlpLogRecord` at capture time. Each SDK populates the fields that apply to it: browser fills `currentUrl`, mobile fills `screenName` / `appState`. Missing fields are omitted from the OTLP record (no stray attributes).
Internal to `@posthog/core` — customers don't see this in autocomplete.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `activeFeatureFlags?` | `string`\[\] | \- |
| `appState?` | `"foreground"` \| `"background"` | Mobile-only — app foreground/background state at capture time |
| `currentUrl?` | `string` | Web-only — current page URL |
| `distinctId?` | `string` | \- |
| `lastActivityTimestamp?` | `number` | Web-only — ms epoch of the most recent session activity |
| `screenName?` | `string` | Mobile-only — current screen / view name |
| `sessionId?` | `string` | \- |
| `sessionStartTimestamp?` | `number` | Web-only — ms epoch when the current session started |
| `windowId?` | `string` | Web-only — current window id |
### `LogSeverityLevel`
> **LogSeverityLevel** = `"trace"` | `"debug"` | `"info"` | `"warn"` | `"error"` | `"fatal"`
Log capture types
### `MarkAsReadResponse`
Response from marking messages as read
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `success` | `boolean` | Whether the operation was successful |
| `unread_count` | `number` | Number of unread messages (should be 0 after marking as read) |
### `MaskInputOptions`
Mask input options for session recording
#### Properties
| Property | Type |
| --- | --- |
| `color?` | `boolean` |
| `date?` | `boolean` |
| `datetime-local?` | `boolean` |
| `email?` | `boolean` |
| `hidden?` | `boolean` |
| `month?` | `boolean` |
| `number?` | `boolean` |
| `password?` | `boolean` |
| `range?` | `boolean` |
| `search?` | `boolean` |
| `select?` | `boolean` |
| `tel?` | `boolean` |
| `text?` | `boolean` |
| `textarea?` | `boolean` |
| `time?` | `boolean` |
| `url?` | `boolean` |
| `week?` | `boolean` |
### `Message`
A message in a conversation
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `author_name?` | `string` | Display name of the message author |
| `author_type` | `MessageAuthorType` | Type of the message author |
| `content` | `string` | The message content as plain text (fallback) |
| `created_at` | `string` | ISO timestamp when the message was created |
| `id` | `string` | Unique identifier for the message |
| `is_private` | `boolean` | Whether this is an internal note (not shown to customer) |
| `rich_content?` | `TipTapDoc` | Rich content in TipTap JSON format (preferred for rendering) Falls back to `content` if missing or invalid |
### `MessageAuthorType`
> **MessageAuthorType** = `"customer"` | `"AI"` | `"human"`
Author types for messages in a conversation
### `MetricAttributes`
> **MetricAttributes** = `Record`<`string`, `MetricAttributeValue`\>
### `MetricAttributeValue`
> **MetricAttributeValue** = `string` | `number` | `boolean`
Metric attribute values are restricted to scalars. Every distinct attribute-value combination creates a new metric series, so high-cardinality values (user IDs, request IDs, URLs) must not be used as attributes — put those on logs or events instead.
### `MetricSample`
A captured metric as seen by `beforeSend`, before aggregation. Mutating `name`, `value`, `unit`, `attributes`, or `bounds` changes what gets aggregated; returning `null` drops the sample.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `attributes?` | `MetricAttributes` | \- |
| `bounds?` | `number`\[\] | Histogram bucket boundaries. See HistogramOptions.bounds. Only histograms use them. |
| `name` | `string` | \- |
| `type` | `MetricType` | \- |
| `unit?` | `string` | \- |
| `value` | `number` | \- |
### `MetricsConfig`
Options for the posthog.metrics API (count, gauge, histogram). Shared by every SDK; browser-only options live in `BrowserMetricsConfig`.
#### Extended by
- `BrowserMetricsConfig`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `beforeSend?` | `BeforeSendMetricFn` \| `BeforeSendMetricFn`\[\] | Pre-aggregation filter for metric samples, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a sample (return `null` to drop) before it is aggregated. |
| `environment?` | `string` | The deployment environment for metric series (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'. |
| `flushIntervalMs?` | `number` | How often the aggregated window is flushed, in milliseconds. Samples are folded into per-series aggregates in memory between flushes — one data point per series per window, no matter how many calls. The browser SDK defaults to 60000: every tab of an app writes to the same series, so a longer window keeps busy series under the backend's per-series point limit. **Default** `10000 (60000 in the browser)` |
| `maxSeriesPerFlush?` | `number` | Cardinality guardrail: maximum distinct series (name + type + unit + attribute combination) held per flush window. Samples for series beyond the cap are dropped with a single warning per window. **Default** `1000` |
| `resourceAttributes?` | `MetricAttributes` | Additional resource attributes applied to every metrics batch. These describe the service/deployment, not individual series. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. **Example** `{ 'host.name': 'web-01', 'cloud.region': 'us-east-1' }` |
| `serviceName?` | `string` | The service name for metric series. Maps to the OTel resource attribute 'service.name'. **Default** `'unknown_service'` |
| `serviceVersion?` | `string` | The service version for metric series (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'. |
### `MetricType`
> **MetricType** = `"count"` | `"gauge"` | `"histogram"`
### `MultipleSurveyQuestion`
- `SurveyQuestionBase`
#### Properties
| Property | Type | Inherited from |
| --- | --- | --- |
| `branching?` | `NextQuestionBranching` \| `EndBranching` \| `ResponseBasedBranching` \| `SpecificQuestionBranching` | `SurveyQuestionBase`.`branching` |
| `buttonText?` | `string` | `SurveyQuestionBase`.`buttonText` |
| `choices` | `string`\[\] | \- |
| `description?` | `string` \| `null` | `SurveyQuestionBase`.`description` |
| `descriptionContentType?` | `SurveyQuestionDescriptionContentType` | `SurveyQuestionBase`.`descriptionContentType` |
| `hasOpenChoice?` | `boolean` | \- |
| `id?` | `string` | `SurveyQuestionBase`.`id` |
| `optional?` | `boolean` | `SurveyQuestionBase`.`optional` |
| `question` | `string` | `SurveyQuestionBase`.`question` |
| `shuffleOptions?` | `boolean` | \- |
| `skipSubmitButton?` | `boolean` | \- |
| `translations?` | `Record`<`string`, `SurveyQuestionTranslation`\> | `SurveyQuestionBase`.`translations` |
| `type` | `"multiple_choice"` \| `"single_choice"` | \- |
| `validation?` | `SurveyValidationRule`\[\] | `SurveyQuestionBase`.`validation` |
### `NetworkMetricsConfig`
Options for automatic HTTP and HTTPS `fetch` and `XMLHttpRequest` duration metrics. Recording never changes the request or its settlement. Fetch returns a derived promise so rejected requests remain observable to the caller.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `attributes?` | (`request`, `response`) => `MetricAttributes` \| `undefined` | Adds attributes to each recorded request. The result is merged over the default attributes, so it can also replace them, e.g. to set `url.template` to a route template. Keep attribute values low-cardinality. The default attributes follow the OTel HTTP client semantic conventions: `http.request.method`, `server.address`, `server.port`, `url.scheme`, `url.template`, `http.response.status_code` and `error.type`. The default `url.template` replaces each all-digit or uuid-like path segment with `:id`. Ids that carry a prefix or suffix, such as `order-123` or `38217.pdf`, are kept as they are, so return your own `url.template` for those routes. `http.response.status_code` is only set when a response arrived. `error.type` is the status code for a 4xx or 5xx response, the error name (e.g. `TypeError`) for a rejected fetch, or `_OTHER` when no response arrived and there is no error. |
| `name?` | `string` \| ((`request`) => `string` \| `null` \| `undefined`) | The metric name. A string is used for every request. A function is called once per request; return a falsy value to skip that request. **Default** `'http.client.request.duration'` |
### `NetworkMetricsRequest`
The request a network metric describes.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `method` | `string` | The HTTP method in upper case, e.g. 'GET'. |
| `url` | `string` | The full request URL, including the query string. |
### `NetworkMetricsResponse`
How a network request ended.
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `durationMs` | `number` | How long the request took, in milliseconds. The end boundary follows the transport: a `fetch` is measured to its response headers, an `XMLHttpRequest` to the end of its response body. |
| `status` | `number` \| `undefined` | The HTTP status code. `undefined` when the request failed before a response arrived. |
### `NetworkRecordOptions`
> **NetworkRecordOptions** = `object`
#### Properties
| Property | Type | Description |
| --- | --- | --- |
| `initiatorTypes?` | `InitiatorType`\[\] | \- |
| `maskRequestFn?` | (`data`) => `CapturedNetworkRequest` \| `undefined` | \- |
| `payloadHostDenyList?` | `string`\[\] | some domains we should never record the payload for example other companies session replay ingestion payloads aren't super useful but are gigantic if this isn't provided we use a default list if this is provided - we add the provided list to the default list i.e. we never record the payloads on the default deny list |
| `payloadSizeLimitBytes` | `number` | the maximum size of the request/response body to record NB this will be at most 1MB even if set larger |
| `performanceEntryTypeToObserve` | `string`\[\] | the PerformanceObserver will only observe these entry types |
| `recordBody?` | `boolean` \| `string`\[\] \| { `request`: `boolean` \| `string`\[\]; `response`: `boolean` \| `string`\[\]; } | \- |
| `recordHeaders?` | `boolean` \| { `request`: `boolean`; `response`: `boolean`; } | \- |
| `recordInitialRequests?` | `boolean` | \- |
| `recordPerformance?` | `boolean` | whether to record PerformanceEntry events for network requests |
| `streamNetworkBody?` | `boolean` | when true, read bodies through a streaming reader that stops at payloadSizeLimitBytes instead of buffering the whole body and then enforcing the limit. Reads only a clone of the body, so it never consumes the stream the page itself reads. **Default** `false` |
### `NetworkRequest`
> **NetworkRequest** = `object`
#### Deprecated
- use CapturedNetworkRequest instead
#### Properties
| Property | Type |
| --- | --- |
| `url` | `string` |
### `NextOptions`
> **NextOptions** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `revalidate` | `false` \| `0` \| `number` |
| `tags` | `string`\[\] |
### `NextOptions`
> **NextOptions** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `revalidate` | `false` \| `0` \| `number` |
| `tags` | `string`\[\] |
### `NextQuestionBranching`
| Property | Type |
| --- | --- |
| `type` | `"next_question"` |
### `OtlpAnyValue`
| Property | Type | Description |
| --- | --- | --- |
| `arrayValue?` | `object` | \- |
| `arrayValue.values` | `OtlpAnyValue`\[\] | \- |
| `boolValue?` | `boolean` | \- |
| `doubleValue?` | `number` | \- |
| `intValue?` | `string` \| `number` | proto3 JSON maps int64 to a string, which is the form the SDK emits. `number` stays valid because encoded records persist in the logs queue: one written by an earlier version rehydrates in the numeric form and is re-sent unchanged. The wire format accepts both. |
| `kvlistValue?` | `object` | \- |
| `kvlistValue.values` | `OtlpKeyValue`\[\] | \- |
| `stringValue?` | `string` | \- |
### `OtlpExemplar`
A sampled measurement linked to the span it was recorded in. IDs are lowercase hex.
#### Properties
| Property | Type |
| --- | --- |
| `asDouble` | `number` |
| `filteredAttributes` | `OtlpKeyValue`\[\] |
| `spanId` | `string` |
| `timeUnixNano` | `string` |
| `traceId` | `string` |
### `OtlpHistogramDataPoint`
| Property | Type | Description |
| --- | --- | --- |
| `attributes` | `OtlpKeyValue`\[\] | \- |
| `bucketCounts` | `number`\[\] | \- |
| `count` | `number` | Plain JSON numbers, not strings — see the ingest's u64 handling. |
| `exemplars?` | `OtlpExemplar`\[\] | \- |
| `explicitBounds` | `number`\[\] | \- |
| `max` | `number` | \- |
| `min` | `number` | \- |
| `startTimeUnixNano` | `string` | \- |
| `sum` | `number` | \- |
| `timeUnixNano` | `string` | \- |
### `OtlpKeyValue`
| Property | Type |
| --- | --- |
| `key` | `string` |
| `value` | `OtlpAnyValue` |
### `OtlpLogRecord`
| Property | Type |
| --- | --- |
| `attributes` | `OtlpKeyValue`\[\] |
| `body` | `object` |
| `body.stringValue` | `string` |
| `flags?` | `number` |
| `observedTimeUnixNano` | `string` |
| `severityNumber` | `number` |
| `severityText` | `OtlpSeverityText` |
| `spanId?` | `string` |
| `timeUnixNano` | `string` |
| `traceId?` | `string` |
### `OtlpLogsPayload`
| Property | Type |
| --- | --- |
| `resourceLogs` | `object`\[\] |
### `OtlpMetric`
| Property | Type |
| --- | --- |
| `gauge?` | `object` |
| `gauge.dataPoints` | `OtlpNumberDataPoint`\[\] |
| `histogram?` | `object` |
| `histogram.aggregationTemporality` | `number` |
| `histogram.dataPoints` | `OtlpHistogramDataPoint`\[\] |
| `name` | `string` |
| `sum?` | `object` |
| `sum.aggregationTemporality` | `number` |
| `sum.dataPoints` | `OtlpNumberDataPoint`\[\] |
| `sum.isMonotonic` | `boolean` |
| `unit?` | `string` |
### `OtlpMetricsPayload`
| Property | Type |
| --- | --- |
| `resourceMetrics` | `object`\[\] |
### `OtlpNumberDataPoint`
| Property | Type | Description |
| --- | --- | --- |
| `asDouble` | `number` | \- |
| `attributes` | `OtlpKeyValue`\[\] | \- |
| `exemplars?` | `OtlpExemplar`\[\] | \- |
| `startTimeUnixNano?` | `string` | \- |
| `timeUnixNano` | `string` | Unix nanos as a decimal string (uint64 doesn't fit in JS Number). |
### `OtlpSeverityEntry`
| Property | Type |
| --- | --- |
| `number` | `number` |
| `text` | `OtlpSeverityText` |
### `OtlpSeverityText`
> **OtlpSeverityText** = `"TRACE"` | `"DEBUG"` | `"INFO"` | `"WARN"` | `"ERROR"` | `"FATAL"`
### `OverrideConfig`
> **OverrideConfig** = `object`
#### Properties
| Property | Type |
| --- | --- |
| `event_trigger` | `boolean` |
| `linked_flag` | `boolean` |
| `sampling` | `boolean` |
| `url_trigger` | `boolean` |
### `OverrideFeatureFlagsOptions`
> **OverrideFeatureFlagsOptions** = `boolean` | `string`\[\] | `FeatureFlagOverrides` | `FeatureFlagOverrideOptions`
Options for overriding feature flags on the client-side.
Can be:
- `false` to clear all overrides
- `string[]` to enable a list of flags
- `FeatureFlagOverrides` to set variants directly
- `FeatureFlagOverrideOptions` for granular control over flags and payloads
### `PerformanceCaptureConfig`
| Property | Type | Description |
| --- | --- | --- |
| `__preview_web_vitals_soft_navs?` | `boolean` | Scope web vitals metrics to the browser's Soft Navigation entries, so that client-side route changes in single-page apps each start a fresh measurement window instead of accumulating against the original hard-navigation timestamp. Without this, an SPA's LCP observer keeps treating the "largest paint so far" as belonging to the initial page load across every subsequent route change, which inflates LCP (and the other metrics) by the time spent on the app. This is a preview option (opt-in) because it relies on Chrome's Soft Navigation Detection API, which is still experimental. When enabled, PostHog loads a pinned stable web-vitals 6.x bundle and passes `reportSoftNavs` to the observers. The default path remains on the existing web-vitals 5.x bundle. In browsers without soft-nav support, metrics fall back to their existing hard-navigation behavior. **Default** `false` |
| `__web_vitals_max_value?` | `number` | We observe very large values reported by the Chrome web vitals library These outliers are likely not real, useful values, and we exclude them You can set this to 0 in order to include all values, NB this is not recommended **Default** `15 * 60 * 1000 (15 minutes)` |
| `network_timing?` | `boolean` | Works with session replay to use the browser's native performance observer to capture performance metrics |
| `web_vitals?` | `boolean` | Use chrome's web vitals library to wrap fetch and capture web vitals When `cookieless_mode` is active, there is no client-side SessionIdManager; vitals are still captured. Nested `$web_vitals_*_event` payloads omit `$session_id` / `$window_id`; PostHog ingestion assigns `$session_id` server-side for cookieless traffic when project cookieless settings are enabled (same as other events). |
| `web_vitals_allowed_metrics?` | `SupportedWebVitalsMetrics`\[\] | By default all 4 metrics are captured You can set this config to restrict which metrics are captured e.g. \['CLS', 'FCP'\] to only capture those two metrics NB setting this does not override whether the capture is enabled **Default** `['LCP', 'CLS', 'FCP', 'INP']` |
| `web_vitals_attribution?` | `boolean` \| `SupportedWebVitalsMetrics`\[\] | Which web vitals metrics include attribution data. Attribution names the cause of a metric, such as the slow interaction target for INP or the load-phase breakdown for LCP, which is what makes a slow number diagnosable. Pass `true` to attribute all metrics, `false` for none, or an array to name them. The default attributes INP and LCP only. CLS is excluded by default because its attribution holds detached DOM nodes and can leak memory in single-page apps. **Default** `['INP', 'LCP']` |
| `web_vitals_delayed_flush_ms?` | `number` | We delay flushing web vitals metrics to reduce the number of events we send This is the maximum time we will wait before sending the metrics **Default** `5000` |
### `PersistentStore`
| Property | Type |
| --- | --- |
| `_error` | (`error`) => `void` |
| `_get` | (`name`) => `any` |
| `_is_supported` | () => `boolean` |
| `_parse` | (`name`) => `any` |
| `_remove` | (`name`, `cross_subdomain?`) => `void` |
| `_set` | (`name`, `value`, `expire_days?`, `cross_subdomain?`, `secure?`, `debug?`) => `boolean` |
### `PostHog`
The PostHog instance interface.
This can be used to type `window.posthog` when loading PostHog via a `