Capturing events
By default, PostHog automatically captures pageviews and pageleaves as well as clicks, change of inputs, and form submissions associated with a
, button
, form
, input
, select
, textarea
, and label
tags. See our autocapture docs for more details on this.
If you prefer to disable or filter these, set the appropriate values in your configuration options.
Custom event capture
You can send custom events using capture
:
posthog.capture('user_signed_up');
Tip: We recommend using a
[object] [verb]
format for your event names, where[object]
is the entity that the behavior relates to, and[verb]
is the behavior itself. For example,project created
,user signed up
, orinvite sent
.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
posthog.capture('user_signed_up', {login_type: "email",is_free_trial: true})
Manually capturing pageviews and pageleaves in single-page apps
PostHog automatically captures $pageview
events on page load and $pageleave
events on page unload. If you have a single-page app, that means it only sends pageview and pageleave once (when your app loads and when users leave).
To make sure any navigating a user does within your app gets captured, you can make pageview and pageleave calls manually like this:
// Capture pageviewposthog.capture('$pageview')// Capture pageleaveposthog.capture('$pageleave')
This automatically sends the current URL along with other autocaptured properties like the referrer, OS, scroll depth, and more. See our guide to tracking pageviews in single-page apps for more details.
Anonymous and identified events
PostHog captures two types of events: anonymous and identified
Identified events enable you to attribute events to specific users, and attach person properties. They're best suited for logged-in users.
Scenarios where you want to capture identified events are:
- Tracking logged-in users in B2B and B2C SaaS apps
- Doing user segmented product analysis
- Growth and marketing teams wanting to analyze the complete conversion lifecycle
Anonymous events are events without individually identifiable data. They're best suited for web analytics or apps where users aren't logged in.
Scenarios where you want to capture anonymous events are:
- Tracking a marketing website
- Content-focused sites
- B2C apps where users don't sign up or log in
Under the hood, the key difference between identified and anonymous events is that for identified events we create a person profile for the user, whereas for anonymous events we do not.
💡 Tip: Under our current pricing, anonymous events can be up to 4x cheaper than identified ones (due to the cost of processing them), so it's recommended you only capture identified events when needed.
Capturing anonymous events
The JavaScript Web SDK captures anonymous events by default. However, this may change depending on your person_profiles
config when initializing PostHog:
person_profiles: 'identified_only'
(recommended) (default) - Anonymous events are captured by default. PostHog only captures identified events for users where person profiles have already been created.person_profiles: 'always'
- Capture identified events for all events.
For example:
posthog.init('<ph_project_api_key>',{api_host: 'https://us.i.posthog.com',person_profiles: 'always'})
Capturing identified events
If you've set the personProfiles
config to IDENTIFIED_ONLY
(the default option), anonymous events are captured by default. To capture identified events, call any of the following functions:
identify()
alias()
group()
setPersonProperties()
setPersonPropertiesForFlags()
setGroupPropertiesForFlags()
When you call any of these functions, it creates a person profile for the user. Once this profile is created, all subsequent events for this user will be captured as identified events.
Alternatively, you can set personProfiles
to ALWAYS
to capture identified events by default.
Identifying users
The most useful of these methods is identify
. We strongly recommend reading our doc on identifying users to better understand how to correctly use it.
Using identify
, you can capture identified events associated with specific users. This enables you to understand how they're using your product across different sessions, devices, and platforms.
posthog.identify('distinct_id', // Required. Replace 'distinct_id' with your user's unique identifier{ email: 'max@hedgehogmail.com', name: 'Max Hedgehog' }, // $set, optional{ first_visited_url: '/blog' } // $set_once, optional);
Calling identify
creates a person profile if one doesn't exist already. This means all events for that distinct ID count as identified events.
You can get the distinct ID of the current user by calling posthog.get_distinct_id()
.
Setting person properties
To set person properties in these profiles, include them when capturing an event:
posthog.capture('event_name',{$set: { name: 'Max Hedgehog' },$set_once: { initial_url: '/blog' },})
Typically, person properties are set when an event occurs like user updated email
but there may be occasions where you want to set person properties as its own event.
posthog.setPersonProperties({ name: "Max Hedgehog" }, // These properties are like the `$set` from above{ initial_url: "/blog" } // These properties are like the `$set_once` from above)
This creates a special $set
event that is sent to PostHog. For more details on the difference between $set
and $set_once
, see our person properties docs.
Resetting a user
If a user logs out or switches accounts, you should call reset
to unlink any future events made on that device with that user. This prevents multiple users from being grouped together due to shared cookies between sessions. We recommend you call reset
on logout even if you don't expect users to share a computer.
You can do that like so:
posthog.reset()
If you also want to reset device_id
, you can pass true
as a parameter:
posthog.reset(true)
This also resets group analytics.
Alias
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
In this case, you can use alias
to assign another distinct ID to the same user.
posthog.alias('alias_id', 'distinct_id');
We recommend reading our docs on alias to best understand how to correctly use this method.
Group analytics
Group analytics enables you to associate the events for that person's session with a group (e.g. teams, organizations, etc.).
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.
This is done by calling the group
method with a group type and group ID.
posthog.group('company', 'company_id_in_your_db')posthog.capture('upgraded_plan') // this event is associated with company ID `company_id_in_your_db`
You can also set group properties by passing a third argument to the group
method.
posthog.group('company', 'company_id_in_your_db', {name: 'Awesome Inc.',employees: 11,})
The name
is a special property used in the PostHog UI for the name of the group. If you don't specify a name
property, the group ID is used instead.
Super properties
Super properties are properties associated with events that are set once and then sent with every capture
call across sessions, be it a $pageview
, an autocaptured button click, or anything else.
They are set using posthog.register
, which takes a properties object as a parameter like this:
posthog.register({'icecream_pref': 'vanilla',})
The call above ensures that every event sent includes a "icecream pref": "vanilla"
property. This way, if you filtered events by property using icecream_pref = vanilla
, it would display all events captured on that user after the posthog.register
call, since they all include the specified super property.
This does not set a person or group property. It only sets the properties on events.
Furthermore, if you register the same property multiple times, the next event will use the new value of that property. If you want to register a property only once (e.g. for ad campaign properties), you can use register_once
, like so:
posthog.register_once({'campaign_source': 'twitter',})
Using register_once
ensures that if a property is already set, it is not set again. For example, if the user already has property "icecream_pref": "vanilla"
, calling posthog.register_once({"icecream_pref": "chocolate"})
will not update the property.
Removing stored super properties
Setting super properties creates a cookie on the client with the respective properties and their values. To stop sending a super property with events and remove the cookie, you can use posthog.unregister
, like so:
posthog.unregister('icecream_pref')
This removes the super property and subsequent events will not include it.
Feature flags
PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.
Boolean feature flags
if (posthog.isFeatureEnabled('flag-key') ) {// Do something differently for this user// Optional: fetch the payloadconst matchedFlagPayload = posthog.getFeatureFlagPayload('flag-key')}
Multivariate feature flags
if (posthog.getFeatureFlag('flag-key') == 'variant-key') { // replace 'variant-key' with the key of your variant// Do something differently for this user// Optional: fetch the payloadconst matchedFlagPayload = posthog.getFeatureFlagPayload('flag-key')}
Ensuring flags are loaded before usage
Every time a user loads a page, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in your chosen persistence option (local storage by default).
This means that for most pages, the feature flags are available immediately — except for the first time a user visits.
To handle this, you can use the onFeatureFlags
callback to wait for the feature flag request to finish:
posthog.onFeatureFlags(function (featureFlags, flagVariants, { errorsLoading }) {// feature flags are guaranteed to be available at this pointif (posthog.isFeatureEnabled('flag-key')) {// do something}})
Callback parameters
The onFeatureFlags
callback receives the following parameters:
flags: string[]
: An object containing the feature flags that apply to the user.flagVariants: Record<string, string | boolean>
: An object containing the variants that apply to the user.{ errorsLoading }: { errorsLoading?: boolean }
: An object containing a boolean indicating if an error occurred during the request to load the feature flags. This istrue
if the request timed out or if there was an error. It will befalse
orundefined
if the request was successful.
You won't usually need to use these, but they are useful if you want to be extra careful about feature flags not being loaded yet because of a network error and/or a network timeout (see feature_flag_request_timeout_ms
).
Reloading feature flags
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:
posthog.reloadFeatureFlags()
Overriding server properties
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:
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})
Note: These are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation.
Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading:
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)
At any point, you can reset these properties by calling resetPersonPropertiesForFlags
:
posthog.resetPersonPropertiesForFlags()
The same holds for group properties:
// set properties for a groupposthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})// reset properties for a given group:posthog.resetGroupPropertiesForFlags('company')// reset properties for all groups:posthog.resetGroupPropertiesForFlags()
Note: You don't need to add the group names here, since these properties are automatically attached to the current group (set via
posthog.group()
). When you change the group, these properties are reset.
Automatic overrides
Whenever you call posthog.identify
with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call posthog.group()
.
Default overridden properties
By default, we always override some properties based on the user IP address.
The list of properties that this overrides:
$geoip_city_name
$geoip_country_name
$geoip_country_code
$geoip_continent_name
$geoip_continent_code
$geoip_postal_code
$geoip_time_zone
This enables any geolocation-based flags to work without manually setting these properties.
Request timeout
You can configure the feature_flag_request_timeout_ms
parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.
posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com',feature_flag_request_timeout_ms: 3000 // Time in milliseconds. Default is 3000 (3 seconds).})
Feature flag error handling
When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:
function handleFeatureFlag(client, flagKey, distinctId) {try {const isEnabled = client.isFeatureEnabled(flagKey, distinctId);console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`);return isEnabled;} catch (error) {console.error(`Error fetching feature flag '${flagKey}': ${error.message}`);// Optionally, you can return a default value or throw the error// return false; // Default to disabledthrow error;}}// Usage exampletry {const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123');if (flagEnabled) {// Implement new feature logic} else {// Implement old feature logic}} catch (error) {// Handle the error at a higher levelconsole.error('Feature flag check failed, using default behavior');// Implement fallback logic}
Bootstrapping flags
Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.
To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.
For details on how to implement bootstrapping, see our bootstrapping guide.
Enriched flag analytics
You can send enriched analytics data for feature flags to help uncover replays where people interact with a flag, target people who've interacted with a feature, or build cohorts of people who've viewed a feature.
To enable this, you can either use our <PosthogFeature>
React component (which implements this for you), or implement it yourself.
To do it yourself, there are 3 things you need to do:
- Whenever a feature is viewed, send the
$feature_view
event with the propertyfeature_flag
set to the name of the flag.
posthog.capture('$feature_view', { feature_flag: flag })
Whenever someone interacts with a feature, send a
$feature_interaction
event with the propertyfeature_flag
set to the name of the flag.At the same time, set the person property
$feature_interaction/<flag-key>
to true.
posthog.capture('$feature_interaction', {feature_flag: flag,$set: { [`$feature_interaction/${flag}`]: true }})
See the React component for another example.
Experiments (A/B tests)
Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:
// Ensure flags are loaded before usage.// You'll only need to call this on the code the first time a user visits.// See this doc for more details: https://posthog.com/docs/feature-flags/manual#ensuring-flags-are-loaded-before-usageposthog.onFeatureFlags(function() {// feature flags should be available at this pointif (posthog.getFeatureFlag('experiment-feature-flag-key') == 'variant-name') {// do something}})// Otherwise, you can just do:if (posthog.getFeatureFlag('experiment-feature-flag-key') == 'variant-name') {// do something}// You can also test your code by overriding the feature flag:// e.g., posthog.featureFlags.overrideFeatureFlags({ flags: {'experiment-feature-flag-key': 'test'}})
It's also possible to run experiments without using feature flags.
Early access feature management
Early access features give you the option to release feature flags that can be controlled by your users. More information on this can be found here.
posthog.getEarlyAccessFeatures((previewItemData) => {// do something with early access feature})
posthog.updateEarlyAccessFeatureEnrollment(flagKey, 'true')
Surveys
Surveys launched with popover presentation are automatically shown to users matching the display conditions you set up.
You can also render unstyled surveys programmatically with the renderSurvey
method.
posthog.renderSurvey('survey_id', '#survey-container')
To disable loading surveys in a specific client, you can set the disable_surveys
config option.
Surveys using the API presentation enables you to implement your own survey UI and use PostHog to handle display logic, capturing results, and analytics.
To implement API surveys, start by fetching active surveys for a user using either of the methods below:
// Fetch enabled surveys for the current userposthog.getActiveMatchingSurveys(callback, forceReload)// Fetch all surveysposthog.getSurveys(callback, forceReload)
The response returns an array of survey objects and is cached by default. To force a reload, pass true
as the forceReload
argument.
The survey objects look like this:
[{"id": "your_survey_id","name": "Your survey name","description": "Metadata describing your survey","type": "api", // either "api", "popover", or "widget""linked_flag_key": null, // linked feature flag key, if any."targeting_flag_key": "your_survey_targeting_flag_key","questions": [{"type": "single_choice","choices": ["Yes","No"],"question": "Are you enjoying PostHog?"}],"conditions": null,"start_date": "2023-09-19T13:10:49.505000Z","end_date": null}]
Capturing survey events
To capture survey results properly in PostHog, you need to capture 3 types of events:
// 1. When a user is shown a surveyposthog.capture("survey shown", {$survey_id: survey.id // required})// 2. When a user has dismissed a surveyposthog.capture("survey dismissed", {$survey_id: survey.id // required})// 3. When a user has responded to a surveyposthog.capture("survey sent", {$survey_id: survey.id, // required$survey_response: survey_response // required. `survey_response` must be a text value.// Convert numbers to text e.g. 8 should be converted to "8".// For multiple choice select surveys, `survey_response` must be an array of values with the selected choices.// e.g., $survey_response: ["response_1", "response_2"]})
Session replay
To set up session replay in your project, all you need to do is install the JavaScript web library and enable "Record user sessions" in your project settings.
For fine-tuning control of which sessions you record, you can use feature flags, sampling, minimum duration, or set the disable_session_recording
config option and use the following methods:
// Turns session recording onposthog.startSessionRecording()// Turns session recording offposthog.stopSessionRecording()// Check if session recording is currently runningposthog.sessionRecordingStarted()
If you are using feature flags or sampling to control which sessions you record, you can override the default behavior (and start a recording regardless) by passing the linked_flag
or sampling
overrides. The following would start a recording for all users, even if they don't match the flag or aren't in the sample:
posthog.startSessionRecording({ linked_flag: true, sampling: true })
To get the playback URL of the current session replay, you can use the following method:
posthog.get_session_replay_url({ withTimestamp: true, timestampLookBack: 30 })
It has two optional parameters:
withTimestamp
(default:false
): When set totrue
, the URL includes a timestamp that takes you to the session at the time of the event.timestampLookBack
(default:10
): The number of seconds back the timestamp links to.
Error tracking
You can enable exception autocapture in the Autocapture & heatmaps section of your project settings. When enabled, this automatically captures $exception
events when errors are thrown.
It is also possible to manually capture exceptions using the captureException
method:
posthog.captureException(error, additionalProperties)
Amending or sampling events
Since version 1.187.0, you can provide a before_send
function when initializing the SDK to amend, filter, sample, or reject events before they are sent to PostHog.
🚨 Warning: Amending and sampling events is advanced functionality and should be done with care. It can cause unexpected results in parts of PostHog.
Redacting information in events
before_send
gives you one place to edit or redact information before it is sent to PostHog. For example:
Redact URLs in event properties
posthog.init('<ph_project_api_key>', {before_send: (event: CaptureResult | null): CaptureResult | null => {if (!event) {return null}// redacting URLs will be specific to your site structurefunction redactUrl(value: string): string {return value.replace(/project\/\d+/, 'project/1234567');}function redactObject(objectToRedact: Record<string, any>): Record<string, any> {return Object.entries(objectToRedact).reduce((acc, [key, value]) => {const redactedValue = key.includes("url") && typeof value === "string" ? redactUrl(value) : value;acc[redactUrl(key)] = redactedValue;return acc;}, {});}const redactedProperties = redactObject(event.properties || {});event.properties = redactedPropertiesif (event.event === '$$heatmap') {// $heatmap data is keyed by urlevent.properties.$heatmap_data = redactObject(event.properties.$heatmap_data || {});}const redactedSet = redactObject(event.$set || {});event.$set = redactedSetconst redactedSetOnce = redactObject(event.$set_once || {});event.$set_once = redactedSetOncereturn event}})
Redact person properties in $set or $set_once
posthog.init('<ph_project_api_key>', {before_send: (event: CaptureResult | null): CaptureResult | null => {if (!event) {return null}event.$set = {...event.$set,name: 'secret name'}event.$set_once = {...event.$set_once,initial_name: 'secret name'}return event}})
Sampling events
Sampling lets you choose to send only a percentage of events to PostHog. It is a good way to control your costs without having to completely turn off features of the SDK.
Some functions of PostHog, for example much of web analytics, rely on receiving all events. Sampling $pageview
or $pageleave
events in particular can cause unexpected results.
Sampling events using our provided customization
We offer a pre-built sampleByEvent
function to sample by event name. You can import this using a package manager, or add the customization script to your site.
import { sampleByEvent } from 'posthog-js/lib/src/customizations'posthog.init('<ph_project_api_key>', {// capture only half of dead click and web vitals eventsbefore_send: sampleByEvent(['$dead_click', '$web_vitals'], 0.5)})
This can be used to sample events by name, distinct ID, session ID, or custom function.
Send no events while developing
When working locally it can be useful to see what PostHog would do, without actually sending the data to PostHog
posthog.init('<ph_project_api_key>', {before_send: (event: CaptureResult | null): CaptureResult | null => {if (event) {console.log('posthog event: ' + event.event, event)}return null}})
Sampling by person distinct ID
We offer a pre-built sampleByDistinctId
function to sample a percentage of events by person distinct ID (in the example below, 40% of events). You can import this using a package manager, or add the customization script to your site.
Note: A particular distinct ID will always either send all events or no events.
import { sampleByDistinctId } from 'posthog-js/lib/src/customizations'posthog.init('<ph_project_api_key>', {before_send: sampleByDistinctId(0.4)})
Sampling by session ID
We offer a pre-built sampleBySessionId
function to sample a percentage of events by session ID (in the example below, 25% of events). You can import this using a package manager, or add the customization script to your site.
Note: A particular session ID will always either send all events or no events.
import { sampleBySessionId } from 'posthog-js/lib/src/customizations'posthog.init('<ph_project_api_key>', {before_send: sampleBySessionId(0.25)})
Sampling events using a custom function
If none of the provided sampling functions meet your needs, you can provide a custom function to sample events.
posthog.init('<ph_project_api_key>', {before_send: (event: CaptureResult | null): CaptureResult | null => {if (!event) {return null}let sampleRate = 1.0 // default to always returning the eventif (event.event === '$heatmap') {sampleRate = 0.1}if (event.event === '$dead_click') {sampleRate = 0.01}return Math.random() < sampleRate ? event : null}})
Chaining before_send functions
You can provide an array of functions to be called one after the other:
posthog.init('<ph_project_api_key>', {before_send: [sampleByDistinctId(0.5), // only half of peoplesampleByEvent(['$web_vitals'], 0.1), // and they capture all events except 10% of web vitalssampleByEvent(['$$heatmap'], 0.5), // and 50% of heatmaps]})