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-node.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
PostHog Node.js SDK
PostHog Node.js SDK allows you to capture events and send them to PostHog from your Node.js applications.
Categories
Initialization
Identification
Capture
Error tracking
Privacy
Feature flags
Traces
Context
PostHog
Other methods
getLibraryId()
Release Tag: public
Returns
string
Examples
// Generated example for getLibraryId
posthog.getLibraryId();enterContext()
Release Tag: public
Set context without a callback wrapper.
Uses AsyncLocalStorage.enterWith() to attach context to the current async execution context. The context lives until that async context ends.
Must be called in the same async scope that makes PostHog calls. Calling this outside a request-scoped async context will leak context across unrelated work. Prefer withContext() when you can wrap code in a callback — it creates an isolated scope that cleans up automatically.
Parameters
data(Partial<ContextData>) - Context data to apply (distinctId, sessionId, properties)options?(ContextOptions) - Context options (fresh: true to start with clean context instead of inheriting)
Returns
void
Examples
// Generated example for enterContext
posthog.enterContext();flush()
Release Tag: public
Returns
Promise<void>
Examples
// Generated example for flush
posthog.flush();prepareEventMessage()
Release Tag: public
Parameters
props(EventMessage)
Returns
Promise<{ distinctId: string; event: string; properties: PostHogEventProperties; options: PostHogCaptureOptions; }>
Examples
// Generated example for prepareEventMessage
posthog.prepareEventMessage();fetch()
Release Tag: public
Parameters
url(string)options(PostHogFetchOptions)
Returns
Promise<PostHogFetchResponse>
Examples
// Generated example for fetch
posthog.fetch();getSurveysStateless()
Release Tag: public
** SURVEYS *
Returns
Promise<SurveyResponse['surveys']>
Examples
// Generated example for getSurveysStateless
posthog.getSurveysStateless();on()
Release Tag: public
Parameters
event(string)cb((...args: any[]) => void)
Returns
() => void
Examples
// Generated example for on
posthog.on();optIn()
Release Tag: public
Returns
Promise<void>
Examples
// Generated example for optIn
posthog.optIn();optOut()
Release Tag: public
Returns
Promise<void>
Examples
// Generated example for optOut
posthog.optOut();register()
Release Tag: public
Parameters
properties(PostHogEventProperties)
Returns
Promise<void>
Examples
// Generated example for register
posthog.register();unregister()
Release Tag: public
Parameters
property(string)
Returns
Promise<void>
Examples
// Generated example for unregister
posthog.unregister();Initialization methods
PostHog()
Release Tag: public
Initialize a new PostHog client instance.
Parameters
apiKey(string) - Your PostHog project API keyoptions?(PostHogOptions) - Configuration options for the client
Returns
any
Examples
Basic initialization
// Basic initialization
const client = new PostHogBackendClient(
'your-api-key',
{ host: 'https://app.posthog.com' }
)With a secret key (Personal API Key or Project Secret API Key) for local evaluation
// With a secret key (Personal API Key or Project Secret API Key) for local evaluation
const client = new PostHogBackendClient(
'your-api-key',
{
host: 'https://app.posthog.com',
secretKey: 'your-secret-key'
}
)debug()
Release Tag: public
Enable or disable debug logging.
Parameters
enabled?(boolean) - Whether to enable debug logging
Returns
void
Examples
Enable debug logging
// Enable debug logging
client.debug(true)Disable debug logging
// Disable debug logging
client.debug(false)getLibraryVersion()
Release Tag: public
Get the library version from package.json.
Returns
string
Examples
// Get version
const version = client.getLibraryVersion()
console.log(`Using PostHog SDK version: ${version}`)getPersistedProperty()
Release Tag: public
Get a persisted property value from memory storage.
Parameters
key(PostHogPersistedProperty) - The property key to retrieve
Returns
Union of:
anyundefined
Examples
Get user ID
// Get user ID
const userId = client.getPersistedProperty('userId')Get session ID
// Get session ID
const sessionId = client.getPersistedProperty('sessionId')setPersistedProperty()
Release Tag: public
Set a persisted property value in memory storage.
Parameters
key(PostHogPersistedProperty) - The property key to setvalue(any | null) - The value to store (null to remove)
Returns
void
Examples
Set user ID
// Set user ID
client.setPersistedProperty('userId', 'user_123')Set session ID
// Set session ID
client.setPersistedProperty('sessionId', 'session_456')shutdown()
Release Tag: public
Shuts down the PostHog instance and ensures all events are sent. Call shutdown() once before the process exits to ensure that all events have been sent and all promises have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it. Use flush() for per-request cleanup instead.
Parameters
shutdownTimeoutMs?(number) - Maximum time to wait for shutdown in milliseconds
Returns
Promise<void>
Examples
// shutdown before process exit
process.on('SIGINT', async () => {
await posthog.shutdown()
process.exit(0)
})Identification methods
alias()
Release Tag: public
Create an alias to link two distinct IDs together.
Parameters
data({ distinctId: string; alias: string; disableGeoip?: boolean; }) - The alias data containing distinctId and alias
Returns
void
Examples
// Link an anonymous user to an identified user
client.alias({
distinctId: 'anonymous_123',
alias: 'user_456'
})aliasImmediate()
Release Tag: public
Create an alias to link two distinct IDs together immediately (synchronously).
Parameters
data({ distinctId: string; alias: string; disableGeoip?: boolean; }) - The alias data containing distinctId and alias
Returns
Promise<void>
Examples
// Link an anonymous user to an identified user immediately
await client.aliasImmediate({
distinctId: 'anonymous_123',
alias: 'user_456'
})getCustomUserAgent()
Release Tag: public
Get the custom user agent string for this client.
Returns
string
Examples
// Get user agent
const userAgent = client.getCustomUserAgent()
// Returns: "posthog-node/5.7.0"groupIdentify()
Release Tag: public
Create or update a group and its properties.
Parameters
{ groupType, groupKey, properties, distinctId, disableGeoip }(any)input(GroupIdentifyMessage)
Returns
void
Examples
Create a company group
// Create a company group
client.groupIdentify({
groupType: 'company',
groupKey: 'acme-corp',
properties: {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500
},
distinctId: 'user_123'
})Update organization properties
// Update organization properties
client.groupIdentify({
groupType: 'organization',
groupKey: 'org-456',
properties: {
plan: 'enterprise',
region: 'US-West'
}
})groupIdentifyImmediate()
Release Tag: public
Create or update a group and its properties immediately (synchronously).
Parameters
{ groupType, groupKey, properties, distinctId, disableGeoip, }(any)input(GroupIdentifyMessage)
Returns
Promise<void>
Examples
// Immediately create or update a company group
await client.groupIdentifyImmediate({
groupType: 'company',
groupKey: 'acme-corp',
properties: {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500
}
})identify()
Release Tag: public
Identify a user and set their properties.
Parameters
{ distinctId, properties, disableGeoip }(any)input(IdentifyMessage)
Returns
void
Examples
Basic identify with properties
// Basic identify with properties
client.identify({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: '[email protected]',
plan: 'premium'
}
})Using $set and $set_once
// Using $set and $set_once
client.identify({
distinctId: 'user_123',
properties: {
$set: { name: 'John Doe', email: '[email protected]' },
$set_once: { first_login: new Date().toISOString() }
$anon_distinct_id: 'anonymous_user_456'
}
})identifyImmediate()
Release Tag: public
Identify a user and set their properties immediately (synchronously).
Parameters
{ distinctId, properties, disableGeoip }(any)input(IdentifyMessage)
Returns
Promise<void>
Examples
// Basic immediate identify
await client.identifyImmediate({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: '[email protected]'
}
})setPersonProperties()
Release Tag: public
Set properties on a person profile.
Parameters
{ distinctId, properties, propertiesOnce }(any)input(SetPersonPropertiesMessage)
Returns
void
Examples
client.setPersonProperties({
distinctId: 'user_123',
properties: { plan: 'premium' },
propertiesOnce: { first_seen: '2026-06-15' }
})unsetPersonProperties()
Release Tag: public
Remove properties from a person profile.
Parameters
{ distinctId, properties }(any)input(UnsetPersonPropertiesMessage)
Returns
void
Examples
client.unsetPersonProperties({
distinctId: 'user_123',
properties: ['plan', 'email']
})Capture methods
capture()
Release Tag: public
Capture an event manually.
Parameters
props(EventMessage) - The event properties
Returns
void
Examples
// Basic capture
client.capture({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' }
})captureAi()
Release Tag: public
Capture an AI event on the dedicated AI capture endpoint. Beta: the signature is stable; operational limits (per-event size cap, batching, endpoint) may change without notice. Delivery is async, and no redaction or truncation is applied to the payload.
Parameters
props(EventMessage) - The event properties
Returns
Union of:
stringundefined
Examples
// Generated example for captureAi
posthog.captureAi();captureAiImmediate()
Release Tag: public
Capture an AI event on the dedicated AI capture endpoint, resolving after the send completes. Use in short-lived processes (serverless) where the runtime may freeze before a background flush runs.
Parameters
props(EventMessage) - The event properties
Returns
Union of:
Promise<stringundefined>
Examples
// Generated example for captureAiImmediate
posthog.captureAiImmediate();captureImmediate()
Release Tag: public
Capture an event immediately (synchronously).
Parameters
props(EventMessage) - The event properties
Returns
Promise<void>
Examples
Basic immediate capture
// Basic immediate capture
await client.captureImmediate({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' }
})With feature flags
// With feature flags
await client.captureImmediate({
distinctId: 'user_123',
event: 'user_action',
sendFeatureFlags: true
})With custom feature flags options
// With custom feature flags options
await client.captureImmediate({
distinctId: 'user_123',
event: 'user_action',
sendFeatureFlags: {
onlyEvaluateLocally: true,
personProperties: { plan: 'premium' },
groupProperties: { org: { tier: 'enterprise' } }
flagKeys: ['flag1', 'flag2']
}
})Error tracking methods
captureException()
Release Tag: public
Capture an error exception as an event.
Parameters
error(unknown) - The error to capturedistinctId?(string) - Optional user distinct IDadditionalProperties?(Record<string | number, any>) - Optional additional properties to includeuuid?(EventMessage['uuid']) - Optional event UUIDflags?(FeatureFlagEvaluations) - OptionalFeatureFlagEvaluationssnapshot to attach the same flag context as your other events
Returns
void
Examples
Capture an error with user ID
// Capture an error with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
client.captureException(error, 'user_123')
}Capture with additional properties
// Capture with additional properties
try {
apiCall()
} catch (error) {
client.captureException(error, 'user_123', {
endpoint: '/api/users',
method: 'POST',
status_code: 500
})
}captureExceptionImmediate()
Release Tag: public
Capture an error exception as an event immediately (synchronously).
Parameters
error(unknown) - The error to capturedistinctId?(string) - Optional user distinct IDadditionalProperties?(Record<string | number, any>) - Optional additional properties to includeflags?(FeatureFlagEvaluations) - OptionalFeatureFlagEvaluationssnapshot to attach the same flag context as your other events
Returns
Promise<void>
Examples
Capture an error immediately with user ID
// Capture an error immediately with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
await client.captureExceptionImmediate(error, 'user_123')
}Capture with additional properties
// Capture with additional properties
try {
apiCall()
} catch (error) {
await client.captureExceptionImmediate(error, 'user_123', {
endpoint: '/api/users',
method: 'POST',
status_code: 500
})
}Privacy methods
disable()
Release Tag: public
Disable the PostHog client (opt-out).
Returns
Promise<void>
Examples
// Disable client
await client.disable()
// Client is now disabled and will not capture eventsenable()
Release Tag: public
Enable the PostHog client (opt-in).
Returns
Promise<void>
Examples
// Enable client
await client.enable()
// Client is now enabled and will capture eventsFeature flags methods
evaluateFlags()
Release Tag: public
Evaluate all feature flags for a user in a single call and return a snapshot. Branch on .isEnabled() / .getFlag(), then pass the same snapshot to capture() via the flags option so the captured event carries the exact flag values the code branched on.
Prefer this over repeated isFeatureEnabled() / getFeatureFlag() calls and over capture({ sendFeatureFlags: true }) — it consolidates flag evaluation into a single /flags request per incoming request.
Local evaluation is transparent. When the poller can resolve a flag from cached definitions, no network call is made and the snapshot's $feature_flag_called events are tagged locally_evaluated: true. A requested key missing from local definitions is included in a /flags fallback unless onlyEvaluateLocally is true. Locally resolved values remain authoritative when remote results are merged. In particular, a cached inactive definition is a conclusive false result locally, while remote evaluation omits globally inactive flags and therefore leaves those keys absent.
Exposure events. isEnabled() and getFlag() send a $feature_flag_called event the first time each flag value is read for a user. Experiments use these events as exposures. The client's sendFeatureFlagEvent option sets the default for these reads. Pass { sendFeatureFlagEvents: true } or { sendFeatureFlagEvents: false } to a read to override it, so one snapshot can serve both experiment flags and flags that should send no events. getFlagPayload() never sends events.
Trim the request. Pass flagKeys to scope local evaluation, the underlying /flags request, and the returned snapshot to a subset of flags. Remote evaluation responses are not cached, so a key missing both locally and remotely costs one /flags request per evaluateFlags() call.
Trim the event payload. Use flags.only([...]) or flags.onlyAccessed() to filter which flags get attached to a captured event without re-fetching.
Parameters
options?(AllFlagsOptions) - Optional configuration for flag evaluation. Supports the same fields asgetAllFlags().flagKeysscopes local evaluation, the/flagsrequest, and the returned snapshot.onlyEvaluateLocallyprevents fallback and leaves unresolved keys absent; the snapshot'sunresolvedFlagslists them with a reason.
Returns
Promise<FeatureFlagEvaluations>
Examples
Basic usage:
const flags = await client.evaluateFlags('user_123', {
personProperties: { plan: 'enterprise' },
})
if (flags.isEnabled('new-dashboard')) {
renderNewDashboard()
}
client.capture({ distinctId: 'user_123', event: 'page_viewed', flags })Scope the request to specific keys:
const flags = await client.evaluateFlags('user_123', {
flagKeys: ['new-dashboard', 'checkout-flow'],
personProperties: { plan: 'enterprise' },
})Attach only the flags the developer actually checked:
const flags = await client.evaluateFlags('user_123')
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ distinctId: 'user_123', event: 'page_viewed', flags: flags.onlyAccessed() })Use to avoid repeating the distinctId:
await client.withContext({ distinctId: 'user_123' }, async () => {
const flags = await client.evaluateFlags()
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ event: 'page_viewed', flags })
})getAllFlags()
Release Tag: public
Get all feature flag values for a specific user.
Parameters
options?(AllFlagsOptions) - Optional configuration for flag evaluation
Returns
Promise<Record<string, FeatureFlagValue>>
Examples
Get all flags for a user
// Get all flags for a user
const allFlags = await client.getAllFlags('user_123')
console.log('User flags:', allFlags)
// Output: { 'flag-1': 'variant-a', 'flag-2': false, 'flag-3': 'variant-b' }With specific flag keys
// With specific flag keys
const specificFlags = await client.getAllFlags('user_123', {
flagKeys: ['flag-1', 'flag-2']
})With groups and properties
// With groups and properties
const orgFlags = await client.getAllFlags('user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})getAllFlagsAndPayloads()
Release Tag: public
Get all feature flag values and payloads for a specific user.
Parameters
options?(AllFlagsOptions) - Optional configuration for flag evaluation
Returns
Promise<PostHogFlagsAndPayloadsResponse>
Examples
Get all flags and payloads for a user
// Get all flags and payloads for a user
const result = await client.getAllFlagsAndPayloads('user_123')
console.log('Flags:', result.featureFlags)
console.log('Payloads:', result.featureFlagPayloads)With specific flag keys
// With specific flag keys
const result = await client.getAllFlagsAndPayloads('user_123', {
flagKeys: ['flag-1', 'flag-2']
})Only evaluate locally
// Only evaluate locally
const result = await client.getAllFlagsAndPayloads('user_123', {
onlyEvaluateLocally: true
})getFeatureFlag()
Release Tag: deprecated
Get the value of a feature flag for a specific user.
A boolean false is a conclusive off evaluation. undefined means no result is available, for example because the key was not returned or local-only evaluation was inconclusive. Local evaluation resolves cached inactive definitions to false; remote evaluation omits globally inactive flags, so the result depends on which evaluation path is available.
Parameters
key(string) - The feature flag keydistinctId(string) - The user's distinct IDoptions?({ groups?: Record<string, string>; personProperties?: Properties; groupProperties?: Record<string, Properties>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation
Returns
Union of:
Promise<FeatureFlagValueundefined>
Examples
Basic feature flag check
// Basic feature flag check
const flagValue = await client.getFeatureFlag('new-feature', 'user_123')
if (flagValue === 'variant-a') {
// Show variant A
} else if (flagValue === 'variant-b') {
// Show variant B
} else {
// Flag evaluated off, or no value was returned
}With groups and properties
// With groups and properties
const flagValue = await client.getFeatureFlag('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' },
groupProperties: { organization: { tier: 'premium' } }
})Only evaluate locally
// Only evaluate locally
const flagValue = await client.getFeatureFlag('local-flag', 'user_123', {
onlyEvaluateLocally: true
})getFeatureFlagEvaluationRuntime()
Release Tag: public
Get where a locally loaded feature flag is meant to be evaluated.
Notes:
Read from the definitions local evaluation already holds, so no request is made. A definition that carries no runtime reports all, the default PostHog applies.
Parameters
key(string) - The feature flag key
Returns
Union of:
FeatureFlagEvaluationRuntimeundefined
Examples
const runtime = client.getFeatureFlagEvaluationRuntime('my-flag')
// Returns: 'client'getFeatureFlagKeysByEvaluationRuntime()
Release Tag: public
Get the keys of locally loaded flags that a runtime can evaluate.
Notes:
A flag set to all suits either runtime, so it is returned for client and for server, and asking for all returns every loaded flag. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.
Parameters
evaluationRuntime(FeatureFlagEvaluationRuntime) - The runtime to match
Returns
string[]
Examples
const clientKeys = client.getFeatureFlagKeysByEvaluationRuntime('client')
// Returns: ['web-banner', 'shared-copy']getFeatureFlagPayload()
Release Tag: deprecated
Get the payload for a feature flag.
Parameters
key(string) - The feature flag keydistinctId(string) - The user's distinct IDmatchValue?(FeatureFlagValue) - Optional match value to get payload foroptions?({ groups?: Record<string, string>; personProperties?: Properties; groupProperties?: Record<string, Properties>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation
Returns
Union of:
Promise<JsonTypeundefined>
Examples
Get payload for a feature flag
// Get payload for a feature flag
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123')
if (payload) {
console.log('Flag payload:', payload)
}Get payload with specific match value
// Get payload with specific match value
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123', 'variant-a')With groups and properties
// With groups and properties
const payload = await client.getFeatureFlagPayload('org-flag', 'user_123', undefined, {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})getFeatureFlagResult()
Release Tag: public
Get the result of evaluating a feature flag, including its value and payload. This is more efficient than calling getFeatureFlag and getFeatureFlagPayload separately when you need both. A result with enabled: false is a conclusive off evaluation; undefined means no evaluation is available. Local evaluation resolves cached inactive definitions to enabled: false, while remote evaluation omits globally inactive flags.
Parameters
key(string) - The feature flag keyoptions?(FlagEvaluationOptions) - Optional configuration for flag evaluation
Returns
Union of:
Promise<FeatureFlagResultundefined>
Examples
Get flag result
// Get flag result
const result = await client.getFeatureFlagResult('my-flag', 'user_123')
if (result) {
console.log('Flag enabled:', result.enabled)
console.log('Variant:', result.variant)
console.log('Payload:', result.payload)
}With groups and properties
// With groups and properties
const result = await client.getFeatureFlagResult('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})getRemoteConfigPayload()
Release Tag: public
Get the remote config payload for a feature flag.
Parameters
flagKey(string) - The feature flag key
Returns
Union of:
Promise<JsonTypeundefined>
Examples
// Get remote config payload
const payload = await client.getRemoteConfigPayload('flag-key')
if (payload) {
console.log('Remote config payload:', payload)
}isFeatureEnabled()
Release Tag: deprecated
Check if a feature flag is enabled for a specific user.
Parameters
key(string) - The feature flag keydistinctId(string) - The user's distinct IDoptions?({ groups?: Record<string, string>; personProperties?: Properties; groupProperties?: Record<string, Properties>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation
Returns
Union of:
Promise<booleanundefined>
Examples
Basic feature flag check
// Basic feature flag check
const isEnabled = await client.isFeatureEnabled('new-feature', 'user_123')
if (isEnabled) {
// Feature is enabled
console.log('New feature is active')
} else {
// Flag evaluated off, or no value was returned
console.log('New feature is not active')
}With groups and properties
// With groups and properties
const isEnabled = await client.isFeatureEnabled('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})isLocalEvaluationReady()
Release Tag: public
Check if local evaluation of feature flags is ready.
Returns
boolean
Examples
// Check if ready
if (client.isLocalEvaluationReady()) {
// Local evaluation is ready, can evaluate flags locally
const flag = await client.getFeatureFlag('flag-key', 'user_123')
} else {
// Local evaluation not ready, will use remote evaluation
const flag = await client.getFeatureFlag('flag-key', 'user_123')
}overrideFeatureFlags()
Release Tag: public
Override feature flags locally. Useful for testing and local development. Overridden flags take precedence over both local evaluation and remote evaluation.
Parameters
overrides(OverrideFeatureFlagsOptions) - Flag overrides configuration
Returns
void
Examples
// Clear all overrides
client.overrideFeatureFlags(false)
// Enable a list of flags (sets them to true)
client.overrideFeatureFlags(['flag-a', 'flag-b'])
// Set specific flag values/variants
client.overrideFeatureFlags({ 'my-flag': 'variant-a', 'other-flag': true })
// Set both flags and payloads
client.overrideFeatureFlags({
flags: { 'my-flag': 'variant-a' },
payloads: { 'my-flag': { discount: 20 } }
})reloadFeatureFlags()
Release Tag: public
Reload feature flag definitions from the configured cache provider or PostHog for local evaluation.
Returns
Promise<void>
Examples
Force reload of feature flags
// Force reload of feature flags
await client.reloadFeatureFlags()
console.log('Feature flags reloaded')Reload before checking a specific flag
// Reload before checking a specific flag
await client.reloadFeatureFlags()
const flag = await client.getFeatureFlag('flag-key', 'user_123')waitForLocalEvaluationReady()
Release Tag: public
Wait for local evaluation of feature flags to be ready.
Parameters
timeoutMs?(number) - Timeout in milliseconds (default: 30000)
Returns
Promise<boolean>
Examples
Wait for local evaluation
// Wait for local evaluation
const isReady = await client.waitForLocalEvaluationReady()
if (isReady) {
console.log('Local evaluation is ready')
} else {
console.log('Local evaluation timed out')
}Wait with custom timeout
// Wait with custom timeout
const isReady = await client.waitForLocalEvaluationReady(10000) // 10 secondsTraces methods
getActiveSpan()
Release Tag: public
The span currently active on this async execution path, or null outside any withSpan callback.
On the edge build this returns null after an await, because the active span is tracked synchronously there.
Subject to change in a minor release.
Returns
Union of:
Spannull
Examples
// Propagate the trace to another service
const traceparent = posthog.getActiveSpan()?.traceparent()
await fetch(url, { headers: traceparent ? { traceparent } : {} })startSpan()
Release Tag: public
Starts a span without making it active — for work that can't wrap a callback. Prefer withSpan, which ends the span for you.
Always returns a handle, so calling code never has to branch: when the traces option is absent, the SDK is disabled, or the user has opted out, the handle is inert and nothing is exported. An inert handle given a parent header still returns it from traceparent(), so a service with tracing off passes a distributed trace through instead of severing it.
Subject to change in a minor release.
Parameters
name(string)options?(StartSpanOptions)
Returns
Span
Examples
const span = posthog.startSpan('checkout', { attributes: { plan: 'pro' } })
span.setAttribute('cart.items', 3)
span.end()withSpan()
Release Tag: public
Runs a callback with a span active for its duration and ends the span for you — at return for a sync callback, at settle for an async one. Takes an optional StartSpanOptions between the name and the callback: withSpan(name, fn) or withSpan(name, options, fn).
Spans started inside the callback nest under it automatically. If the callback throws or rejects, the span records the exception and the original error is rethrown unchanged. A callback that ends the span itself gets the rethrow but not the recording, since the span is already exported by then.
Spans nest across await only on the Node runtime, which tracks the active span with AsyncLocalStorage. The edge build restores the active span when the callback returns its promise, so spans started after an await there begin a new trace.
Subject to change in a minor release.
Parameters
name(string)fn((span: Span) => T)
Returns
T
Examples
await posthog.withSpan('POST /checkout', { parent: req.get('traceparent') }, async (span) => {
span.setAttribute('plan', user.plan)
return processOrder()
})Context methods
getContext()
Release Tag: public
Get the current context data.
Returns
Union of:
ContextDataundefined
Examples
// Get current context within a withContext block
posthog.withContext({ distinctId: 'user_123' }, () => {
const context = posthog.getContext()
console.log(context?.distinctId) // 'user_123'
})withContext()
Release Tag: public
Run a function with specific context that will be applied to all events captured within that context. It propagates the context to all subsequent calls down the call stack. Context properties like tags and sessionId will be automatically attached to all events. By default, nested contexts inherit from parent contexts. Use { fresh: true } to start with a clean context.
Parameters
data(Partial<ContextData>) - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture)fn(() => T) - Function to run with the contextoptions?(ContextOptions) - Context options (fresh: true to start with clean context instead of inheriting)
Returns
T
Examples
posthog.withContext({ distinctId: 'user_123' }, () => {
posthog.capture({ event: 'button clicked' })
})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