JavaScript

Last updated:

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

Note: You can just use our snippet to start capturing events with our JS.

This page of the Docs refers to our posthog-js library.

Installation

You can either load the snippet as a script in your HTML:

JavaScript snippet Recommended

This is the simplest way to get PostHog up and running on your website, and only takes a few minutes to set-up.

Add to your website & app

Paste this snippet within the <head> tags of your website - ideally just inside the closing </head> tag - on all pages that you wish to track.

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.async=!0,p.src=s.api_host+"/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="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags".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: '<ph_instance_address>'})
</script>

Be sure to replace <ph_project_api_key> and <ph_instance_address> with your project's values. (You can find the snippet pre-filled with this data in the PostHog app under Project / Settings. (Quick links if you use PostHog Cloud US or PostHog Cloud EU)

What this code does

After adding the snippet to your website, it will automatically start to:

Place the snippet in the <head> tags of your website, ideally just above the closing </head> tag. You will need to do this for all pages that you wish to track.

Or you can include it using npm, by doing either:

yarn add posthog-js

And then include it in your files:

JavaScript
import posthog from 'posthog-js'
posthog.init('<ph_project_api_key>', { api_host: '<ph_instance_address>' })

If you don't want to send a bunch of test data while you're developing, you could do the following:

JavaScript
if (!window.location.host.includes('127.0.0.1') && !window.location.host.includes('localhost')) {
posthog.init('<ph_project_api_key>', { api_host: '<ph_instance_address>' })
}

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

Usage

Autocapture

When you call posthog.init the PostHog JS library begins automatically capturing user 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

Autocapture allows you to track the majority of general events on your website right out of the gate

Tuning autocapture

You can configure autocapture using allowlists. If an array is passed for an allowlist, autocapture events will only be sent for elements matching at least one of the items in the array.

For example, to only capture clicks on buttons on the docs section of the website that contain the data attribute ph-autocapture you can do:

JavaScript
posthog.init('<ph_project_api_key>', {
api_host: '<ph_instance_address>',
autocapture: {
event_allowlist: ['click'], // DOM events from this list ['click', 'change', 'submit']
url_allowlist: ['posthog.com./docs/.*'], // strings or RegExps
element_allowlist: ['button'], // DOM elements from this list ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']
css_selector_allowlist: ['[ph-autocapture]'], // List of CSS selectors
},
})

The allowlists only filter autocapture events, they won't affect the data collected by session recordings.

PostHog puts a great amount of effort into making sure it doesn't capture any sensitive data from your website. If there are other elements you don't want to be captured, you can add the ph-no-capture class name.

HTML
<button class='ph-no-capture'>Sensitive information here</button>

Alternatively you can disable autocapture completely by setting autocapture: false in the config.

Disabling autocapture will not disable session recording. You can disable session recording using disable_session_recording or by turning it off in your project's settings.

Autocapture on input elements

For security reasons, PostHog is very conservative regarding input tags to prevent passwords or other sensitive data from being collected.

Specifically, PostHog autocapture will grab only the name, id, and class attributes from input tags.

Sometimes less data might be collected than expected. If you need to collect more data from inputs, you should look into Custom events and Actions.

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.

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.

Send custom events with posthog.capture

This allows you to send more context than the default event info that PostHog captures whenever a user does something. In that case, you can send an event with any metadata you may wish to add.

JavaScript
posthog.capture('[event-name]', {property1: 'value', property2: 'another value'});

Setting user properties via an event

To set properties on a user, you can use the posthog.people.set and posthog.people.set_once methods.

However, you can also leverage the event properties $set and $set_once to do this via an event.

$set

Example

JavaScript
posthog.capture('some event', { $set: { userProperty: 'value' } })

Usage

When capturing an event, you can pass a property called $set as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.

This works the same way as posthog.people.set.

$set_once

Example

JavaScript
posthog.capture('some event', { $set_once: { userProperty: 'value' } })

Usage

$set_once works just like $set, except that it will only set the property if the user doesn't already have that property set.

This works the same way as posthog.people.set_once.

Identifying users

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

To make sure you understand which user is performing actions within your app, you can identify users at any point. From the moment you make this call, all events will be identified with that distinct id.

The ID can by anything, but is usually the unique ID that you identify users by in the database. Normally, you would put this below posthog.init if you have the information there.

If a user was previously anonymous (because they hadn't signed up or logged in yet), we'll automatically alias their anonymous ID with their new unique ID. That means all their events from before and after they signed up will be shown under the same user.

JavaScript
posthog.identify(
'[user unique id]', // distinct_id, required
{ userProperty: 'value1' }, // $set, optional
{ anotherUserProperty: 'value2' } // $set_once, optional
);

You can also pass two more arguments to posthog.identify. Both take objects consisting of as many properties as you want to be set on that user's profile. The difference is that the second argument will use the $set mechanism, whereas the third argument will use $set_once.

You can read more about the difference between this in the setting properties section.

Warning! You can't call identify straight after an `.init` (as `.init` sends a pageview event, probably with the user's anonymous ID).

To address the issue described above, you can call .init passing a loaded callback function, inside which you can then call identify, like so:

JavaScript
posthog.init('<ph_project_api_key>', {
api_host: '<ph_instance_address>',
loaded: function(posthog) { posthog.identify('[user unique id]'); }
});

Multiple IDs

If you use multiple distinct IDs for the same user (e.g. a logical ID and a UUID), you may want to set both for the same user. This way, if PostHog receives events for either ID, it will properly match them to the same person. This is also helpful if you want to associate anonymous IDs with an identified person (we actually do this automatically when you call .identify). To associate multiple IDs to the same person, you do an alias call, as shown below.

JavaScript
posthog.alias('[distinct ID]', '[alias ID]')

Any events sent to either will be received under the same person.

Note: that the '[alias ID]' cannot be associated with multiple distinct ids.

Reset after logout

If a user is logged out, you most likely want to call reset to unset any distinct_ids.

This is especially important if your users are sharing a computer, as otherwise all of those users will be grouped together into a single user due to shared cookies between sessions.

We strongly recommend you do this on logout even if you don't expect users to share a computer. This can help make sure all your users are properly tracked in the odd case a user logs in with a different account.

You can do that like so:

JavaScript
posthog.reset()

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

JavaScript
posthog.reset(true)

Sending user information

An ID alone might not be enough to work out which user is who within PostHog. That's why it's useful to send over more metadata of the user. At minimum, we recommend sending the email property, which is also what we use to display in PostHog.

You can make this call on every page view to make sure this information is up-to-date. Alternatively, you can also do this whenever a user first appears (after signup) or when they change their information.

JavaScript
posthog.people.set({ email: 'john@gmail.com' })

One-page apps and page views

This JS snippet automatically sends pageview events whenever it gets loaded. If you have a one-page app, that means it'll only send a pageview once, when your app loads.

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

JavaScript
posthog.capture('$pageview')

This will automatically send the current URL.

Signup example

As an example, here is how to put some of the above concepts together:

JavaScript
function signup(email) {
// Your own internal logic for creating an account and getting a user_id
let userId = createAccount(email)
// Identify user with internal ID
posthog.identify(userId)
// Set email or any other data
posthog.people.set({ email: email })
}

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:

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

However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use posthog.people.set. More information on this can be found on the Sending User Information section.

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:

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

JavaScript
posthog.unregister('icecream pref')

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

Opt users out

PostHog JS offers a function to opt users out based on your cookie settings definition (e.g. preferences set via a cookie banner).

This is also the suggested way to prevent capturing any data from the admin on the page, as well as from team members of your organization. A simple way to do this is to access the page as the admin (or any other user on your team you wish to stop capturing data on), and call posthog.opt_out_capturing(); on the developer console. You can also add this logic in you app and call it directly after an admin/team member logs in.

If you still wish to capture these events but want to create a distinction between users and team in PostHog, you should look into Cohorts.

With PostHog, you can:

Opt a user out:

JavaScript
posthog.opt_out_capturing()

See if a user has opted out:

JavaScript
posthog.has_opted_out_capturing()

Opt a user back in:

JavaScript
posthog.opt_in_capturing()

Feature Flags

PostHog v1.10.0 introduced Feature Flags, which allow you to safely deploy and roll back new features.

Here's how you can use them:

  • Do something when the feature flags load:

    The argument callback(flags: string[]) will be called when the feature flags are loaded.

    In case the flags are already loaded, it'll be called immediately. Additionally, it will also be called when the flags are re-loaded e.g. after calling identify or reloadFeatureFlags.

JavaScript
posthog.onFeatureFlags(callback)
  • Check if a feature is enabled:
JavaScript
posthog.isFeatureEnabled('keyword')
  • Trigger a reload of the feature flags:
JavaScript
posthog.reloadFeatureFlags()
  • By default, this function will send a $feature_flag_called event to your instance every time it's called so you're able to do analytics. You can disable this by passing the send_event property:
JavaScript
posthog.isFeatureEnabled('keyword', { send_event: false })

Feature Flag Payloads

Payloads allow you to retrieve a value that is associated with the matched flag. The value can be a string, boolean, number, dictionary, or array. This allows for custom configurations based on values defined in the posthog app.

JavaScript
posthog.getFeatureFlagPayload('keyword')

Bootstrapping Flags

There is a delay between loading the library and feature flags becoming available to use. For some cases, like redirecting users to a different page based on a feature flag, this is extremely detrimental, as the flags load after the redirect logic occurs, thus never working.

In cases like these, where you want flags to be immediately available on page load, you can use the bootstrap library option.

This allows you to pass in a distinctID and feature flags during library initialisation, like so:

JavaScript
posthog.init('<ph_project_api_key>', {
api_host: '<ph_instance_address>',
bootstrap: {
distinctID: 'your-anonymous-id',
featureFlags: {
'flag-1': true,
'variant-flag': 'control',
'other-flag': false,
},
},
})

To compute these flag values, use the corresponding getAllFlags method in your server-side library. Note that bootstrapping flags requires server-side initialisation.

If the ID you're passing in is an identified ID (that is, an ID with which you've called posthog.identify() elsewhere), you can also pass in the isIdentifiedID bootstrap option, which ensures that this ID is treated as an identified ID in the library. This is helpful as it warns you when you try to do something wrong with this ID, like calling identify again.

JavaScript
posthog.init('<ph_project_api_key>', {
api_host: '<ph_instance_address>',
bootstrap: {
distinctID: 'your-identified-id',
isIdentifiedID: true,
featureFlags: {
'flag-1': true,
'variant-flag': 'control',
'other-flag': false,
},
},
})

Note: Passing in a distinctID to bootstrap replaces any existing IDs, which means you may fail to connect any old anonymous user events with the logged in person, if your logic calls identify in the frontend immediately on login. In this case, you can omit passing in the distinctID.

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
JavaScript
posthog.group('company', '42dlsfj23f')
posthog.capture('upgraded plan') // this event is associated with company ID `42dlsfj23f`
  • Associate the events for this session with a group AND update the properties of that group
JavaScript
posthog.group('company', '42dlsfj23f', {
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.

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

Persistence

In order for PostHog to work optimally, we require storing a small amount of information about the user on the user's browser. This ensures that if the user navigates away, and comes back to your site at a later time, we will still identify them properly. 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 a cookie, which means that PostHog will still be able to identify your users even across subdomains. By default, this cookie is set to expire after 365 days.

If you would like to change how PostHog stores this information, you can do so with the persistence parameter.

  • persistence: "cookie" (default). Everything is stored in a cookie.
  • persistence: "localStorage+cookie". User's distinct ID is stored in a cookie and everything else is stored in the browser's localStorage.
  • persistence: "localStorage". Everything is stored in localStorage.
  • persistence: "memory". Stores in page memory, which means data is only persisted for the duration of the page view.

As a note, 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.

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

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. Warning: Remember to call posthog.identify every time your app loads or every page refresh will be treated as a different user.

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:

JavaScript
posthog.init('<ph_project_api_key>', {
api_host: '<ph_instance_address>',
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 posthog-core.js.

Some of the most relevant options are:

AttributeDescription
api_host

Type: String
Default: https://app.posthog.com
URL of your PostHog instance.
autocapture

Type: Boolean
Default: true
Determines if PostHog should autocapture events. This setting does not affect capturing pageview events (see capture_pageview).
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.
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_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.
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.
persistence

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

Type: Array
Default: []
A list of properties that should never be sent with capture calls.
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
xhr_headers

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

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

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 Configuration Making calls Identify We highly recommend reading our section on Identifying users to better understand how to correctly use this method. Capture Setting user properties via an event To set properties on your users via an event, you can leverage the event properties $set and $set_once . $set…

Read next article