JavaScript Web

Last updated:

|Edit this page
Which features are available in this library?
  • Event capture
  • Autocapture
  • User identification
  • Session recording
  • Feature flags
  • Group analytics

Note: This doc refers to our posthog-js library for use on the browser. For server-side JavaScript, see our Node SDK.

Installation

Option 1: Add the JavaScript snippet to your HTML Recommended

This is the simplest way to get PostHog up and running. It only takes a few minutes.

Copy the snippet below and replace <ph_project_api_key> and <ph_client_api_host> with your project's values, then add it within the <head> tags at the base of your product - ideally just before the closing </head> tag. This ensures PostHog loads on any page users visit.

You can find the snippet pre-filled with this data in your project settings.

HTML
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com'})
</script>

Once the snippet is added, PostHog automatically captures $pageview and other events like button clicks. You can then enable other products, such as session replays, within your project settings.


Set up a reverse proxy (recommended)

We recommend setting up a reverse proxy so that events are less likely to be intercepted by tracking blockers. We have our own managed reverse proxy service included in the Teams plan, which routes through our infrastructure and makes setting up your proxy easy.

If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare, AWS Cloudfront, and Vercel.

Include ES5 support (optional)

If you need ES5 support for example to track Internet Explorer 11 replace /static/array.js in the snippet with /static/array.full.es5.js

Option 2: Install via package manager

yarn add posthog-js

And then include it in your files:

Web
import posthog from 'posthog-js'
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })

If you don't want to send test data while you're developing, you can do the following:

Web
if (!window.location.host.includes('127.0.0.1') && !window.location.host.includes('localhost')) {
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })
}

If you're using React or Next.js, checkout our React SDK or Next.js integration.

Advanced option - bundle all required extensions

By default, the PostHog JS library will only load the core functionality, lazy-loading extensions such as Surveys or the Session Replay 'recorder' when needed. This can cause issues if you have a Content Security Policy (CSP) that blocks inline scripts or if you want to optimize your bundle at build time to ensure all dependencies are ready immediately. In addition environments like the Chrome Extension store will reject code that loads remote code. To solve this issue we have multiple import options available.

Please note - with any of the no-external options, the Toolbar will be unavailable as this is only possible as a runtime dependency loaded directly from us.posthog.com

Web
// No external code loading possible (this disables all extensions such as Replay, Surveys, Exceptions etc.)
import posthog from 'posthog-js/dist/module.no-external'
// No external code loading possible but all external dependencies pre-bundled
import posthog from 'posthog-js/dist/module.full.no-external'
// All external dependencies pre-bundled and with the ability to load external scripts (primarily useful is you use Site Apps)
import posthog from 'posthog-js/dist/module.full'
// Finally you can also import specific extra dependencies
import "posthog-js/dist/recorder"
import "posthog-js/dist/surveys"
import "posthog-js/dist/exception-autocapture"
import "posthog-js/dist/tracing-headers"
import "posthog-js/dist/web-vitals"
import posthog from 'posthog-js/dist/module.no-external'
// All other posthog commands are the same as usual
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })

NOTE: You should ensure if using this option that you always import posthog-js from the same module, otherwise multiple bundles could get included. At this time posthog-js/react does not work with any module import other than the default.

Track across marketing website & app

We recommend putting PostHog both on your homepage and your application if applicable. That means you'll be able to follow a user from the moment they come onto your website, all the way through signup and actually using your product.

PostHog automatically sets a cross-domain cookie, so if your website is yourapp.com and your app is on app.yourapp.com users will be followed when they go from one to the other. See our tutorial on cross-website tracking if you need to track users across different domains.

Permitted domains

You can also configure "permitted domains" in your project settings. These are domains where you'll be able to record user sessions and use the PostHog toolbar.

Capturing events

You can send custom events using capture:

Web
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, or invite sent.

Setting event properties

Optionally, you can also include additional information in the event by setting the properties value:

Web
posthog.capture('user_signed_up', {
login_type: "email",
is_free_trial: true
})

Page views and autocapture

By default, PostHog automatically captures the following frontend events:

  • Pageviews, including the URL.
  • Autocaptured events, such as any click, change of input, or submission associated with a, button, form, input, select, textarea, and label tags.

If you prefer to disable these, set the appropriate values in your configuration options.

Manually capturing pageviews and pageleaves in single-page apps

PostHog automatically sends $pageview events whenever it gets loaded and $pageleave when they leaves. If you have a single-page app, that means it only sends pageview and pageleave once (when your app loads and when they leave).

To make sure any navigating a user does within your app gets captured, you can make pageview and pageleave calls manually.

Web
// Capture pageview
posthog.capture('$pageview')
// Capture pageleave
posthog.capture('$pageleave')

This automatically sends the current URL along with other autocaptured properties like the referrer, OS, scroll depth, and more.

Identifying users

We strongly recommend reading our docs on identifying users to better understand how to correctly use this method.

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.

Web
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().

Get the current user's distinct ID

You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify for a user or not.

To do this, call posthog.get_distinct_id(). This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().

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.

Web
posthog.alias('alias_id', 'distinct_id');

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Reset after logout

If a user logs out, you should call reset to unlink any future events made on that device with that user.

This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. We strongly recommend you call reset on logout even if you don't expect users to share a computer.

You can do that like so:

Web
posthog.reset()

If you also want to reset device_id, you can pass true as a parameter:

Web
posthog.reset(true)

Anonymous vs identfied 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.

How to capture anonymous events

The JavaScript Web SDK captures anonymous events by default. However, this may change depending on your person_profiles config when initializing PostHog:

  1. 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.

  2. person_profiles: 'always' - Capture identified events for all events.

For example:

Web
posthog.init(
'<ph_project_api_key>',
{
api_host: 'https://us.i.posthog.com',
person_profiles: 'always'
}
)

How to capture identified events

If you've set the personProfiles config to IDENTIFIED_ONLY (the default option), anonymous events are captured by default. Then, to capture identified events, call any of the following functions:

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.

Setting person properties

To set person properties in these profiles, include them when capturing an event:

Web
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.

JavaScript
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.

Super Properties

Super Properties are properties associated with events that are set once and then sent with every capture call, 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, and they persist across sessions.

For example, take a look at the following call:

Web
posthog.register({
'icecream pref': 'vanilla',
team_id: 22,
})

The call above ensures that every event sent by the user will include "icecream pref": "vanilla" and "team_id": 22. 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 the user's properties. It only sets the properties for their events. To store person properties, see the setting person properties docs.

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:

Web
posthog.register_once({
'campaign source': 'twitter',
})

Using register_once will ensure that if a property is already set, it will not be 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. In order to stop sending a Super Property with events and remove the cookie, you can use posthog.unregister, like so:

Web
posthog.unregister('icecream pref')

This will remove the Super Property and subsequent events will not include it.

Opt out of data capture

You can completely opt-out users from data capture. To do this, there are two options:

  1. Opt users out by default by setting opt_out_capturing_by_default to true in your PostHog config.
Web
posthog.init('<ph_project_api_key>', {
opt_out_capturing_by_default: true,
});
  1. Opt users out on a per-person basis by calling posthog.opt_out_capturing().

Similarly, you can opt users in:

Web
posthog.opt_in_capturing()

To check if a user is opted out:

Web
posthog.has_opted_out_capturing()

Feature Flags

PostHog's feature flags enable you to safely deploy and roll back new features.

Boolean feature flags

Web
if (posthog.isFeatureEnabled('flag-key') ) {
// Do something differently for this user
// Optional: fetch the payload
const matchedFlagPayload = posthog.getFeatureFlagPayload('flag-key')
}

Multivariate feature flags

Web
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 payload
const 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:

Web
posthog.onFeatureFlags(function () {
// feature flags are guaranteed to be available at this point
if (posthog.isFeatureEnabled('flag-key')) {
// do something
}
})

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:

Web
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:

Web
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:

Web
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

At any point, you can reset these properties by calling resetPersonPropertiesForFlags:

Web
posthog.resetPersonPropertiesForFlags()

The same holds for group properties:

Web
// set properties for a group
posthog.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:

  1. $geoip_city_name
  2. $geoip_country_name
  3. $geoip_country_code
  4. $geoip_continent_name
  5. $geoip_continent_code
  6. $geoip_postal_code
  7. $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.

JavaScript
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).
}
)

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:

JavaScript
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 disabled
throw error;
}
}
// Usage example
try {
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 level
console.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 analytics

You can send enriched analytics data for feature flags, which helps 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 on your own if you're not using react.

To implement it on your own, there are 3 things you need to do:

  1. Whenever a feature is viewed, send the $feature_view event with the property feature_flag set to the name of the flag.
JavaScript
posthog.capture('$feature_view', { feature_flag: flag })
  1. Whenever someone interacts with a feature, send the $feature_interaction event with the property feature_flag set to the name of the flag.
  2. At the same time, set the person property $feature_interaction/<flag-key> to true. Here's a code example.
JavaScript
posthog.capture('$feature_interaction', { feature_flag: flag, $set: { [`$feature_interaction/${flag}`]: true } })

Here's a code example for the entire React component.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

Web
// 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-usage
posthog.onFeatureFlags(function() {
// feature flags should be available at this point
if (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.override({'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.

Web
posthog.getEarlyAccessFeatures((previewItemData) => {
// do something with early access feature
})
Web
posthog.updateEarlyAccessFeatureEnrollment(flagKey, 'true')

Group analytics

Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.

  • Associate the events for this session with a group
Web
posthog.group('company', 'company_id_in_your_db')
posthog.capture('upgraded_plan') // this event is associated with company ID `company_id_in_your_db`
  • Associate the events for this session with a group AND update the properties of that group
Web
posthog.group('company', 'company_id_in_your_db', {
name: 'Awesome Inc.',
employees: 11,
})

The name is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name property, the group ID will be used instead.

Handling logging out

When the user logs out it's important to call posthog.reset() to avoid new events being registered under the previously active group.

Integrating groups with feature flags

If you have updated tracking, you can use group-based feature flags as normal.

Web
if (posthog.isFeatureEnabled('new-groups-feature')) {
// do something
}

To check flag status for a different group, first switch the active group by calling posthog.group().

Surveys

Surveys launched with popover presentation are automatically shown to users matching the display conditions you set up.

To disable loading surveys in a specific client, you can set the disable_surveys config option.

Surveys using the API presentation enable 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:

Web
// Fetch enabled surveys for the current user
posthog.getActiveMatchingSurveys(callback, forceReload)
// Fetch all surveys
posthog.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:

JSON
[{
"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 display survey results in PostHog, you need to capture 3 types of events:

Web
// 1. When a user is shown a survey
posthog.capture("survey shown", {
$survey_id: survey.id // required
})
// 2. When a user has dismissed a survey
posthog.capture("survey dismissed", {
$survey_id: survey.id // required
})
// 3. When a user has responded to a survey
posthog.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 "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:

Web
// Turns session recording on
posthog.startSessionRecording()
// Turns session recording off
posthog.stopSessionRecording()
// Check if session recording is currently running
posthog.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:

Web
posthog.startSessionRecording({ linked_flag: true, sampling: true })

To get the playback URL of the current session replay, you can use the following method:

Web
posthog.get_session_replay_url(
{ withTimestamp: true, timestampLookBack: 30 }
)

It has two optional parameters:

  • withTimestamp (default: false): When set to true, 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.

Persistence

For PostHog to work optimally, we store small amount of information about the user on the user's browser. This ensures we identify users properly if they navigates away from your site and come back later. We store the following information in the user's browser:

  • User's ID
  • Session ID & Device ID
  • Active & enabled feature flags
  • Any super properties you have defined.
  • Some PostHog configuration options (e.g. whether session recording is enabled)

By default, we store all this information in both a cookie and localStorage, which means PostHog can identify your users across subdomains. By default, this cookie is set to expire after 365 days and is named with your Project API key e.g. ph_<project_api_key>_posthog.

If you want to change how PostHog stores this information, you can do so with the persistence configuration option:

  • persistence: "localStorage+cookie" (default): Limited things are stored in the cookie such as the distinctID and the sessionID, and everything else in the browser's localStorage.

  • persistence: "cookie" : Stores all data in a cookie.

  • persistence: "localStorage": Stores everything in localStorage.

  • persistence: "sessionStorage": Stores everything in sessionStorage.

  • persistence: "memory": Stores everything in page memory, which means data is only persisted for the duration of the page view.

To change persistence values without reinitializing PostHog, you can use the posthog.set_config() method. This enables you to switch from memory to cookies to better comply with privacy regulations.

Web
const handleCookieConsent = (consent) => {
posthog.set_config({ persistence: consent === 'yes' ? 'localStorage+cookie' : 'memory' });
localStorage.setItem('cookie_consent', consent);
};

Persistence caveats

  • Be aware that localStorage and sessionStorage can't be used across subdomains. If you have multiple sites on the same domain, you may want to consider a cookie option or make sure to set all super properties across each subdomain.

  • Due to the size limitation of cookies you may run into 431 Request Header Fields Too Large errors (e.g. if you have a lot of feature flags). In that case, use localStorage+cookie.

  • If you don't want PostHog to store anything on the user's browser (e.g. if you want to rely on your own identification mechanism only or want completely anonymous users), you can set disable_persistence: true in PostHog's config. If you do this, remember to call posthog.identify every time your app loads. If you don't, every page refresh is treated as a new and different user.

Amending events before they are captured

Since version 1.187.0, when initializing the SDK, you can provide a before_send function. This can be used to amend or reject events before they are sent to PostHog.

Note: Amending and rejecting 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.

Redact URLs in event properties

TypeScript
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 structure
function 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 = redactedProperties
if (event.event === '$$heatmap') {
// $heatmap data is keyed by url
event.properties.$heatmap_data = redactObject(event.properties.$heatmap_data || {});
}
const redactedSet = redactObject(event.$set || {});
event.$set = redactedSet
const redactedSetOnce = redactObject(event.$set_once || {});
event.$set_once = redactedSetOnce
return event
}
})

Redact person properties in $set or $set_once

TypeScript
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 - relies 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 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 events
before_send: sampleByEvent(['$dead_click', '$web_vitals'], 0.5)
})

Sampling events using a custom function

TypeScript
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 event
if (event.event === '$heatmap') {
sampleRate = 0.1
}
if (event.event === '$dead_click') {
sampleRate = 0.01
}
return Math.random() < sampleRate ? event : null
}
})

Sampling to receive only 40% of events by person distinct ID

A particular distinct ID will always either send all events or no events.

You can import this using a package manager, or add the customization script to your site.

import { sampleByDistinctId } from 'posthog-js/lib/src/customizations'
posthog.init('<ph_project_api_key>', {
before_send: sampleByDistinctId(0.4)
})

Sampling to receive only 25% of events by session ID

A particular session ID will always either send all events or no events.

You can import this using a package manager, or add the customization script to your site.

import { sampleBySessionId } from 'posthog-js/lib/src/customizations'
posthog.init('<ph_project_api_key>', {
before_send: sampleBySessionId(0.25)
})

Providing more than one before_send function

You can provide an array of functions to be called one after the other

TypeScript
posthog.init('<ph_project_api_key>', {
before_send: [
sampleByDistinctId(0.5), // only half of people
sampleByEvent(['$web_vitals'], 0.1), // and they capture all events except 10% of web vitals
sampleByEvent(['$$heatmap'], 0.5), // and 50% of heatmaps
]
})

Or 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

TypeScript
posthog.init('<ph_project_api_key>', {
before_send: (event: CaptureResult | null): CaptureResult | null => {
if (event) {
console.log('posthog event: ' + event.event, event)
}
return null
}
})

Config

When calling posthog.init, there are various configuration options you can set in addition to loaded and api_host.

To configure these options, pass them as an object to the posthog.init call, like so:

TypeScript
posthog.init('<ph_project_api_key>', {
api_host: 'https://us.i.posthog.com',
loaded: function (posthog) {
posthog.identify('[user unique id]')
},
autocapture: false,
// ... more options
})

There are multiple different configuration options, most of which you do not have to ever worry about. For brevity, only the most relevant ones are used here. However you can view all the configuration options in the SDK's source code.

Some of the most relevant options are:

AttributeDescription
api_host

Type: String
Default: https://us.i.posthog.com
URL of your PostHog instance.
ui_host

Type: String
Default: undefined
If using a reverse proxy for api_host then this should be the actual PostHog app URL (e.g. https://us.posthog.com). This ensures that links to PostHog point to the correct host.
autocapture

Type: Boolean or AutocaptureConfig
Default: true
Determines if PostHog should autocapture events. This setting does not affect capturing pageview events (see capture_pageview). See below for AutocaptureConfig)
bootstrap

Type: Object
Default: {}
An object containing the distinctID, isIdentifiedID, and featureFlags keys, where distinctID is a string, and featureFlags is an object of key-value pairs
capture_pageview

Type: Boolean
Default: true
Determines if PostHog should automatically capture pageview events.
capture_pageleave

Type: Boolean
Default: true
Determines if PostHog should automatically capture pageleave events.
capture_dead_clicks

Type: Boolean
Default: true
Determines if PostHog should automatically capture dead click events.
cross_subdomain_cookie

Type: Boolean
Default: true
Determines if cookie should be set on the top level domain (example.com). If PostHog-js is loaded on a subdomain (test.example.com), and cross_subdomain_cookie is set to false, it'll set the cookie on the subdomain only (test.example.com).
disable_persistence

Type: Boolean
Default: false
Disable persisting user data across pages. This will disable cookies, session storage and local storage.
disable_surveys

Type: Boolean
Default: false
Determines if surveys script should load which controls whether they show up for users, and whether requests for API surveys return valid data
disable_session_recording

Type: Boolean
Default: false
Determines if users should be opted out of session recording.
enable_recording_console_log

Type: Boolean
Default: false
Determines if console logs should be recorded as part of the session recording. More information.
enable_heatmaps

Type: Boolean
Default: undefined
Determines if heatmap data should be captured.
loaded

Type: Function
Default: function () {}
A function to be called once the PostHog scripts have loaded successfully.
mask_all_text

Type: Boolean
Default: false
Prevent PostHog autocapture from capturing any text from your elements.
mask_all_element_attributes

Type: Boolean
Default: false
Prevent PostHog autocapture from capturing any attributes from your elements.
opt_out_capturing_by_default

Type: Boolean
Default: false
Determines if users should be opted out of PostHog tracking by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing.
opt_out_persistence_by_default

Type: Boolean
Default: false
Determines if users should be opted out of browser data storage by this PostHog instance by default, requiring additional logic to opt them into capturing by calling posthog.opt_in_capturing.
persistence

Type: localStorage or sessionStorage or cookie or memory or localStorage+cookie
Default: localStorage+cookie
Determines how PostHog stores information about the user. See persistence for details.
property_denylist

Type: Array
Default: []
A list of properties that should never be sent with capture calls.
person_profiles

Type: Enum: always, identified_only
Default: identified_only
Set whether events should capture identified events and process person profiles
rate_limiting

Type: Object
Default: { events_per_second: 10, events_burst_limit: events_per_second * 10 }
Controls event rate limiting to help you avoid accidentally sending too many events. events_per_second determines how many events can be sent per second on average (default: 10). events_burst_limit sets the maximum events that can be sent at once (default: 10 times the events_per_second value).
sanitize_properties

Type: Function
Default: null
A function that allows you to sanitize or modify the properties that get sent. Example: sanitize_properties: function(properties, event) { if(properties['$ip']) { properties['$ip'] = null } return properties }
session_recording

Type: Object
Default: See here.
Configuration options for recordings. More details found here
session_idle_timeout_seconds

Type: Integer
Default: 1800
The maximum amount of time a session can be inactive before it is split into a new session.
xhr_headers

Type: Object
Default: {}
Any additional headers you wish to pass with the XHR requests to the PostHog API.

AutocaptureConfig

The autocapture config takes an object providing full control of autocapture's behavior.

AttributeDescription
url_allowlist

Type: Array of Strings or Regexp
Default: undefined
List of URLs to enable autocapture on, can be string or regex matches e.g. ['https://example.com', 'test.com/.*']. An empty list means no URLs are allowed for capture, undefined means all URLs are.
dom_event_allowlist

Type: Array of Strings
Default: undefined
An array of DOM events, like 'click', 'change', 'submit', to enable autocapture on. An empty array means no events are enable for capture, undefined means all are.
element_allowlist

Type: Array of Strings
Default: undefined
An array of DOM elements, like 'a', 'button', 'form', 'input', 'select', 'textarea', or 'label', to allow autocapture on. An empty array means no elements are enabled for capture, undefined means all elements are enabled.
css_selector_allowlist

Type: Array of Strings
Default: undefined
An array of CSS selectors to enable autocapture on. An empty array means no CSS selectors are allowed for capture, undefined means all CSS selectors are.
element_attribute_ignorelist

Type: Array of Strings
Default: undefined
An array of element attributes that autocapture will not capture. Both an empty array and undefined mean any of the attributes from the element are captured.
capture_copied_text

Type: Boolean
Default: false
When set to true, autocapture will capture the text of any element that is cut or copied.

Advanced configuration

In this section we describe some additional details on advanced configuration available.

AttributeDescription
advanced_disable_decide

Type: Boolean
Default: false
Will completely disable the /decide endpoint request (and features that rely on it). More details below.
advanced_disable_feature_flags

Type: Boolean
Default: false
Will keep /decide running, but without any feature flag requests
advanced_disable_feature_flags_on_first_load

Type: Boolean
Default: false
Stops from firing feature flag requests on first page load. Only requests feature flags when user identity or properties are updated, or you manually request for flags to be loaded.
feature_flag_request_timeout_ms

Type: Integer
Default: 3000
Sets timeout for fetching feature flags
secure_cookie

Type: Boolean
Default: false
If this is true, PostHog cookies will be marked as secure, meaning they will only be transmitted over HTTPS.
custom_campaign_params

Type: Array
Default: []
List of query params to be automatically captured (see UTM Segmentation )
fetch_options.cache

Type: string
Default: undefined
fetch call cache behavior (see MDN Docs to understand available options). It's important when using NextJS, see companion documentation. This is a tricky option, avoid using it unless you are aware of the changes this could cause - such as cached feature flag values, etc.
fetch_options.next_options

Type: Object
Default: undefined
Arguments to be passed to the next key when calling fetch under NextJS. See companion documentation.
These are features for advanced users and may lead to unintended side effects if not reviewed carefully. If you are unsure about something, just reach out.

Disable /decide endpoint

This feature was introduced in posthog-js 1.10.0. Previously, disabling autocapture would inherently disable the /decide endpoint altogether. This meant that disabling autocapture would inadvertenly turn off session recording, feature flags, compression and the toolbar too.

One of the very first things the PostHog library does when init() is called is make a request to the /decide endpoint on PostHog's backend. This endpoint contains information on how to run the PostHog library so events are properly received in the backend. This endpoint is required to run most features of the library (detailed below). However, if you're not using any of the described features, you may wish to turn off the call completely to avoid an extra request and reduce resource usage on both the client and the server.

The /decide endpoint can be disabled by setting advanced_disable_decide = true in PostHog config.

Resources dependent on /decide

These are features/resources that will be fully disabled when the /decide endpoint is disabled.
  • Autocapture. The /decide endpoint contains information on whether autocapture should be enabled or not (apart from local configuration).
  • Session recording. The endpoint contains information on where to send relevant session recording events.
  • Compression. The endpoint contains information on what compression methods are supported on the backend (e.g. LZ64, gzip) for event payloads.
  • Feature flags. The endpoint contains the feature flags enabled for the current person.
  • Surveys. The endpoint contains information on whether surveys should be enabled or not.
  • Toolbar. The endpoint contains authentication information and other toolbar capabilities information required to run it.

Any custom event capturing (posthog.capture), $identify, $set, $set_once and basically any other calls not detailed above will work as expected when /decide is disabled.

Running more than one instance of PostHog at the same time

While not a first-class citizen, PostHog allows you to run more than one instance of PostHog at the same if you, for example, want to track different events in different posthog instances/projects.

posthog.init accepts a third parameter that can be used to create named instances.

TypeScript
posthog.init('<ph_project_api_key>', {}, 'organization1')
posthog.init('<ph_project_api_key>', {}, 'organization2')

You can then call these different instances by accessing it on the global posthog object

TypeScript
posthog.organization1.capture("some_event")
posthog.organization2.capture("other_event")

Note: You'll probably want to disable autocapture (and some other events) to avoid them from being sent to both instances. Check all of our config options to better understand that.

Debugging

In your dev console you can run posthog.debug(). This will enable debugging, easily allowing you to see all data that is being sent to PostHog.

Development

For instructions on how to run posthog-js locally and setup your development environment, please checkout the README on the posthog-js repository.

Questions?

Was this page useful?

Next article

Android

It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your mobile app. Installation Capturing events Identifying users We highly recommend reading our section on Identifying users to better understand how to correctly use this method. Get the current user's distinct ID You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify…

Read next article