JavaScript Library

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

This page of the Docs refers to our JS library.

Why Does This Exist?

The reason this exists is that whilst the default snippet captures every click on certain elements (like a, button, input etc.) and page views, it's often worth sending more context whenever a user does something. This might also be useful if you have a one page app.


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

!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(,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>'})

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


npm install --save posthog-js

And then include it in your files:

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:

if (!window.location.href.includes('')) {
posthog.init("<ph_project_api_key>", {api_host: '<ph_instance_address>'})



Just by calling posthog.init above, you're already automatically capturing:

  • 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

Ignore/Censure elements

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.

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

Important Note on Autocapture

While autocapture allows you to track the majority of general events on your website right out of the gate, it is important to note that, for security reasons, PostHog is very conservative regarding input tags. In order to prevent passwords or other sensitive data from being collected, very little data is collected from inputs with autocapture.

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

As such, you should be aware of this when you start, in order to understand why you may be getting less data than expected.

If you need to collect more data from inputs, you should look into Custom Events and Actions.

Website vs 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 and your app is on users will be followed when they go from one to the other.

Sending Events

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.

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.



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


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.



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


$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

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.

'[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 previous section.

Warning! You can't call identify straight after an .init (as .init sends a page view, probably with the user's anonymous id. To combat this, you can call .init with a callback, inside which you can then call identify.

posthog.init('[your api key]', {
api_host: 'https://posthog.[your-domain].com',
loaded: function(posthog) { posthog.identify('[user unique id]'); }

Reset After Logout

If a user is logged out, you probably 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 1 user due to shared cookies between sessions.

You can do that like so:


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


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.

posthog.people.set({email: ''});

Note: you can call this function at any point, but it'll only be sent after the posthog.identify call

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.


This will automatically send the current URL.

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:

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

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

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:


See if a user has opted out:


Opt a user back in:


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

  • Check if a feature is enabled:
  • Trigger a reload of the feature flags:
  • 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:
posthog.isFeatureEnabled('keyword', {send_event: false})

Complete Signup Pseudocode

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

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
// Set email or any other data
posthog.people.set({email: email});


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

There are 33 different options, most of which you do not have to ever worry about.

Some of the most relevant options are:


Type: String
URL of your PostHog instance.

Type: Boolean
Default: true
Determines if PostHog should autocapture events.

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

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

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

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

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

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

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

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

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

Type: Object
Default: See here.
Advanced feature - use with caution. Configuration options for rrweb.

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

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


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.


To develop, clone the repo and run:

yarn start

To create a minified production version, run:

yarn build

Was this page helpful?