JavaScript Integration

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('[your-token]', {api_host: 'https://[your-instance]'})

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("[your-token]", {api_host: 'https://[your-instance]'});

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

window.location.href.indexOf('') === -1 && posthog.init("[your-token]", {api_host: 'https://[your-instance]'})



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'});

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.

posthog.identify('[user unique id]');

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]'); }

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

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. Aditionally, 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:


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.

You can do that like so:


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


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:

Attribute Type Default Description
api_host String URL of your PostHog instance.
autocapture Boolean true Determines if PostHog should autocapture events.
loaded Function function () {} (no-op) A function to be called once the PostHog scripts have loaded successfully.
capture_pageview Boolean true Determines if PostHog should automatically capture pageview events.
opt_out_capturing_by_default Boolean false Determines if users should be opted out of PostHog tracking by default, requiring additional logic to opt them into capturing.
property_blacklist Array [] A list of properties that should never be sent with capture calls.
xhr_headers Object {} Any additional headers you wish to pass with the XHR requests to the PostHog API.

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

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


To develop, clone the repo and run:

yarn start

To create a minified production version, run:

yarn build