references/posthog-js.md
PostHog JavaScript Web SDK
SDK Version: 1.363.4
Posthog-js allows you to automatically capture usage and send events to PostHog.
Categories
- Initialization
- Identification
- Capture
- Surveys
- Error tracking
- LLM analytics
- Privacy
- Session replay
- Feature flags
- Toolbar
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.
Other methods
PostHog()
Release Tag: public
Constructs a new instance of the PostHog class
Returns
any
Examples
// Generated example for PostHog
posthog.PostHog();
get_explicit_consent_status()
Release Tag: public
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.
Returns
Union of:
'granted''denied''pending'
Examples
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
}
get_session_id()
Release Tag: public
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.
Returns
string
Examples
// Generated example for get_session_id
posthog.get_session_id();
push()
Release Tag: 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).
Parameters
item(SnippetArrayItem) - A [function_name, args...] array to be executed
Returns
void
Examples
posthog.push(['register', { a: 'b' }]);
Identification methods
alias()
Release Tag: public
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
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
Union of:
CaptureResultvoidnumber
Examples
link anonymous user to account on signup
// link anonymous user to account on signup
posthog.alias('user_12345')
explicit alias with original ID
// explicit alias with original ID
posthog.alias('user_12345', 'anonymous_abc123')
createPersonProfile()
Release Tag: 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'. Learn more about person profiles
Returns
void
Examples
posthog.createPersonProfile()
get_distinct_id()
Release Tag: 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.
Returns
string
Examples
get the current user ID
// get the current user ID
const userId = posthog.get_distinct_id()
console.log('Current user:', userId)
use in loaded callback
// use in loaded callback
posthog.init('token', {
loaded: (posthog) => {
const id = posthog.get_distinct_id()
// use the ID
}
})
get_property()
Release Tag: 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
property_name(string) - The name of the super property you want to retrieve
Returns
Union of:
Propertyundefined
Examples
// grab value for '$user_id' after the posthog library has loaded
posthog.init('<YOUR PROJECT TOKEN>', {
loaded: function(posthog) {
user_id = posthog.get_property('$user_id');
}
});
getGroups()
Release Tag: public
Returns the current groups.
Returns
Record<string, any>
Examples
// Generated example for getGroups
posthog.getGroups();
getSessionProperty()
Release Tag: 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
property_name(string) - The name of the session super property you want to retrieve
Returns
Union of:
Propertyundefined
Examples
// 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');
}
});
group()
Release Tag: public
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
groupType(string) - Group type (example: 'organization')groupKey(string) - Group key (example: 'org::5')groupPropertiesToSet?(Properties) - Optional properties to set for group
Returns
void
Examples
associate user with an organization
// associate user with an organization
posthog.group('organization', 'org_12345', {
name: 'Acme Corp',
plan: 'enterprise'
})
associate with multiple group types
// associate with multiple group types
posthog.group('organization', 'org_12345')
posthog.group('team', 'team_67890')
identify()
Release Tag: public
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
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.
Returns
void
Examples
basic identification
// basic identification
posthog.identify('user_12345')
identify with user properties
// identify with user properties
posthog.identify('user_12345', {
email: '[email protected]',
plan: 'premium'
})
identify with set and set_once properties
// 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
)
onSessionId()
Release Tag: public
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
callback(SessionIdChangedCallback) - The callback function will be called once a session id is present or when it or the window id are updated.
Returns
() => void
Examples
posthog.onSessionId(function(sessionId, windowId) { // do something })
reset()
Release Tag: public
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
reset_device_id?(boolean)
Returns
void
Examples
reset on user logout
// reset on user logout
function logout() {
posthog.reset()
// redirect to login page
}
reset and generate new device ID
// reset and generate new device ID
posthog.reset(true) // also resets device_id
resetGroups()
Release Tag: public
Resets only the group properties of the user currently logged in. Learn more about groups
Returns
void
Examples
posthog.resetGroups()
setInternalOrTestUser()
Release Tag: public
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
Examples
// 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' })
setPersonProperties()
Release Tag: public
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
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
Examples
set user properties
// set user properties
posthog.setPersonProperties({
email: '[email protected]',
plan: 'premium'
})
set properties
// set properties
posthog.setPersonProperties(
{ name: 'Max Hedgehog' }, // $set properties
{ initial_url: '/blog' } // $set_once properties
)
Surveys methods
cancelPendingSurvey()
Release Tag: public
Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).
Parameters
surveyId(string)
Returns
void
Examples
// Generated example for cancelPendingSurvey
posthog.cancelPendingSurvey();
canRenderSurvey()
Release Tag: 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. Use canRenderSurveyAsync instead.
Parameters
surveyId(string) - The ID of the survey to check.
Returns
Union of:
SurveyRenderReasonnull
Examples
// Generated example for canRenderSurvey
posthog.canRenderSurvey();
canRenderSurveyAsync()
Release Tag: public
Checks the feature flags associated with this Survey to see if the survey can be rendered.
Parameters
surveyId(string) - The ID of the survey to check.forceReload?(boolean) - If true, the survey will be reloaded from the server, Default: false
Returns
Promise<SurveyRenderReason>
Examples
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)
}
})
displaySurvey()
Release Tag: public
Display a survey programmatically as either a popover or inline element.
Parameters
surveyId(string) - The survey ID to displayoptions?(DisplaySurveyOptions) - Display configuration
Returns
void
Examples
Display as popover (respects all conditions defined in the dashboard)
// Display as popover (respects all conditions defined in the dashboard)
posthog.displaySurvey('survey-id-123')
Display inline in a specific element
// Display inline in a specific element
posthog.displaySurvey('survey-id-123', {
displayType: DisplaySurveyType.Inline,
selector: '#survey-container'
})
Force display ignoring conditions and delays
// Force display ignoring conditions and delays
posthog.displaySurvey('survey-id-123', {
displayType: DisplaySurveyType.Popover,
ignoreConditions: true,
ignoreDelay: true
})
getActiveMatchingSurveys()
Release Tag: public
Get surveys that should be enabled for the current user. See fetching surveys documentation for more details.
Parameters
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.
Returns
void
Examples
posthog.getActiveMatchingSurveys((surveys) => {
// do something
})
getSurveys()
Release Tag: public
Get list of all surveys.
Parameters
callback(SurveyCallback) - Function that receives the array of surveysforceReload?(boolean) - Optional boolean to force an API call for updated surveys
Returns
void
Examples
function callback(surveys, context) {
// do something
}
posthog.getSurveys(callback, false)
onSurveysLoaded()
Release Tag: public
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
callback(SurveyCallback) - The callback function will be called when surveys are loaded or updated.
Returns
() => void
Examples
posthog.onSurveysLoaded((surveys, context) => { // do something })
renderSurvey()
Release Tag: deprecated
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
surveyId(string) - The ID of the survey to render.selector(string) - The selector of the HTML element to render the survey on.
Returns
void
Examples
posthog.renderSurvey(coolSurveyID, '#survey-container')
Capture methods
capture()
Release Tag: 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
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 detailsoptions?(CaptureOptions) - Optional configuration for the capture request
Returns
Union of:
CaptureResultundefined
Examples
// basic event capture
posthog.capture('cta-button-clicked', {
button_name: 'Get Started',
page: 'homepage'
})
on()
Release Tag: 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
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
event('eventCaptured' | 'featureFlagsReloading') - The event to listen for.cb((...args: any[]) => void) - The callback function to call when the event is emitted.
Returns
() => void
Examples
posthog.on('eventCaptured', (event) => {
console.log(event)
})
Track when feature flags are reloading to show a loading state
// Track when feature flags are reloading to show a loading state
posthog.on('featureFlagsReloading', () => {
console.log('Feature flags are being reloaded...')
})
register_for_session()
Release Tag: 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
properties(Properties) - An associative array of properties to store about the user
Returns
void
Examples
register session-specific properties
// register session-specific properties
posthog.register_for_session({
current_page_type: 'checkout',
ab_test_variant: 'control'
})
register properties for user flow tracking
// register properties for user flow tracking
posthog.register_for_session({
selected_plan: 'pro',
completed_steps: 3,
flow_id: 'signup_flow_v2'
})
register_once()
Release Tag: 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
properties(Properties) - An associative array of properties to store about the userdefault_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
Returns
void
Examples
register once-only properties
// register once-only properties
posthog.register_once({
first_login_date: new Date().toISOString(),
initial_referrer: document.referrer
})
override existing value if it matches default
// override existing value if it matches default
posthog.register_once(
{ user_type: 'premium' },
'unknown' // overwrite if current value is 'unknown'
)
register()
Release Tag: 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
properties(Properties) - properties to store about the userdays?(number) - How many days since the user's last visit to store the super properties
Returns
void
Examples
register a single property
// register a single property
posthog.register({ plan: 'premium' })
register multiple properties
// register multiple properties
posthog.register({
email: '[email protected]',
account_type: 'business',
signup_date: '2023-01-15'
})
register with custom expiration
// register with custom expiration
posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 days
unregister_for_session()
Release Tag: 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
property(string) - The name of the session super property to remove
Returns
void
Examples
// remove a session property
posthog.unregister_for_session('current_flow')
unregister()
Release Tag: 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
property(string) - The name of the super property to remove
Returns
void
Examples
// remove a super property
posthog.unregister('plan_type')
Error tracking methods
captureException()
Release Tag: public
Capture a caught exception manually
Parameters
error(unknown) - The error to captureadditionalProperties?(Properties) - Any additional properties to add to the error event
Returns
Union of:
CaptureResultundefined
Examples
Capture a caught exception
// Capture a caught exception
try {
// something that might throw
} catch (error) {
posthog.captureException(error)
}
With additional properties
// With additional properties
posthog.captureException(error, {
customProperty: 'value',
anotherProperty: ['I', 'can be a list'],
...
})
startExceptionAutocapture()
Release Tag: public
turns exception autocapture on, and updates the config option capture_exceptions to the provided config (or true)
Parameters
config?(ExceptionAutoCaptureConfig) - optional configuration option to control the exception autocapture behavior
Returns
void
Examples
Start with default exception autocapture rules. No-op if already enabled
// Start with default exception autocapture rules. No-op i