PostHog JavaScript Web SDK
SDK Version:
PostHog
This is the SDK reference for the PostHog JavaScript Web SDK. You can learn more about example usage in the JavaScript Web SDK documentation. You can also follow framework specific guides to integrate PostHog into your project.
This SDK is designed for browser environments. Use the PostHog Node.js SDK for server-side usage.
Initialization methods
debugpublic
Enables or disables debug mode for detailed logging.
Notes:
Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding ?__posthog_debug=true to the URL.
Parameters
| Name | Type |
|---|---|
debug? | boolean |
If true, will enable debug mode. | |
Examples
Returns
| Type |
|---|
void |
getPageViewIdpublic
Returns the current page view ID.
Examples
Returns
| Type | |
|---|---|
| Union of | string |
undefined |
initpublic
Initializes a new instance of the PostHog capturing object.
Notes:
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
Parameters
| Name | Type |
|---|---|
token | string |
Your PostHog API token | |
config? | OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>> |
A dictionary of config options to override | |
name? | string |
The name for the new posthog instance that you want created | |
Examples
Returns
| Type |
|---|
PostHog |
set_configpublic
Updates the configuration of the PostHog instance.
Parameters
| Name | Type |
|---|---|
config | Partial<PostHogConfig> |
A dictionary of new configuration values to update | |
Examples
Returns
| Type |
|---|
void |
Capture methods
capturepublic
Captures an event with optional properties and configuration.
Notes:
You can capture arbitrary object-like values as events. Learn about capture best practices
Parameters
| Name | Type |
|---|---|
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 | |
Examples
Returns
| Type | |
|---|---|
| Union of | CaptureResult |
undefined |
onpublic
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
Parameters
| Name | Type |
|---|---|
event | 'eventCaptured' |
The event to listen for. | |
cb | (...args: any[]) => void |
The callback function to call when the event is emitted. | |
Examples
Returns
| Type |
|---|
() => void |
register_for_sessionpublic
Registers super properties for the current session only.
Notes:
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.
Parameters
| Name | Type |
|---|---|
properties | Properties |
An associative array of properties to store about the user | |
Examples
Returns
| Type |
|---|
void |
register_oncepublic
Registers super properties only if they haven't been set before.
Notes:
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.
Parameters
| Name | Type |
|---|---|
properties | Properties |
An associative array of properties to store about the user | |
default_value? | Property |
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 | |
Examples
Returns
| Type |
|---|
void |
registerpublic
Registers super properties that are included with all events.
Notes:
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.
Parameters
| Name | Type |
|---|---|
properties | Properties |
properties to store about the user | |
days? | number |
How many days since the user's last visit to store the super properties | |
Examples
Returns
| Type |
|---|
void |
unregister_for_sessionpublic
Removes a session super property from the current session.
Notes:
This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.
Parameters
| Name | Type |
|---|---|
property | string |
The name of the session super property to remove | |
Examples
Returns
| Type |
|---|
void |
unregisterpublic
Removes a super property from persistent storage.
Notes:
This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile.
Parameters
| Name | Type |
|---|---|
property | string |
The name of the super property to remove | |
Examples
Returns
| Type |
|---|
void |
Error tracking methods
captureExceptionpublic
Capture a caught exception manually
Parameters
| Name | Type |
|---|---|
error | unknown |
The error to capture | |
additionalProperties? | Properties |
Any additional properties to add to the error event | |
Examples
Returns
| Type | |
|---|---|
| Union of | CaptureResult |
undefined |
Feature flags methods
getEarlyAccessFeaturespublic
Get the list of early access features. To check enrollment status, use isFeatureEnabled. Learn more in the docs
Parameters
| Name | Type |
|---|---|
callback | EarlyAccessFeatureCallback |
The callback function will be called when the early access features are loaded. | |
force_reload? | boolean |
Whether to force a reload of the early access features. | |
stages? | EarlyAccessFeatureStage[] |
The stages of the early access features to load. | |
Examples
Returns
| Type |
|---|
void |
getFeatureFlagpublic
Gets the value of a feature flag for the current user.
Notes:
Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values.
Parameters
| Name | Type |
|---|---|
key | string |
options? | {
send_event?: boolean;
} |
(optional) If send_event: false, we won't send an $feature_flag_call event to PostHog. | |
Examples
Returns
| Type | |
|---|---|
| Union of | boolean |
string | |
undefined |
getFeatureFlagPayloadpublic
Get feature flag payload value matching key for user (supports multivariate flags).
Parameters
| Name | Type |
|---|---|
key | string |
Examples
Returns
| Type |
|---|
JsonType |
isFeatureEnabledpublic
Checks if a feature flag is enabled for the current user.
Notes:
Returns true if the flag is enabled, false if disabled, or undefined if not found. This is a convenience method that treats any truthy value as enabled.
Parameters
| Name | Type |
|---|---|
key | string |
options? | {
send_event: boolean;
} |
(optional) If send_event: false, we won't send an $feature_flag_call event to PostHog. | |
Examples
Returns
| Type | |
|---|---|
| Union of | boolean |
undefined |
onFeatureFlagspublic
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.
Parameters
| Name | Type |
|---|---|
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. | |
Examples
Returns
| Type |
|---|
() => void |
reloadFeatureFlagspublic
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
Examples
Returns
| Type |
|---|
void |
resetGroupPropertiesForFlagspublic
Resets the group properties for feature flags.
Parameters
| Name | Type |
|---|---|
group_type? | string |
Examples
Returns
| Type |
|---|
void |
resetPersonPropertiesForFlagspublic
Resets the person properties for feature flags.
Examples
Returns
| Type |
|---|
void |
setGroupPropertiesForFlagspublic
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
| Name | Type |
|---|---|
properties | {
[type: string]: Properties;
} |
The properties to override, the key of which is the group type. | |
reloadFeatureFlags? | boolean |
Whether to reload feature flags. | |
Examples
Returns
| Type |
|---|
void |
setPersonPropertiesForFlagspublic
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
| Name | Type |
|---|---|
properties | Properties |
The properties to override. | |
reloadFeatureFlags? | boolean |
Whether to reload feature flags. | |
Examples
Returns
| Type |
|---|
void |
updateEarlyAccessFeatureEnrollmentpublic
Opt the user in or out of an early access feature. Learn more in the docs
Parameters
| Name | Type |
|---|---|
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. | |
Examples
Returns
| Type |
|---|
void |
Identification methods
aliaspublic
Creates an alias linking two distinct user identifiers. Learn more about identifying users
Notes:
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.
Parameters
| Name | Type |
|---|---|
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. | |
Examples
Returns
| Type | |
|---|---|
| Union of | CaptureResult |
void | |
number |
createPersonProfilepublic
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
Examples
Returns
| Type |
|---|
void |
get_distinct_idpublic
Returns the current distinct ID for the user.
Notes:
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
Returns
| Type |
|---|
string |
get_propertypublic
Returns the value of a super property. Returns undefined if the property doesn't exist.
Notes:
get_property() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.
Parameters
| Name | Type |
|---|---|
property_name | string |
The name of the super property you want to retrieve | |
Examples
Returns
| Type | |
|---|---|
| Union of | Property |
undefined |
getGroupspublic
Returns the current groups.
Examples
Returns
| Type |
|---|
Record<string, any> |
getSessionPropertypublic
Returns the value of the session super property named property_name. If no such property is set, getSessionProperty() will return the undefined value.
Notes:
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.
Parameters
| Name | Type |
|---|---|
property_name | string |
The name of the session super property you want to retrieve | |
Examples
Returns
| Type | |
|---|---|
| Union of | Property |
undefined |
grouppublic
Associates the user with a group for group-based analytics. Learn more about groups
Notes:
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.
Parameters
| Name | Type |
|---|---|
groupType | string |
Group type (example: 'organization') | |
groupKey | string |
Group key (example: 'org::5') | |
groupPropertiesToSet? | Properties |
Optional properties to set for group | |
Examples
Returns
| Type |
|---|
void |
identifypublic
Associates a user with a unique identifier instead of an auto-generated ID. Learn more about identifying users
Notes:
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).
Parameters
| Name | Type |
|---|---|
new_distinct_id? | string |
A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used. | |
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. | |
Examples
Returns
| Type |
|---|
void |
onSessionIdpublic
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
| Name | Type |
|---|---|
callback | SessionIdChangedCallback |
The callback function will be called once a session id is present or when it or the window id are updated. | |
Examples
Returns
| Type |
|---|
() => void |
resetpublic
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
Parameters
| Name | Type |
|---|---|
reset_device_id? | boolean |
Examples
Returns
| Type |
|---|
void |
resetGroupspublic
Resets only the group properties of the user currently logged in. Learn more about groups
Examples
Returns
| Type |
|---|
void |
setPersonPropertiespublic
Sets properties on the person profile associated with the current distinct_id. Learn more about identifying users
Notes:
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.
Parameters
| Name | Type |
|---|---|
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. | |
Examples
Returns
| Type |
|---|
void |
LLM analytics methods
captureTraceFeedbackpublic
Capture written user feedback for a LLM trace. Numeric values are converted to strings.
Parameters
| Name | Type |
|---|---|
traceId | string | number |
The trace ID to capture feedback for. | |
userFeedback | string |
The feedback to capture. | |
Examples
Returns
| Type |
|---|
void |
captureTraceMetricpublic
Capture a metric for a LLM trace. Numeric values are converted to strings.
Parameters
| Name | Type |
|---|---|
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. | |
Examples
Returns
| Type |
|---|
void |
Privacy methods
clear_opt_in_out_capturingpublic
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
Examples
Returns
| Type |
|---|
void |
has_opted_in_capturingpublic
Checks if the user has opted into data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
Examples
Returns
| Type |
|---|
boolean |
has_opted_out_capturingpublic
Checks if the user has opted out of data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
Examples
Returns
| Type |
|---|
boolean |
is_capturingpublic
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 explicitly opted out.
Examples
Returns
| Type |
|---|
boolean |
opt_in_capturingpublic
Opts the user into data capturing and persistence.
Notes:
Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an $opt_in event unless disabled.
Parameters
| Name | Type |
|---|---|
options? | {
captureEventName?: EventName | null | false; /** event name to be used for capturing the opt-in action */
captureProperties?: Properties; /** set of properties to be captured along with the opt-in action */
} |
Examples
Returns
| Type |
|---|
void |
opt_out_capturingpublic
Opts the user out of data capturing and persistence.
Notes:
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.
Examples
Returns
| Type |
|---|
void |
Session replay methods
get_session_replay_urlpublic
Returns the Replay url for the current session.
Parameters
| Name | Type |
|---|---|
options? | {
withTimestamp?: boolean;
timestampLookBack?: number;
} |
Options for the url | |
Examples
Returns
| Type |
|---|
string |
sessionRecordingStartedpublic
returns a boolean indicating whether session recording is currently running
Examples
Returns
| Type |
|---|
boolean |
startSessionRecordingpublic
turns session recording on, and updates the config option disable_session_recording to false
Parameters
| Name | Type |
|---|---|
override? | {
sampling?: boolean;
linked_flag?: boolean;
url_trigger?: true;
event_trigger?: true;
} | 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. | |
Examples
Returns
| Type |
|---|
void |
stopSessionRecordingpublic
turns session recording off, and updates the config option disable_session_recording to true
Examples
Returns
| Type |
|---|
void |
Surveys methods
canRenderSurveydeprecated
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
| Name | Type |
|---|---|
surveyId | string |
The ID of the survey to check. | |
Examples
Returns
| Type | |
|---|---|
| Union of | SurveyRenderReason |
null |
canRenderSurveyAsyncpublic
Checks the feature flags associated with this Survey to see if the survey can be rendered.
Parameters
| Name | Type |
|---|---|
surveyId | string |
The ID of the survey to check. | |
forceReload? | boolean |
If true, the survey will be reloaded from the server, Default: false | |
Examples
Returns
| Type |
|---|
Promise<SurveyRenderReason> |
displaySurveypublic
Display a survey programmatically as either a popover or inline element.
Parameters
| Name | Type |
|---|---|
surveyId | string |
The survey ID to display | |
options? | DisplaySurveyOptions |
Display configuration | |
Examples
Returns
| Type |
|---|
void |
getActiveMatchingSurveyspublic
Get surveys that should be enabled for the current user. See fetching surveys documentation for more details.
Parameters
| Name | Type |
|---|---|
callback | SurveyCallback |
The callback function will be called when the surveys are loaded or updated. | |
forceReload? | boolean |
Whether to force a reload of the surveys. | |
Examples
Returns
| Type |
|---|
void |
getSurveyspublic
Get list of all surveys.
Parameters
| Name | Type |
|---|---|
callback | SurveyCallback |
Function that receives the array of surveys | |
forceReload? | boolean |
Optional boolean to force an API call for updated surveys | |
Examples
Returns
| Type |
|---|
void |
onSurveysLoadedpublic
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
| Name | Type |
|---|---|
callback | SurveyCallback |
The callback function will be called when surveys are loaded or updated. | |
Examples
Returns
| Type |
|---|
() => void |
renderSurveydeprecated
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
| Name | Type |
|---|---|
surveyId | string |
The ID of the survey to render. | |
selector | string |
The selector of the HTML element to render the survey on. | |
Examples
Returns
| Type |
|---|
void |
Toolbar methods
loadToolbarpublic
returns a boolean indicating whether the toolbar loaded
Parameters
| Name | Type |
|---|---|
params | ToolbarParams |
Examples
Returns
| Type |
|---|
boolean |
Other methods
PostHogpublic
Constructs a new instance of the PostHog class
Examples
Returns
| Type |
|---|
any |
get_explicit_consent_statuspublic
Returns the explicit consent status of the user.
Notes:
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.
Examples
Returns
| Type | |
|---|---|
| Union of | 'granted' |
'denied' | |
'pending' |
get_session_idpublic
Returns the current session_id.
Notes:
This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.
Examples
Returns
| Type |
|---|
string |
pushpublic
push() keeps the standard async-array-push behavior around after the lib is loaded. This is only useful for external integrations that do not wish to rely on our convenience methods (created in the snippet).
Parameters
| Name | Type |
|---|---|
item | SnippetArrayItem |
A [function_name, args...] array to be executed | |
Examples
Returns
| Type |
|---|
void |