PostHog JavaScript Web SDK
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
init
public
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
// basic initializationposthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com'})
Returns
Type |
---|
PostHog |
Other methods
alias
public
Creates an alias linking two distinct user identifiers.
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.
Best Practices - Call alias() when a unique ID is first created (e.g., account creation) - Should only be called once per user (except for chaining) - Multiple aliases can map to the same original ID
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
// link anonymous user to account on signupposthog.alias('user_12345')
Returns
Type | |
---|---|
Union of | CaptureResult |
void | |
number |
calculateEventProperties
public
calculateEventProperties
This method is used internally to calculate the event properties before sending it to PostHog. It can also be used by integrations (e.g. Segment) to enrich events with PostHog properties before sending them to Segment, which is required for some PostHog products to work correctly. (e.g. to have a correct $session_id property).
Parameters
Name | Type |
---|---|
eventName | string |
The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', '$pageview', etc. | |
eventProperties | Properties |
The properties to include with the event. | |
timestamp? | Date |
The timestamp of the event, e.g. for calculating time on page. If not set, it'll automatically be set to the current time. | |
uuid? | string |
The uuid of the event, e.g. for storing the $pageview ID. | |
readOnly? | boolean |
Set this if you do not intend to actually send the event, and therefore do not want to update internal state e.g. session timeout |
Examples
// Generated example for calculateEventPropertiesposthog.calculateEventProperties();
Returns
Type |
---|
Properties |
canRenderSurvey
deprecated
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.
Parameters
Name | Type |
---|---|
surveyId | string |
The ID of the survey to check. |
Examples
// Generated example for canRenderSurveyposthog.canRenderSurvey();
Returns
Type | |
---|---|
Union of | SurveyRenderReason |
null |
canRenderSurveyAsync
public
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
// Generated example for canRenderSurveyAsyncposthog.canRenderSurveyAsync();
Returns
Type |
---|
Promise<SurveyRenderReason> |
capture
public
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
// basic event captureposthog.capture('cta-button-clicked', {button_name: 'Get Started',page: 'homepage'})
Returns
Type | |
---|---|
Union of | CaptureResult |
undefined |
captureException
public
Capture a caught exception manually
Parameters
Name | Type |
---|---|
error | unknown |
additionalProperties? | Properties |
Examples
// Generated example for captureExceptionposthog.captureException();
Returns
Type |
---|
void |
captureTraceFeedback
public
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
// Generated example for captureTraceFeedbackposthog.captureTraceFeedback();
Returns
Type |
---|
void |
captureTraceMetric
public
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
// Generated example for captureTraceMetricposthog.captureTraceMetric();
Returns
Type |
---|
void |
clear_opt_in_out_capturing
public
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
Examples
// Generated example for clear_opt_in_out_capturingposthog.clear_opt_in_out_capturing();
Returns
Type |
---|
void |
createPersonProfile
public
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'.
Examples
// Generated example for createPersonProfileposthog.createPersonProfile();
Returns
Type |
---|
void |
debug
public
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
// enable debug modeposthog.debug(true)
Returns
Type |
---|
void |
get_distinct_id
public
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
// get the current user IDconst userId = posthog.get_distinct_id()console.log('Current user:', userId)
Returns
Type |
---|
string |
get_property
public
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
// grab value for '$user_id' after the posthog library has loadedposthog.init('<YOUR PROJECT TOKEN>', {loaded: function(posthog) {user_id = posthog.get_property('$user_id');}});
Returns
Type | |
---|---|
Union of | Property |
undefined |
get_session_id
public
Returns the current session_id.
NOTE: This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.
Examples
// Generated example for get_session_idposthog.get_session_id();
Returns
Type |
---|
string |
get_session_replay_url
public
Returns the Replay url for the current session.
Parameters
Name | Type |
---|---|
options? | {
withTimestamp?: boolean;
timestampLookBack?: number;
} |
Options for the url |
Examples
// Generated example for get_session_replay_urlposthog.get_session_replay_url();
Returns
Type |
---|
string |
getActiveMatchingSurveys
public
Get surveys that should be enabled for the current user.
Parameters
Name | Type |
---|---|
callback | SurveyCallback |
forceReload? | boolean |
Examples
// Generated example for getActiveMatchingSurveysposthog.getActiveMatchingSurveys();
Returns
Type |
---|
void |
getEarlyAccessFeatures
public
Get the list of early access features. To check enrollment status, use isFeatureEnabled
.
Parameters
Name | Type |
---|---|
callback | EarlyAccessFeatureCallback |
force_reload? | boolean |
stages? | EarlyAccessFeatureStage[] |
Examples
// Generated example for getEarlyAccessFeaturesposthog.getEarlyAccessFeatures();
Returns
Type |
---|
void |
getFeatureFlag
public
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
// check boolean flagif (posthog.getFeatureFlag('new-feature')) {// show new feature}
Returns
Type | |
---|---|
Union of | boolean |
string | |
undefined |
getFeatureFlagPayload
public
Parameters
Name | Type |
---|---|
key | string |
Examples
// Generated example for getFeatureFlagPayloadposthog.getFeatureFlagPayload();
Returns
Type |
---|
JsonType |
getGroups
public
Examples
// Generated example for getGroupsposthog.getGroups();
Returns
Type |
---|
Record<string, any> |
getPageViewId
public
Examples
// Generated example for getPageViewIdposthog.getPageViewId();
Returns
Type | |
---|---|
Union of | string |
undefined |
getSessionProperty
public
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
// grab value for 'user_id' after the posthog library has loadedposthog.init('YOUR PROJECT TOKEN', {loaded: function(posthog) {user_id = posthog.getSessionProperty('user_id');}});
Returns
Type | |
---|---|
Union of | Property |
undefined |
Examples
// Generated example for getSurveysposthog.getSurveys();
Returns
Type |
---|
void |
group
public
Associates the user with a group for group-based analytics.
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
// associate user with an organizationposthog.group('organization', 'org_12345', {name: 'Acme Corp',plan: 'enterprise'})
Returns
Type |
---|
void |
has_opted_in_capturing
public
Checks if the user has opted into data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
Examples
if (posthog.has_opted_in_capturing()) {// show analytics features}
Returns
Type |
---|
boolean |
has_opted_out_capturing
public
Checks if the user has opted out of data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
Examples
if (posthog.has_opted_out_capturing()) {// disable analytics features}
Returns
Type |
---|
boolean |
identify
public
Associates a user with a unique identifier instead of an auto-generated ID.
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).
User Merging Behavior - If the user is already identified, calling identify again will not merge users - To merge identified users, use the alias
method instead - Use reset()
to start a fresh session before identifying a different user
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
// basic identificationposthog.identify('user_12345')
Returns
Type |
---|
void |
isFeatureEnabled
public
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
// simple feature flag checkif (posthog.isFeatureEnabled('new-checkout')) {showNewCheckout()}
Returns
Type | |
---|---|
Union of | boolean |
undefined |
loadToolbar
public
returns a boolean indicating whether the toolbar loaded
Parameters
Name | Type |
---|---|
params | ToolbarParams |
Examples
// Generated example for loadToolbarposthog.loadToolbar();
Returns
Type |
---|
boolean |
on
public
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' |
cb | (...args: any[]) => void |
Examples
// Generated example for onposthog.on();
Returns
Type |
---|
() => void |
onFeatureFlags
public
Parameters
Name | Type |
---|---|
callback | FeatureFlagsCallback |
Examples
// Generated example for onFeatureFlagsposthog.onFeatureFlags();
Returns
Type |
---|
() => void |
onSessionId
public
Parameters
Name | Type |
---|---|
callback | SessionIdChangedCallback |
Examples
// Generated example for onSessionIdposthog.onSessionId();
Returns
Type |
---|
() => void |
onSurveysLoaded
public
Parameters
Name | Type |
---|---|
callback | SurveyCallback |
Examples
// Generated example for onSurveysLoadedposthog.onSurveysLoaded();
Returns
Type |
---|
() => void |
opt_in_capturing
public
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
// simple opt-inposthog.opt_in_capturing()
Returns
Type |
---|
void |
opt_out_capturing
public
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
// opt user out (e.g., on privacy settings page)posthog.opt_out_capturing()
Returns
Type |
---|
void |
push
public
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).
Usage: posthog.push(['register', a: 'b' ]);
Parameters
Name | Type |
---|---|
item | SnippetArrayItem |
A [function_name, args...] array to be executed |
Examples
// Generated example for pushposthog.push();
Returns
Type |
---|
void |
register_for_session
public
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
// register session-specific propertiesposthog.register_for_session({current_page_type: 'checkout',ab_test_variant: 'control'})
Returns
Type |
---|
void |
register_once
public
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
// register once-only propertiesposthog.register_once({first_login_date: new Date().toISOString(),initial_referrer: document.referrer})
Returns
Type |
---|
void |
register
public
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
// register a single propertyposthog.register({ plan: 'premium' })
Returns
Type |
---|
void |
reloadFeatureFlags
public
Examples
// Generated example for reloadFeatureFlagsposthog.reloadFeatureFlags();
Returns
Type |
---|
void |
renderSurvey
public
Render a survey on a specific element.
Parameters
Name | Type |
---|---|
surveyId | string |
selector | string |
Examples
// Generated example for renderSurveyposthog.renderSurvey();
Returns
Type |
---|
void |
reset
public
Resets all user data and starts a fresh session.
Notes:
⚠️ 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
// reset on user logoutfunction logout() {posthog.reset()// redirect to login page}
Returns
Type |
---|
void |
resetGroupPropertiesForFlags
public
Parameters
Name | Type |
---|---|
group_type? | string |
Examples
// Generated example for resetGroupPropertiesForFlagsposthog.resetGroupPropertiesForFlags();
Returns
Type |
---|
void |
resetGroups
public
Resets only the group properties of the user currently logged in.
Examples
// Generated example for resetGroupsposthog.resetGroups();
Returns
Type |
---|
void |
resetPersonPropertiesForFlags
public
Examples
// Generated example for resetPersonPropertiesForFlagsposthog.resetPersonPropertiesForFlags();
Returns
Type |
---|
void |
sessionRecordingStarted
public
returns a boolean indicating whether session recording is currently running
Examples
// Generated example for sessionRecordingStartedposthog.sessionRecordingStarted();
Returns
Type |
---|
boolean |
set_config
public
Updates the configuration of the PostHog instance.
Parameters
Name | Type |
---|---|
config | Partial<PostHogConfig> |
A dictionary of new configuration values to update |
Examples
// Generated example for set_configposthog.set_config();
Returns
Type |
---|
void |
setGroupPropertiesForFlags
public
Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type. For example: setGroupPropertiesForFlags('organization': name: 'CYZ', employees: '11' )
Parameters
Name | Type |
---|---|
properties | {
[type: string]: Properties;
} |
reloadFeatureFlags? | boolean |
Examples
// Generated example for setGroupPropertiesForFlagsposthog.setGroupPropertiesForFlags();
Returns
Type |
---|
void |
setPersonProperties
public
Sets properties on the person profile associated with the current distinct_id
.
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
// set user propertiesposthog.setPersonProperties({email: 'user@example.com',plan: 'premium'})
Returns
Type |
---|
void |
setPersonPropertiesForFlags
public
Set override person properties for feature flags. This is used when dealing with new persons / where you don't want to wait for ingestion to update user properties.
Parameters
Name | Type |
---|---|
properties | Properties |
reloadFeatureFlags? | boolean |
Examples
// Generated example for setPersonPropertiesForFlagsposthog.setPersonPropertiesForFlags();
Returns
Type |
---|
void |
startSessionRecording
public
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
// Generated example for startSessionRecordingposthog.startSessionRecording();
Returns
Type |
---|
void |
stopSessionRecording
public
turns session recording off, and updates the config option disable_session_recording to true
Examples
// Generated example for stopSessionRecordingposthog.stopSessionRecording();
Returns
Type |
---|
void |
toString
public
Examples
// Generated example for toStringposthog.toString();
Returns
Type |
---|
string |
unregister_for_session
public
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
// remove a session propertyposthog.unregister_for_session('current_flow')
Returns
Type |
---|
void |
unregister
public
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
// remove a super propertyposthog.unregister('plan_type')
Returns
Type |
---|
void |
updateEarlyAccessFeatureEnrollment
public
Opt the user in or out of an early access feature.
Parameters
Name | Type |
---|---|
key | string |
isEnrolled | boolean |
Examples
// Generated example for updateEarlyAccessFeatureEnrollmentposthog.updateEarlyAccessFeatureEnrollment();
Returns
Type |
---|
void |