JavaScript web

Browser only. posthog-js runs in the browser. For server-side JavaScript, use the Node.js SDK.

Installation

Option 1: Install with the AI wizard

Run the AI wizard in your project directory to detect your framework, install PostHog, and configure your app:

Option 2: Add the JavaScript snippet to your HTML Recommended

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||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult 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_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})
</script>

Keeping the SDK version up to date

Be careful to avoid things which can cause the SDK version to be cached and fail to update. See: Ways SDK versions fall behind

Using TypeScript with the script tag?

If you're using TypeScript and want type safety for window.posthog, install the @posthog/types package:

Terminal
npm install @posthog/types@1

Then create a type declaration file:

typescript
// posthog.d.ts
import type { PostHog } from '@posthog/types'
declare global {
interface Window {
posthog?: PostHog
}
}
export {}

See the JavaScript SDK types reference for all exported interfaces and options.

Option 3: Install via package manager

npm install --save posthog-js@1

If your site sets a Content-Security-Policy, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of posthog.com that change over time, so allow the wildcard:

script-src 'self' https://*.posthog.com;
connect-src 'self' https://*.posthog.com;
worker-src 'self' blob: data:;

script-src covers the snippet and the lazy-loaded bundles, connect-src covers event ingestion and feature flags, and worker-src covers session replay. The toolbar needs a few more, or use a reverse proxy so everything is first-party. Failing to do so causes silent failures where capture and identify calls never send, so the integration looks complete while zero events arrive. Remember connect-src falls back to default-src, so default-src 'self' blocks event delivery even when the script itself is bundled.

And then include it with your project token and host (which you can find in your project settings):

Web
import posthog from 'posthog-js'
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30'
})

See our framework specific docs for Next.js, React, Vue, Angular, Astro, Remix, and Svelte for more installation details.

Update early, update often

We ship weirdly fast, especially for our JavaScript web SDK. If you choose the npm package instead of the HTML snippet, be sure to update it frequently:

To actually update the package, you need to update the version constraint in your package.json file and then reinstall, or run update instead of install:

npm update posthog-js
Bundle all required extensions (advanced)

By default, the JavaScript Web library only loads the core functionality. It lazy-loads 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.
  • You want to optimize your bundle at build time to ensure all dependencies are ready immediately.
  • Your app is running in environments like the Chrome Extension store or Electron that reject or block remote code loading.

To solve these issues, we have multiple import options available below.

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
// (disables extensions like Replay, Surveys, Exceptions)
import posthog from 'posthog-js/dist/module.no-external'
// No external loading, with extensions pre-bundled
import posthog from 'posthog-js/dist/module.full.no-external'
// Pre-bundled extensions, still loads JS snippets
import posthog from 'posthog-js/dist/module.full'
// Import specific extensions manually
import 'posthog-js/dist/posthog-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 work the same
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})

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/react does not work with any module import other than the default.

Tree shaking with the slim bundle (advanced)

If you only need a subset of PostHog features, you can use the slim bundle to reduce your bundle size. It gives you the core functionality (event capture, identify, group analytics) and lets you explicitly opt in to additional features via extension bundles. This is currently experimental, but offers the biggest reduction in bundle size.

Web
import posthog from 'posthog-js/dist/module.slim'
import {
SessionReplayExtensions,
AnalyticsExtensions,
} from 'posthog-js/dist/extension-bundles'
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
__extensionClasses: {
...SessionReplayExtensions,
...AnalyticsExtensions,
}
})

Note: Always import posthog-js from the same module path (posthog-js/dist/module.slim) throughout your app, otherwise multiple bundles could get included.

Available extension bundles

BundleWhat's included
FeatureFlagsExtensionsFeature Flags
SessionReplayExtensionsSession Replay
AnalyticsExtensionsAutocapture, pageview tracking, heatmaps, dead click detection, web vitals
ErrorTrackingExtensionsError Tracking
SurveysExtensionsSurveys
ExperimentsExtensionsExperiments
SiteAppsExtensionsJS snippets
TracingExtensionsDistributed tracing header injection
ToolbarExtensionsToolbar
LogsExtensionsLog capture
ConversationsExtensionsSupport
WebMCPExtensionsWebMCP tool call capture for MCP Analytics. Add ErrorTrackingExtensions to also send failed calls to Error Tracking.
AllExtensionsEverything (equivalent to the default posthog-js bundle)

Note: Each extension bundle includes its own dependencies. You don't need to worry about adding them separately.

Don't want to send test data while developing?

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

Web
const host = window.location.host
if (
!host.includes('127.0.0.1') &&
!host.includes('localhost')
) {
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-08-30',
})
}
What is the `defaults` option?

The defaults option is a date that selects a configuration snapshot used as defaults to initialize PostHog. The examples use the latest snapshot. This default is overridden when you explicitly set a value for any of the options. The configuration reference lists each snapshot and what it changes.

Using Google Tag Manager? Use the Google Tag Manager template rather than a custom HTML tag.

Pass this to your agent

Give your agent the markdown version of the JavaScript SDK reference.

What the SDK does

After setup, the SDK captures pageviews, clicks, form interactions, and sessions automatically:

  • Anonymous-to-identified profiles. Events start under a generated anonymous ID with no person profile (person_profiles: 'identified_only' by default). Calling identify links that history to the user's profile. If you already know who signed in on page load, see identifying users.
  • **Cross-subdomain tracking.** Default storage pairs `localStorage` with a shared cookie, so PostHog keeps identity and sessions across subdomains like `example.com` and `app.example.com`. See [Persistence](/docs/libraries/js/persistence) for storage modes or [cross-domain tracking](/tutorials/cross-domain-tracking) for separate root domains.
  • **Consent and opt-out.** You can start opted out or run cookieless by default, then update consent at runtime with [opt_in_capturing](/docs/libraries/js/1.x.x#posthogopt_in_capturing) and [opt_out_capturing](/docs/libraries/js/1.x.x#posthogopt_out_capturing). See [Privacy and consent](/docs/libraries/js/1.x.x#privacy-and-consent) for every consent method.
  • Named instances and debugging. Pass a name string as the third argument to init to create an isolated secondary instance. Disable autocapture on it, so you don't capture duplicate events.

Next steps

GuideCovers
UsageSDK lifecycle across events, identity, feature flags, surveys, replay, and filtering
ConfigurationInteractive config builder, where settings apply, proxy paths, and snippet pins
SecurityVersion pinning, Subresource Integrity (SRI), CSP, nonces, and no-external bundles
PersistenceBrowser storage modes, subdomain cookies, and consent storage separation
Version 1.x.xFull generated API signatures, config options, and TypeScript types

Still have questions?

Was this page useful?