AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, multi-step procedure for integrating the PostHog SDK into a wide range of web, mobile, and backend frameworks. It handles the detection of the project environment, installation of the appropriate SDK, initialization, user identification, and secure configuration of environment variables. The skill emphasizes following framework-specific patterns and maintaining an analytics contract, ensuring that PostHog is implemented consistently without disrupting existing application logic.
What it does
- Detects the project's framework, language, and package manager.
- Installs the correct PostHog SDK for the identified platform.
- Configures PostHog initialization and provider setup based on framework-specific references.
- Implements user identification logic for login and signup events.
- Manages environment variables for project tokens and host URLs securely.
- Verifies the integration and performs minimal cleanup.
When to use it
- When setting up PostHog in a project for the first time.
- When reviewing pull requests that require PostHog initialization.
- When adding analytics to a new application across supported frameworks.
- When migrating or updating PostHog configurations in an existing codebase.
Advantages
- Ensures consistent implementation across diverse technology stacks.
- Prevents hardcoding of sensitive project tokens and host URLs.
- Follows established framework-specific best practices and patterns.
- Minimizes the risk of breaking application boot or build processes.
- Automates the repetitive aspects of SDK setup and environment configuration.
Usage examples
- “Set up PostHog in my Next.js project.”
- The agent will detect the Next.js environment, install the PostHog SDK, configure the necessary provider, and set up environment variables in .env.local.
- “Integrate PostHog into this Android app.”
- The agent will identify the Android/Kotlin structure, initialize PostHog in the Application class, and guide the setup of local.properties for configuration.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/posthog/instrument-integration/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-integration.zip -d .agents/skills
Documentation by PostHog
Add PostHog SDK integration
Use this skill to add the PostHog SDK to an application. Use it when setting up PostHog for the first time, or reviewing PRs that need PostHog initialization. Covers SDK installation, provider setup, and basic configuration. Supports any framework or language.
Supported frameworks and languages: Next.js, React, React Router, Vue, Nuxt, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, PHP, Ruby on Rails, Go, Elixir, Android, iOS, Swift, Flutter, React Native, Expo, Node.js, and vanilla JavaScript.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Look for dependency files (package.json, pubspec.yaml, Podfile, Package.swift, requirements.txt, Gemfile, composer.json, go.mod, mix.exs, etc.) to determine the framework and language.
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) to determine the package manager.
Check for existing PostHog setup. If PostHog is already installed and initialized, do not modify its code. Inform the user and skip to verification.
STEP 2: Research integration. 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and configuration patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.
STEP 3: Install the PostHog SDK.
Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.
STEP 4: Initialize PostHog.
Follow the framework reference for where and how to initialize. This varies significantly by framework (e.g., instrumentation-client.ts for Next.js 15.3+, AppConfig.ready() for Django, create_app() for Flask).
Set up the PostHog provider/wrapper component if the framework requires one.
STEP 5: Identify users.
Add PostHog
identify()calls on the client side during login and signup events.If both frontend and backend exist, pass the client-side session and distinct ID using
X-POSTHOG-DISTINCT-IDandX-POSTHOG-SESSION-IDheaders to the server-side code.
STEP 6: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.Write these values to the appropriate env file (e.g.
.env.localfor Next.js,.envfor others) using the framework's naming convention.Reference these environment variables in code instead of hardcoding them.
STEP 7: Verify and clean up.
Check the project for errors. Look for type checking or build scripts in package.json.
Ensure any components created were actually used.
Run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Never run formatting or linting across the entire project's codebase.
Reference files
references/EXAMPLE-next-app-router.md- next-app-router example project codereferences/EXAMPLE-next-pages-router.md- next-pages-router example project codereferences/EXAMPLE-react-react-router-6.md- react-react-router-6 example project codereferences/EXAMPLE-react-react-router-7-framework.md- react-react-router-7-framework example project codereferences/EXAMPLE-react-react-router-7-data.md- react-react-router-7-data example project codereferences/EXAMPLE-react-react-router-7-declarative.md- react-react-router-7-declarative example project codereferences/EXAMPLE-react-vite.md- react-vite example project codereferences/EXAMPLE-nuxt-3-6.md- nuxt-3-6 example project codereferences/EXAMPLE-nuxt-4.md- nuxt-4 example project codereferences/EXAMPLE-vue-3.md- vue-3 example project codereferences/EXAMPLE-react-tanstack-router-file-based.md- react-tanstack-router-file-based example project codereferences/EXAMPLE-react-tanstack-router-code-based.md- react-tanstack-router-code-based example project codereferences/EXAMPLE-tanstack-start.md- tanstack-start example project codereferences/EXAMPLE-sveltekit.md- sveltekit example project codereferences/EXAMPLE-astro-static.md- astro-static example project codereferences/EXAMPLE-astro-view-transitions.md- astro-view-transitions example project codereferences/EXAMPLE-astro-ssr.md- astro-ssr example project codereferences/EXAMPLE-astro-hybrid.md- astro-hybrid example project codereferences/EXAMPLE-angular.md- angular example project codereferences/EXAMPLE-javascript-node.md- javascript-node example project codereferences/EXAMPLE-javascript-web.md- javascript-web example project codereferences/EXAMPLE-django.md- django example project codereferences/EXAMPLE-flask.md- flask example project codereferences/EXAMPLE-fastapi.md- fastapi example project codereferences/EXAMPLE-python.md- python example project codereferences/EXAMPLE-laravel.md- laravel example project codereferences/EXAMPLE-php.md- php example project codereferences/EXAMPLE-ruby-on-rails.md- ruby-on-rails example project codereferences/EXAMPLE-ruby.md- ruby example project codereferences/EXAMPLE-android.md- android example project codereferences/EXAMPLE-swift.md- swift example project codereferences/EXAMPLE-react-native.md- react-native example project codereferences/EXAMPLE-expo.md- expo example project codereferences/next-js.md- Next.jsreferences/react.md- Reactreferences/react-router-v6.md- React router v6references/react-router-v7-framework-mode.md- React router v7 framework mode (remix v3)references/react-router-v7-data-mode.md- React router v7 data modereferences/react-router-v7-declarative-mode.md- React router v7 declarative modereferences/nuxt-js-3-6.md- Nuxt.js (v3.0 to v3.6)references/nuxt-js.md- Nuxt.jsreferences/vue-js.md- Vue.jsreferences/tanstack-start.md- Tanstack startreferences/svelte.md- Sveltereferences/astro.md- Astroreferences/angular.md- Angularreferences/js.md- JavaScript webreferences/posthog-js.md- PostHog JavaScript web SDKreferences/node.md- Node.jsreferences/posthog-node.md- PostHog Node.js SDKreferences/django.md- Djangoreferences/flask.md- Flaskreferences/python.md- Pythonreferences/posthog-python.md- PostHog python SDKreferences/dotnet.md- .netreferences/elixir.md- Elixirreferences/go.md- Goreferences/laravel.md- Laravelreferences/php.md- Phpreferences/ruby-on-rails.md- Ruby on railsreferences/ruby.md- Rubyreferences/android.md- Androidreferences/ios.md- Iosreferences/usage.md- Ios SDK usagereferences/configuration.md- Ios SDK configurationreferences/flutter.md- Flutterreferences/react-native.md- React nativereferences/identify-users.md- Identify usersreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each framework reference contains SDK-specific installation, initialization, and usage patterns. Find the one matching the user's stack.
Key principles
Environment variables: Always use environment variables for PostHog keys. Never hardcode them.
Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.
Match the example: Your implementation should follow the example project's patterns as closely as possible.
Analytics contract: Treat event names, property names, and feature flag keys as part of an analytics contract. Reuse existing names and patterns found in the project. When introducing new ones, make them clear, descriptive, and consistent with existing conventions.
Files
- ATTRIBUTION.mdAdded by AutoGineer952 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.8 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/EXAMPLE-android.md49.8 KiB
- references/EXAMPLE-angular.md23.1 KiB
- references/EXAMPLE-astro-hybrid.md27.5 KiB
- references/EXAMPLE-astro-ssr.md27.6 KiB
- references/EXAMPLE-astro-static.md19.6 KiB
- references/EXAMPLE-astro-view-transitions.md23.3 KiB
- references/EXAMPLE-django.md30.7 KiB
- references/EXAMPLE-expo.md35.1 KiB
- references/EXAMPLE-fastapi.md40.9 KiB
- references/EXAMPLE-flask.md32.4 KiB
- references/EXAMPLE-javascript-node.md9.0 KiB
- references/EXAMPLE-javascript-web.md11.8 KiB
- references/EXAMPLE-laravel.md59.3 KiB
- references/EXAMPLE-next-app-router.md17.6 KiB
- references/EXAMPLE-next-pages-router.md19.1 KiB
- references/EXAMPLE-nuxt-3-6.md22.3 KiB
- references/EXAMPLE-nuxt-4.md28.9 KiB
- references/EXAMPLE-php.md13.0 KiB
- references/EXAMPLE-python.md11.6 KiB
- references/EXAMPLE-react-native.md46.0 KiB
- references/EXAMPLE-react-react-router-6.md13.5 KiB
- references/EXAMPLE-react-react-router-7-data.md20.1 KiB
- references/EXAMPLE-react-react-router-7-declarative.md15.0 KiB
- references/EXAMPLE-react-react-router-7-framework.md32.5 KiB
- references/EXAMPLE-react-tanstack-router-code-based.md19.6 KiB
- references/EXAMPLE-react-tanstack-router-file-based.md18.3 KiB
- references/EXAMPLE-react-vite.md12.4 KiB
- references/EXAMPLE-ruby-on-rails.md38.0 KiB
- references/EXAMPLE-ruby.md10.0 KiB
- references/EXAMPLE-sveltekit.md18.6 KiB
- references/EXAMPLE-swift.md18.8 KiB
- references/EXAMPLE-tanstack-start.md29.9 KiB
- references/EXAMPLE-vue-3.md17.9 KiB
- references/android.md33.3 KiB
- references/angular.md16.5 KiB
- references/astro.md15.8 KiB
- references/configuration.md17.2 KiB
- references/django.md14.9 KiB
- references/dotnet.md25.8 KiB
- references/elixir.md17.6 KiB
- references/flask.md8.1 KiB
- references/flutter.md42.8 KiB
- references/go.md20.1 KiB
- references/identify-users.md12.2 KiB
- references/ios.md8.0 KiB
- references/js.md16.1 KiB
- references/laravel.md13.1 KiB
- references/next-js.md18.3 KiB
- references/node.md45.6 KiB
- references/nuxt-js-3-6.md11.4 KiB
- references/nuxt-js.md15.1 KiB
- references/php.md23.7 KiB
- references/posthog-js.md51.6 KiB
- references/posthog-node.md33.9 KiB
- references/posthog-python.md69.3 KiB
- references/python.md52.2 KiB
- references/react-native.md59.9 KiB
- references/react-router-v6.md13.6 KiB
- references/react-router-v7-data-mode.md13.5 KiB
- references/react-router-v7-declarative-mode.md13.7 KiB
- references/react-router-v7-framework-mode.md20.2 KiB
- references/react.md21.9 KiB
- references/ruby-on-rails.md19.7 KiB
- references/ruby.md25.5 KiB
- references/svelte.md14.6 KiB
- references/tanstack-start.md12.8 KiB
- references/usage.md29.2 KiB
- references/vue-js.md13.4 KiB
references/posthog-js.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
PostHog JavaScript Web SDK
Posthog-js allows you to automatically capture usage and send events to PostHog.
Categories
Initialization
Identification
Capture
Error tracking
Surveys
Logs
LLM analytics
Privacy
Session replay
Feature flags
Toolbar
Lifecycle
PostHog
This is the SDK reference for the PostHog JavaScript Web SDK. You can learn more about example usage in the JavaScript Web SDK documentation. You can also follow framework specific guides to integrate PostHog into your project. This SDK is designed for browser environments. Use the PostHog Node.js SDK for server-side usage.
Other methods
PostHog()
Release Tag: public
Creates an uninitialized PostHog instance.
Notes:
Most browser applications should use the default exported singleton and call posthog.init(). Construct a new instance only when you need to manage a separate SDK instance manually.
Returns
any
Examples
const instance = new PostHog()
instance.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com' })clearIdentity()
Release Tag: public
Clear HMAC-based identity verification, reverting to anonymous mode.
Returns
void
Examples
posthog.clearIdentity()get_explicit_consent_status()
Release Tag: public
Returns the explicit consent status of the user.
Notes:
This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not take the default config options into account, only whether the user has made an explicit choice, so this can be used to determine whether to show an initial cookie banner or not.
Returns
Union of:
'granted''denied''pending'
Examples
const consentStatus = posthog.get_explicit_consent_status()
if (consentStatus === "granted") {
// user has explicitly opted in
} else if (consentStatus === "denied") {
// user has explicitly opted out
} else if (consentStatus === "pending"){
// user has not made a choice, show consent banner
}get_session_id()
Release Tag: public
Returns the current session_id.
Notes:
This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager.
Returns
string
Examples
// Generated example for get_session_id
posthog.get_session_id();getAllFeatureFlags()
Release Tag: public
Returns all currently cached feature flags as FeatureFlagResults. This is a synchronous read of the flags from the last load (no network request); call reloadFeatureFlags() first to refresh. Conclusive off evaluations are included with enabled: false; keys omitted from the response, including globally inactive flags, are absent. Unlike getFeatureFlag(), this method does not send a $feature_flag_called event.
Returns
FeatureFlagResult[]
Examples
// Generated example for getAllFeatureFlags
posthog.getAllFeatureFlags();push()
Release Tag: public
push() keeps the standard async-array-push behavior around after the lib is loaded. This is only useful for external integrations that do not wish to rely on our convenience methods (created in the snippet).
Parameters
item(SnippetArrayItem) - A[function_name, ...args]array to be executed.
Returns
void
Examples
posthog.push(['register', { a: 'b' }]);setIdentity()
Release Tag: public
Set HMAC-based identity verification.
Notes:
When set, products like conversations use server-verified identity (distinct_id + HMAC hash) instead of anonymous session identifiers. The hash should be computed server-side as HMAC-SHA256 of the distinct_id, signed with the Secret API key from Support settings. Project secret API keys (project settings) and personal API keys are rejected. Any additional signed identity claims are cleared because they are bound to the previously configured distinct_id.
Parameters
distinctId(string) - The verified user distinct_idhash(string) - HMAC-SHA256 of distinctId, signed with the Secret API key from Support settings
Returns
void
Examples
posthog.setIdentity('user_123', 'a1b2c3d4e5f6...')Error tracking methods
addExceptionStep()
Release Tag: public
Add a breadcrumb-like step that will be attached to the next captured exception.
Parameters
message(string) - The step message.properties?(Properties) - Additional context for this step.
Returns
void
Examples
posthog.addExceptionStep('Checkout button clicked', {
checkout_id: 'ch_123',
})captureException()
Release Tag: public
Capture a caught exception manually
Parameters
error(unknown) - The error or exception-like value to capture.additionalProperties?(Properties) - Any additional properties to add to the error event.
Returns
Union of:
CaptureResultundefined
Examples
Capture a caught exception
// Capture a caught exception
try {
// something that might throw
} catch (error) {
posthog.captureException(error)
}With additional properties
// With additional properties
posthog.captureException(error, {
customProperty: 'value',
anotherProperty: ['I', 'can be a list'],
...
})startExceptionAutocapture()
Release Tag: public
turns exception autocapture on, and updates the config option capture_exceptions to the provided config (or true)
Parameters
config?(ExceptionAutoCaptureConfig) - optional configuration option to control the exception autocapture behavior
Returns
void
Examples
Start with default exception autocapture rules. No-op if already enabled
// Start with default exception autocapture rules. No-op if already enabled
posthog.startExceptionAutocapture()Start and override controls
// Start and override controls
posthog.startExceptionAutocapture({
// you don't have to send all of these (unincluded values will use the default)
capture_unhandled_errors: true || false,
capture_unhandled_rejections: true || false,
capture_console_errors: true || false
})stopExceptionAutocapture()
Release Tag: public
turns exception autocapture off by updating the config option capture_exceptions to false
Returns
void
Examples
// Stop capturing exceptions automatically
posthog.stopExceptionAutocapture()Identification methods
alias()
Release Tag: public
Creates an alias linking two distinct user identifiers. Learn more about identifying users
Notes:
PostHog will use this to link two distinct_ids going forward (not retroactively). Call this when a user signs up to connect their anonymous session with their account.
Parameters
alias(string) - A unique identifier that you want to use for this user in the future.original?(string) - The current identifier being used for this user.
Returns
Union of:
CaptureResultvoidnumber
Examples
link anonymous user to account on signup
// link anonymous user to account on signup
posthog.alias('user_12345')explicit alias with original ID
// explicit alias with original ID
posthog.alias('user_12345', 'anonymous_abc123')createPersonProfile()
Release Tag: public
Creates a person profile for the current user, if they don't already have one and config.person_profiles is set to 'identified_only'. Produces a warning and does not create a profile if config.person_profiles is set to 'never'. Learn more about person profiles
Returns
void
Examples
posthog.createPersonProfile()get_distinct_id()
Release Tag: public
Returns the current distinct ID for the user.
Notes:
This is either the auto-generated ID or the ID set via identify(). The distinct ID is used to associate events with users in PostHog.
Returns
string
Examples
get the current user ID
// get the current user ID
const userId = posthog.get_distinct_id()
console.log('Current user:', userId)use in loaded callback
// use in loaded callback
posthog.init('token', {
loaded: (posthog) => {
const id = posthog.get_distinct_id()
// use the ID
}
})get_property()
Release Tag: public
Returns the value of a super property. Returns undefined if the property doesn't exist.
Notes:
get_property() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.
Parameters
property_name(string) - The name of the super property you want to retrieve
Returns
Union of:
Propertyundefined
Examples
// grab value for '$user_id' after the posthog library has loaded
posthog.init('<YOUR PROJECT TOKEN>', {
loaded: function(posthog) {
user_id = posthog.get_property('$user_id');
}
});getGroups()
Release Tag: public
Returns the current groups.
Returns
Record<string, any>
Examples
// Generated example for getGroups
posthog.getGroups();getSessionProperty()
Release Tag: public
Returns the value of the session super property named property_name. If no such property is set, getSessionProperty() will return the undefined value.
Notes:
This is based on browser-level sessionStorage, NOT the PostHog session. getSessionProperty() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically.
Parameters
property_name(string) - The name of the session super property you want to retrieve
Returns
Union of:
Propertyundefined
Examples
// grab value for 'user_id' after the posthog library has loaded
posthog.init('YOUR PROJECT TOKEN', {
loaded: function(posthog) {
user_id = posthog.getSessionProperty('user_id');
}
});group()
Release Tag: public
Associates the user with a group for group-based analytics. Learn more about groups
Notes:
Groups allow you to analyze users collectively (e.g., by organization, team, or account). This sets the group association for all subsequent events and reloads feature flags.
Parameters
groupType(string) - Group type (example: 'organization')groupKey(string) - Group key (example: 'org::5')groupPropertiesToSet?(Properties) - Optional properties to set for group
Returns
void
Examples
associate user with an organization
// associate user with an organization
posthog.group('organization', 'org_12345', {
name: 'Acme Corp',
plan: 'enterprise'
})associate with multiple group types
// associate with multiple group types
posthog.group('organization', 'org_12345')
posthog.group('team', 'team_67890')identify()
Release Tag: public
Associates a user with a unique identifier instead of an auto-generated ID. Learn more about identifying users
Notes:
By default, PostHog assigns each user a randomly generated distinct_id. Use this method to replace that ID with your own unique identifier (like a user ID from your database).
Parameters
new_distinct_id(string) - A non-empty string that uniquely identifies a user.userPropertiesToSet?(Properties) - Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet.userPropertiesToSetOnce?(Properties) - Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
Returns
void
Examples
basic identification
// basic identification
posthog.identify('user_12345')identify with user properties
// identify with user properties
posthog.identify('user_12345', {
email: '[email protected]',
plan: 'premium'
})identify with set and set_once properties
// identify with set and set_once properties
posthog.identify('user_12345',
{ last_login: new Date() }, // updates every time
{ signup_date: new Date() } // sets only once
)onSessionId()
Release Tag: public
Register an event listener that runs whenever the session id or window id change. If there is already a session id, the listener is called immediately in addition to being called on future changes. Can be used, for example, to sync the PostHog session id with a backend session.
Parameters
callback(SessionIdChangedCallback) - The callback function will be called once a session id is present or when it or the window id are updated.
Returns
() => void
Examples
posthog.onSessionId(function(sessionId, windowId) { // do something })reset()
Release Tag: public
Resets all user data and starts a fresh session.
⚠️ Warning: Only call this when a user logs out. Calling at the wrong time can cause split sessions.
This clears: - Session ID and super properties - User identification (sets new random distinct_id) - Cached data and consent settings
⚠️ Warning: because consent is cleared, reset() returns the instance to the default consent state. With opt_out_capturing_by_default that default is opted out, so calling reset() after opt_in_capturing() silently stops capturing. Always reset() first, then opt in.
Parameters
options?(boolean | ResetOptions) - Boolean to reset the device ID (legacy), or reset options including bootstrap values.
Returns
void
Examples
reset on user logout
// reset on user logout
function logout() {
posthog.reset()
// redirect to login page
}reset and generate new device ID
// reset and generate new device ID
posthog.reset(true) // also resets device_idreset with a custom anonymous ID and bootstrapped feature flags
// reset with a custom anonymous ID and bootstrapped feature flags
posthog.reset({
bootstrap: {
distinctID: myAnonymousID,
isIdentifiedID: false,
featureFlags: { 'my-flag': true },
}
})with opt_out_capturing_by_default, reset() before opting in, never after
// with opt_out_capturing_by_default, reset() before opting in, never after
posthog.reset()
posthog.opt_in_capturing()resetGroups()
Release Tag: public
Resets only the group properties of the user currently logged in. Learn more about groups
Returns
void
Examples
posthog.resetGroups()setInternalOrTestUser()
Release Tag: public
Marks the current user as a test user by setting the $internal_or_test_user person property to true. This also enables person processing for the current user.
This is useful for using in a cohort your internal/test filters for your posthog org.
Returns
void
Examples
// Manually mark as test user
posthog.setInternalOrTestUser()
// Or use internal_or_test_user_hostname config for automatic detection
posthog.init('token', { internal_or_test_user_hostname: 'localhost' })setPersonProperties()
Release Tag: public
Sets properties on the person profile associated with the current distinct_id. Learn more about identifying users
Notes:
Updates user properties that are stored with the person profile in PostHog. If person_profiles is set to identified_only and no profile exists, this will create one.
Parameters
userPropertiesToSet?(Properties) - Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet.userPropertiesToSetOnce?(Properties) - Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
Returns
void
Examples
set user properties
// set user properties
posthog.setPersonProperties({
email: '[email protected]',
plan: 'premium'
})set properties
// set properties
posthog.setPersonProperties(
{ name: 'Max Hedgehog' }, // $set properties
{ initial_url: '/blog' } // $set_once properties
)unsetPersonProperties()
Release Tag: public
Removes properties from the person profile associated with the current distinct_id. Learn more about identifying users
Notes:
Deletes the given person properties from the person profile in PostHog. This is the counterpart to — instead of hand-passing $unset inside a capture() call, you can remove properties with a dedicated method. If person_profiles is set to never, this call is ignored.
$fbc and $fbp read by the SDK are unset for this call only. save_campaign_params: false stops the reads.
Parameters
propertyNames(string | string[]) - The name (or names) of the person properties to remove.
Returns
void
Examples
remove a single property
// remove a single property
posthog.unsetPersonProperties('plan')remove multiple properties
// remove multiple properties
posthog.unsetPersonProperties(['plan', 'email'])Surveys methods
cancelPendingSurvey()
Release Tag: public
Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay).
Parameters
surveyId(string) - The survey ID whose pending display should be cancelled.
Returns
void
Examples
// Generated example for cancelPendingSurvey
posthog.cancelPendingSurvey();canRenderSurvey()
Release Tag: deprecated
Checks the feature flags associated with this Survey to see if the survey can be rendered. This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded. Use canRenderSurveyAsync instead.
Parameters
surveyId(string) - The ID of the survey to check.
Returns
Union of:
SurveyRenderReasonnull
Examples
// Generated example for canRenderSurvey
posthog.canRenderSurvey();canRenderSurveyAsync()
Release Tag: public
Checks the feature flags associated with this Survey to see if the survey can be rendered.
Parameters
surveyId(string) - The ID of the survey to check.forceReload?(boolean) - If true, the survey will be reloaded from the server, Default: false
Returns
Promise<SurveyRenderReason>
Examples
posthog.canRenderSurveyAsync(surveyId).then((result) => {
if (result.visible) {
// Survey can be rendered
console.log('Survey can be rendered')
} else {
// Survey cannot be rendered
console.log('Survey cannot be rendered:', result.disabledReason)
}
})displaySurvey()
Release Tag: public
Display a survey programmatically as either a popover or inline element.
Parameters
surveyId(string) - The survey ID to display.options?(DisplaySurveyOptions) - Display configuration. Defaults to a popover that respects dashboard conditions and delays.
Returns
void
Examples
Display as popover (respects all conditions defined in the dashboard)
// Display as popover (respects all conditions defined in the dashboard)
posthog.displaySurvey('survey-id-123')Display inline in a specific element
// Display inline in a specific element
posthog.displaySurvey('survey-id-123', {
displayType: DisplaySurveyType.Inline,
ignoreConditions: false,
ignoreDelay: false,
selector: '#survey-container'
})Force display ignoring conditions and delays
// Force display ignoring conditions and delays
posthog.displaySurvey('survey-id-123', {
displayType: DisplaySurveyType.Popover,
ignoreConditions: true,
ignoreDelay: true
})getActiveMatchingSurveys()
Release Tag: public
Get surveys that should be enabled for the current user. See fetching surveys documentation for more details.
Parameters
callback(SurveyCallback) - The callback function will be called when the surveys are loaded or updated.forceReload?(boolean) - Whether to force a reload of the surveys.
Returns
void
Examples
posthog.getActiveMatchingSurveys((surveys) => {
// do something
})getSurveys()
Release Tag: public
Get list of all surveys.
Parameters
callback(SurveyCallback) - Function that receives the array of surveys.forceReload?(boolean) - Optional boolean to force an API call for updated surveys.
Returns
void
Examples
function callback(surveys, context) {
// do something
}
posthog.getSurveys(callback, false)onActiveMatchingSurveysChanged()
Release Tag: public
Register an event listener that runs when the set of active matching surveys changes. The listener receives the initial matching set and updates after event/action triggers, cancellation, consumption, session expiry, definitions refresh, captured pageviews, feature-flag updates, marking a survey as seen, and reset. Unchanged results are suppressed.
URL conditions are re-evaluated on captured $pageview events, including automatic SPA pageviews when capture_pageview is 'history_change'. With automatic pageviews disabled, capture $pageview after navigation. This does not observe arbitrary DOM mutations or time passing; selector, device and wait-period conditions are checked on the supported updates.
The optional callback context distinguishes load errors from a successfully loaded empty result. New subscribers receive the current snapshot without replaying earlier errors: a settled unavailable state is ([], { isLoaded: false }), while usable cached definitions are evaluated normally. An initial load already in progress delivers when it resolves. Recoverable load failures keep the subscription alive. Unsubscribing prevents any further delivery, including callbacks from an outstanding initial request.
Parameters
callback(SurveyCallback) - The callback to call with active matching surveys.
Returns
() => void
Examples
const unsubscribe = posthog.onActiveMatchingSurveysChanged((surveys) => {
// respond to changes in currently matching surveys
})onSurveysLoaded()
Release Tag: public
Register an event listener that runs when surveys are loaded. Callback parameters: - surveys: Survey[]: An array containing all survey objects fetched from PostHog using the getSurveys method - context: isLoaded: boolean, error?: string : An object indicating if the surveys were loaded successfully
Parameters
callback(SurveyCallback) - The callback function will be called when surveys are loaded or updated.
Returns
() => void
Examples
posthog.onSurveysLoaded((surveys, context) => { // do something })renderSurvey()
Release Tag: deprecated
Although we recommend using popover surveys and display conditions, if you want to show surveys programmatically without setting up all the extra logic needed for API surveys, you can render surveys programmatically with the renderSurvey method. This takes a survey ID and an HTML selector to render an unstyled survey.
Parameters
surveyId(string) - The ID of the survey to render.selector(string) - The selector of the HTML element to render the survey on.
Returns
void
Examples
posthog.renderSurvey(coolSurveyID, '#survey-container')Capture methods
capture()
Release Tag: public
Captures an event with optional properties and configuration.
Notes:
You can capture arbitrary object-like values as events. Learn about capture best practices
Parameters
event_name(EventName) - The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase')properties?(Properties | null) - Properties to include with the event describing the user or event detailsoptions?(CaptureOptions) - Optional configuration for the capture request
Returns
Union of:
CaptureResultundefined
Examples
// basic event capture
posthog.capture('cta-button-clicked', {
button_name: 'Get Started',
page: 'homepage'
})on()
Release Tag: public
Exposes a set of events that PostHog will emit. e.g. eventCaptured is emitted immediately before trying to send an event
Unlike onFeatureFlags and onSessionId these are not called when the listener is registered, the first callback will be the next event after registering a listener
Available events: - eventCaptured: Emitted immediately before trying to send an event - featureFlagsReloading: Emitted when feature flags are being reloaded (e.g. after identify(), group(), or reloadFeatureFlags())
Parameters
event('eventCaptured' | 'featureFlagsReloading') - The event to listen for.cb((...args: any[]) => void) - The callback function to call when the event is emitted.
Returns
() => void
Examples
posthog.on('eventCaptured', (event) => {
console.log(event)
})Track when feature flags are reloading to show a loading state
// Track when feature flags are reloading to show a loading state
posthog.on('featureFlagsReloading', () => {
console.log('Feature flags are being reloaded...')
})register_for_session()
Release Tag: public
Registers super properties for the current session only.
Notes:
Session super properties are automatically added to all events during the current browser session. Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage.
Parameters
properties(Properties) - An associative array of properties to store about the user
Returns
void
Examples
register session-specific properties
// register session-specific properties
posthog.register_for_session({
current_page_type: 'checkout',
ab_test_variant: 'control'
})register properties for user flow tracking
// register properties for user flow tracking
posthog.register_for_session({
selected_plan: 'pro',
completed_steps: 3,
flow_id: 'signup_flow_v2'
})register_once()
Release Tag: public
Registers super properties only if they haven't been set before.
Notes:
Unlike register(), this method will not overwrite existing super properties. Use this for properties that should only be set once, like signup date or initial referrer.
Parameters
properties(Properties) - An associative array of properties to store about the userdefault_value?(Property) - Value to override if already set in super properties (ex: 'False') Default: 'None'days?(number) - How many days since the users last visit to store the super properties
Returns
void
Examples
register once-only properties
// register once-only properties
posthog.register_once({
first_login_date: new Date().toISOString(),
initial_referrer: document.referrer
})override existing value if it matches default
// override existing value if it matches default
posthog.register_once(
{ user_type: 'premium' },
'unknown' // overwrite if current value is 'unknown'
)register()
Release Tag: public
Registers super properties that are included with all events.
Notes:
Super properties are stored in persistence and automatically added to every event you capture. These values will overwrite any existing super properties with the same keys.
Parameters
properties(Properties) - properties to store about the userdays?(number) - How many days since the user's last visit to store the super properties
Returns
void
Examples
register a single property
// register a single property
posthog.register({ plan: 'premium' })register multiple properties
// register multiple properties
posthog.register({
email: '[email protected]',
account_type: 'business',
signup_date: '2023-01-15'
})register with custom expiration
// register with custom expiration
posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 daysunregister_for_session()
Release Tag: public
Removes a session super property from the current session.
Notes:
This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage.
Parameters
property(string) - The name of the session super property to remove
Returns
void
Examples
// remove a session property
posthog.unregister_for_session('current_flow')unregister()
Release Tag: public
Removes a super property from persistent storage.
Notes:
This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile.
Parameters
property(string) - The name of the super property to remove
Returns
void
Examples
// remove a super property
posthog.unregister('plan_type')Logs methods
captureLog()
Release Tag: public
Capture a log entry and send it to the PostHog logs endpoint.
Parameters
options(CaptureLogOptions) - The log entry options
Returns
void
Examples
posthog.captureLog({
body: 'checkout completed',
level: 'info',
attributes: { order_id: 'ord_789', amount_cents: 4999 },
})LLM analytics methods
captureTraceFeedback()
Release Tag: public
Capture written user feedback for a LLM trace. Numeric values are converted to strings.
Parameters
traceId(string | number) - The trace ID to capture feedback for.userFeedback(string) - The feedback to capture.
Returns
void
Examples
// Generated example for captureTraceFeedback
posthog.captureTraceFeedback();captureTraceMetric()
Release Tag: public
Capture a metric for a LLM trace. Numeric values are converted to strings.
Parameters
traceId(string | number) - The trace ID to capture the metric for.metricName(string) - The name of the metric to capture.metricValue(string | number | boolean) - The value of the metric to capture.
Returns
void
Examples
// Generated example for captureTraceMetric
posthog.captureTraceMetric();Privacy methods
clear_opt_in_out_capturing()
Release Tag: public
Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
Returns
void
Examples
// Generated example for clear_opt_in_out_capturing
posthog.clear_opt_in_out_capturing();has_opted_in_capturing()
Release Tag: public
Checks if the user has opted into data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
Returns
boolean
Examples
if (posthog.has_opted_in_capturing()) {
// show analytics features
}has_opted_out_capturing()
Release Tag: public
Checks if the user has opted out of data capturing.
Notes:
Returns the current consent status for event tracking and data persistence.
In cookieless 'always' mode this returns true, because the SDK does not store data for the user. Events are still captured in this mode. To check if the SDK captures events, use is_capturing().
Returns
boolean
Examples
if (posthog.has_opted_out_capturing()) {
// disable analytics features
}is_capturing()
Release Tag: public
Checks whether the PostHog library is currently capturing events.
Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by some config options.
Additionally, if the cookieless_mode is set to 'on_reject', we will capture events in cookieless mode if the user has opted out or been defaulted to opt-out.
Returns
boolean
Examples
// Generated example for is_capturing
posthog.is_capturing();opt_in_capturing()
Release Tag: public
Opts the user into data capturing and persistence.
Notes:
Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an $opt_in event unless disabled. The event is only captured when the user was not already opted in, so calling this on every page load (for example from a consent tool callback that re-applies stored consent) sends it once per user rather than once per page.
Parameters
options?({ captureEventName?: EventName | null | false; /** event name to be used for capturing the opt-in action */ captureProperties?: Properties; /** set of properties to be captured along with the opt-in action */ }) - A dictionary of opt-in options.
Returns
void
Examples
simple opt-in
// simple opt-in
posthog.opt_in_capturing()opt-in with custom event and properties
// opt-in with custom event and properties
posthog.opt_in_capturing({
captureEventName: 'Privacy Accepted',
captureProperties: { source: 'banner' }
})opt-in without capturing event
// opt-in without capturing event
posthog.opt_in_capturing({
captureEventName: false
})opt_out_capturing()
Release Tag: public
Opts the user out of data capturing and persistence.
Notes:
Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance. If opt_out_persistence_by_default is true, SDK persistence will also be disabled.
Returns
void
Examples
// opt user out (e.g., on privacy settings page)
posthog.opt_out_capturing()Initialization methods
debug()
Release Tag: public
Enables or disables debug mode for detailed logging.
Notes:
Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding ?__posthog_debug=true to the URL.
Parameters
debug?(boolean) - If true, will enable debug mode.
Returns
void
Examples
enable debug mode
// enable debug mode
posthog.debug(true)disable debug mode
// disable debug mode
posthog.debug(false)getPageViewId()
Release Tag: public
Returns the current page view ID.
Returns
Union of:
stringundefined
Examples
// Generated example for getPageViewId
posthog.getPageViewId();init()
Release Tag: public
Initializes a new instance of the PostHog capturing object.
Notes:
All new instances are added to the main posthog object as sub properties (such as posthog.library_name) and also returned by this function. Learn more about configuration options
Parameters
token(string) - Your PostHog API tokenconfig?(OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>>) - A dictionary of config options to overridename?(string) - The name for the new posthog instance that you want created
Returns
PostHog
Examples
basic initialization
// basic initialization
posthog.init('<ph_project_api_key>', {
api_host: '<ph_client_api_host>'
})multiple instances
// multiple instances
posthog.init('<ph_project_api_key>', {}, 'project1')
posthog.init('<ph_project_api_key>', {}, 'project2')set_config()
Release Tag: public
Updates the configuration of the PostHog instance.
Parameters
config(Partial<PostHogConfig>) - A dictionary of new configuration values to update
Returns
void
Examples
// Generated example for set_config
posthog.set_config();Session replay methods
get_session_replay_url()
Release Tag: public
Returns the Replay url for the current session.
Parameters
options?({ withTimestamp?: boolean; timestampLookBack?: number; }) - Options for the URL.
Returns
string
Examples
basic usage
// basic usage
posthog.get_session_replay_url()timestamp
// timestamp
posthog.get_session_replay_url({ withTimestamp: true })timestamp and lookback
// timestamp and lookback
posthog.get_session_replay_url({
withTimestamp: true,
timestampLookBack: 30 // look back 30 seconds
})sessionRecordingStarted()
Release Tag: public
returns a boolean indicating whether session recording is currently running
Returns
boolean
Examples
// Stop session recording if it's running
if (posthog.sessionRecordingStarted()) {
posthog.stopSessionRecording()
}startSessionRecording()
Release Tag: public
turns session recording on, and updates the config option disable_session_recording to false
Parameters
override?({ sampling?: boolean; linked_flag?: boolean; url_trigger?: true; event_trigger?: true; } | true) - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config.trueis shorthand for sampling: true, linked_flag: true
Returns
void
Examples
Start and ignore controls
// Start and ignore controls
posthog.startSessionRecording(true)Start and override controls
// Start and override controls
posthog.startSessionRecording({
// you don't have to send all of these
sampling: true || false,
linked_flag: true || false,
url_trigger: true || false,
event_trigger: true || false
})stopSessionRecording()
Release Tag: public
turns session recording off, and updates the config option disable_session_recording to true
Returns
void
Examples
// Stop session recording
posthog.stopSessionRecording()Feature flags methods
getEarlyAccessFeatures()
Release Tag: public
Get the list of early access features. To check enrollment status, use isFeatureEnabled. Learn more in the docs
Parameters
callback(EarlyAccessFeatureCallback) - The callback function will be called when the early access features are loaded.force_reload?(boolean) - Whether to force a reload of the early access features.stages?(EarlyAccessFeatureStage[]) - The stages of the early access features to load.
Returns
void
Examples
const posthog = usePostHog()
const activeFlags = useActiveFeatureFlags()
const [activeBetas, setActiveBetas] = useState([])
const [inactiveBetas, setInactiveBetas] = useState([])
const [comingSoonFeatures, setComingSoonFeatures] = useState([])
useEffect(() => {
posthog.getEarlyAccessFeatures((features) => {
// Filter features by stage
const betaFeatures = features.filter(feature => feature.stage === 'beta')
const conceptFeatures = features.filter(feature => feature.stage === 'concept')
setComingSoonFeatures(conceptFeatures)
if (!activeFlags || activeFlags.length === 0) {
setInactiveBetas(betaFeatures)
return
}
const activeBetas = betaFeatures.filter(
beta => activeFlags.includes(beta.flagKey)
);
const inactiveBetas = betaFeatures.filter(
beta => !activeFlags.includes(beta.flagKey)
);
setActiveBetas(activeBetas)
setInactiveBetas(inactiveBetas)
}, true, ['concept', 'beta'])
}, [activeFlags])getFeatureFlag()
Release Tag: public
Gets the value of a feature flag for the current user.
Notes:
Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values. An evaluated boolean flag returns true or false; undefined means no current evaluation is available for the key. Globally inactive flags are omitted from the remote /flags response, so after that response loads they are unavailable rather than represented by a false result.
Parameters
key(string) - Key of the feature flag.options?(FeatureFlagOptions) - Optional lookup settings. If{ send_event: false }, we won't send a$feature_flag_calledevent to PostHog. If{ fresh: true }, we won't return cached values from localStorage - only values loaded from the server.
Returns
Union of:
booleanstringundefined
Examples
check boolean flag
// check boolean flag
if (posthog.getFeatureFlag('new-feature')) {
// show new feature
}check multivariate flag
// check multivariate flag
const variant = posthog.getFeatureFlag('button-color')
if (variant === 'red') {
// show red button
}getFeatureFlagPayload()
Release Tag: deprecated
Get feature flag payload value matching key for user (supports multivariate flags).
Parameters
key(string) - Key of the feature flag.
Returns
JsonType
Examples
const betaFeature = posthog.getFeatureFlagResult('beta-feature')
if (betaFeature?.variant === 'some-value') {
const someValue = betaFeature?.payload
// do something
}getFeatureFlagResult()
Release Tag: public
Get a feature flag evaluation result including both the flag value and payload.
A result with enabled: false is a conclusive off evaluation. undefined means no current evaluation is available for the key. This includes globally inactive flags, which are omitted from the remote /flags response.
By default, this method emits the $feature_flag_called event.
Parameters
key(string) - Key of the feature flag.options?(FeatureFlagOptions) - Options for the feature flag lookup.
Returns
Union of:
FeatureFlagResultundefined
Examples
const result = posthog.getFeatureFlagResult('my-flag')
if (result?.enabled) {
console.log('Flag is enabled with payload:', result.payload)
}multivariate flag
// multivariate flag
const result = posthog.getFeatureFlagResult('button-color')
if (result?.variant === 'red') {
showRedButton(result.payload)
}isFeatureEnabled()
Release Tag: public
Checks if a feature flag is enabled for the current user.
Notes:
Returns true or false when the flag has an evaluation value. A false result means the value evaluated off; it does not mean the SDK observed the flag's global active setting. Returns undefined when no current evaluation is available, unless defaultValue is given. Globally inactive flags are omitted from the remote /flags response and therefore have no value. This is a convenience method that treats any truthy value as enabled.
Parameters
key(string) - Key of the feature flag.options(IsFeatureEnabledOptions & { defaultValue: boolean; }) - Optional lookup settings. If{ send_event: false }, we won't send a$feature_flag_calledevent to PostHog. If{ fresh: true }, we won't return cached values from localStorage - only values loaded from the server. If{ defaultValue: false }, we return that value instead of undefined when the flag has no value.
Returns
boolean
Examples
simple feature flag check
// simple feature flag check
if (posthog.isFeatureEnabled('new-checkout')) {
showNewCheckout()
}disable event tracking
// disable event tracking
if (posthog.isFeatureEnabled('feature', { send_event: false })) {
// flag checked without sending $feature_flag_called event
}onFeatureFlags()
Release Tag: public
Register an event listener that runs when feature flags become available or when they change. If there are flags, the listener is called immediately in addition to being called on future changes. Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser, including when another open tab of your site stores new flags. Do not call reloadFeatureFlags() inside this callback: each reload in one tab triggers the callback in the other tabs, which can send flag requests in a loop.
Parameters
callback(FeatureFlagsCallback) - The callback function will be called once the feature flags are ready or when they are updated. It'll return a list of feature flags enabled for the user, the variants, and also a context object indicating whether we succeeded to fetch the flags or not.
Returns
() => void
Examples
posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
// do something
})reloadFeatureFlags()
Release Tag: public
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.
Returns
void
Examples
posthog.reloadFeatureFlags()resetGroupPropertiesForFlags()
Release Tag: public
Resets the group properties for feature flags.
Parameters
group_type?(string) - Optional group type to reset. If omitted, all group properties are reset.
Returns
void
Examples
posthog.resetGroupPropertiesForFlags()resetPersonPropertiesForFlags()
Release Tag: public
Resets the person properties for feature flags.
Parameters
reloadFeatureFlags?(boolean) - Whether to reload feature flags.
Returns
void
Examples
posthog.resetPersonPropertiesForFlags()Reset properties without reloading
// Reset properties without reloading
posthog.resetPersonPropertiesForFlags(false)setGroupPropertiesForFlags()
Release Tag: public
Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type.
Parameters
properties({ [type: string]: Properties; }) - The properties to override, the key of which is the group type.reloadFeatureFlags?(boolean) - Whether to reload feature flags.
Returns
void
Examples
Set properties with reload
// Set properties with reload
posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })Set properties without reload
// Set properties without reload
posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false)setPersonPropertiesForFlags()
Release Tag: public
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:
Parameters
properties(Properties) - The properties to override.reloadFeatureFlags?(boolean) - Whether to reload feature flags.
Returns
void
Examples
Set properties
// Set properties
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})Set properties without reloading
// Set properties without reloading
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)updateEarlyAccessFeatureEnrollment()
Release Tag: public
Opt the user in or out of an early access feature. Learn more in the docs
Parameters
key(string) - The key of the feature flag to update.isEnrolled(boolean) - Whether the user is enrolled in the feature.stage?(string) - The stage of the feature flag to update.
Returns
void
Examples
const toggleBeta = (betaKey) => {
if (activeBetas.some(
beta => beta.flagKey === betaKey
)) {
posthog.updateEarlyAccessFeatureEnrollment(
betaKey,
false
)
setActiveBetas(
prevActiveBetas => prevActiveBetas.filter(
item => item.flagKey !== betaKey
)
);
return
}
posthog.updateEarlyAccessFeatureEnrollment(
betaKey,
true
)
setInactiveBetas(
prevInactiveBetas => prevInactiveBetas.filter(
item => item.flagKey !== betaKey
)
);
}
const registerInterest = (featureKey) => {
posthog.updateEarlyAccessFeatureEnrollment(
featureKey,
true
)
// Update UI to show user has registered
}updateFlags()
Release Tag: public
Manually update feature flag values without making a network request. This is useful when you have feature flag values from an external source (e.g., server-side evaluation, edge middleware) and want to inject them into the client SDK.
Parameters
flags(Record<string, boolean | string>) - An object mapping flag keys to their values (boolean or string variant)payloads?(Record<string, JsonType>) - Optional object mapping flag keys to their JSON payloadsoptions?({ merge?: boolean; }) - Optional settings. Use{ merge: true }to merge with existing flags instead of replacing.
Returns
void
Examples
// Replace all flags with server-evaluated values
posthog.updateFlags({
'my-flag': true,
'my-experiment': 'variant-a'
})
// Merge with existing flags (update only specified flags)
posthog.updateFlags(
{ 'my-flag': true },
undefined,
{ merge: true }
)
// With payloads
posthog.updateFlags(
{ 'my-flag': true },
{ 'my-flag': { some: 'data' } }
)Toolbar methods
loadToolbar()
Release Tag: public
returns a boolean indicating whether the toolbar loaded
Parameters
params(ToolbarParams) - Toolbar parameters.
Returns
boolean
Examples
// Generated example for loadToolbar
posthog.loadToolbar();Lifecycle methods
shutdown()
Release Tag: public
Flushes any queued events and resolves once teardown is complete.
Notes:
This exists primarily for parity with the server-side Node.js SDK, whose shutdown() you call once before a process exits. In the browser there is no process to exit, so this method performs synchronous best-effort extension cleanup, flushes the request queues, and always resolves.
It is safe to call in isomorphic teardown code (for example a Nuxt/Next module that calls shutdown() on both the server and the client) so the same symmetric cleanup works in either environment without throwing.
Parameters
_shutdownTimeoutMs?(number) - Retained for parity with the Node.js SDK; ignored in browsers.
Returns
Promise<void>
Examples
// symmetric teardown that runs on both server and client
await posthog.shutdown()Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-integration · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-integration.zip