Generated banner for Omnibus Instrument Product Analytics
Generated logo for Omnibus Instrument Product Analytics

Omnibus Instrument Product Analytics

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, step-by-step procedure for integrating PostHog product analytics into a wide variety of web, mobile, and backend frameworks. It handles the full lifecycle of the integration, from detecting the project's technology stack and installing the necessary SDKs to implementing event tracking, user identification, and error monitoring. The skill emphasizes non-intrusive changes, ensuring that new analytics code is added alongside existing logic without disrupting the project's architecture.

What it does

  • Detects the project framework and language to determine the correct PostHog SDK.
  • Installs the required PostHog SDK package automatically.
  • Initializes the PostHog instance according to framework-specific best practices.
  • Implements targeted event tracking for key user actions and business logic.
  • Configures user identification flows for login and signup events.
  • Sets up environment variables for secure API key and host management.

When to use it

  • After implementing new features that require tracking for user engagement analysis.
  • When reviewing pull requests to ensure critical user behaviors are being captured.
  • When setting up product analytics for a new project from scratch.
  • When migrating or adding analytics to an existing application.

Advantages

  • Supports a broad range of modern frontend, backend, and mobile frameworks.
  • Ensures consistent event naming and property capture across the codebase.
  • Maintains architectural integrity by requiring minimal, targeted code additions.
  • Automates the tedious aspects of SDK initialization and environment configuration.

Usage examples

“Add PostHog analytics to my Next.js project.”
The agent will detect the Next.js environment, install the PostHog SDK, initialize it in the appropriate root file, and guide you through adding capture calls to key user flows.
“I need to track user signups in my Django application using PostHog.”
The agent will identify the Django setup, configure the PostHog Python SDK, and implement identify calls within your authentication logic.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/omnibus-instrument-product-analytics/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip omnibus-instrument-product-analytics.zip -d .agents/skills

Documentation by PostHog

Add PostHog product analytics events

Use this skill to add product analytics events (capture calls) that track meaningful user actions in new or changed code. Use it after implementing features or reviewing PRs to ensure key user behaviors are captured. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any framework or language.

Supported frameworks: Next.js, React Router, Nuxt, Vue, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, Ruby on Rails, Android, iOS, React Native, Expo, and more.

Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the platform.

  • Look for dependency files (package.json, requirements.txt, Gemfile, composer.json, go.mod, etc.) to determine the framework and language.

  • Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager.

  • Check for existing PostHog setup. If PostHog is already installed and initialized, skip to STEP 5.

STEP 2: Research integration. (Skip if PostHog is already set up.) 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and event capture 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. (Skip if PostHog is already set up.)

  • Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.

  • Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.

STEP 4: Initialize PostHog. (Skip if PostHog is already set up.)

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

STEP 5: Plan event tracking.

  • From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events.

  • Also look for files related to login that could be used for identifying users, along with error handling.

  • Find any existing posthog.capture() code. Make note of event name formatting. Don't duplicate existing events; supplement them.

  • Track actions only, not pageviews (those can be captured automatically). Exceptions can be made for "viewed"-type events at the top of a conversion funnel.

  • Server-side events are REQUIRED if the project includes any instrumentable server-side code (API routes, server actions, webhook handlers, payment/checkout completion, authentication endpoints).

STEP 6: Implement event capture.

  • For each planned event, add posthog.capture() calls with useful properties.

  • If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it.

  • Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.

  • You must read a file immediately before attempting to write it.

STEP 7: Identify users.

  • Add PostHog identify() calls on the client side during login and signup events. Use the contents of login and signup forms to identify users on submit.

  • If both frontend and backend exist, pass the client-side session and distinct ID using X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to the server-side code. On the server side, make sure events have a matching distinct ID.

STEP 8: Add error tracking.

  • Add PostHog exception capture error tracking to relevant files, particularly around critical user flows and API boundaries.

STEP 9: Set up environment variables.

  • If an env-file-tools MCP server is connected, use check_env_keys to see which keys already exist, then use set_env_values to create or update the PostHog API key and host.

  • Reference these environment variables in code instead of hardcoding them.

STEP 10: 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.

Reference files

  • references/EXAMPLE-next-app-router.md - next-app-router example project code

  • references/EXAMPLE-next-pages-router.md - next-pages-router example project code

  • references/EXAMPLE-react-react-router-6.md - react-react-router-6 example project code

  • references/EXAMPLE-react-react-router-7-framework.md - react-react-router-7-framework example project code

  • references/EXAMPLE-react-react-router-7-data.md - react-react-router-7-data example project code

  • references/EXAMPLE-react-react-router-7-declarative.md - react-react-router-7-declarative example project code

  • references/EXAMPLE-nuxt-3.6.md - nuxt-3.6 example project code

  • references/EXAMPLE-nuxt-4.md - nuxt-4 example project code

  • references/EXAMPLE-vue-3.md - vue-3 example project code

  • references/EXAMPLE-react-tanstack-router-file-based.md - react-tanstack-router-file-based example project code

  • references/EXAMPLE-react-tanstack-router-code-based.md - react-tanstack-router-code-based example project code

  • references/EXAMPLE-tanstack-start.md - tanstack-start example project code

  • references/EXAMPLE-sveltekit.md - sveltekit example project code

  • references/EXAMPLE-astro-static.md - astro-static example project code

  • references/EXAMPLE-astro-view-transitions.md - astro-view-transitions example project code

  • references/EXAMPLE-astro-ssr.md - astro-ssr example project code

  • references/EXAMPLE-astro-hybrid.md - astro-hybrid example project code

  • references/EXAMPLE-angular.md - angular example project code

  • references/EXAMPLE-django.md - django example project code

  • references/EXAMPLE-flask.md - flask example project code

  • references/EXAMPLE-fastapi.md - fastapi example project code

  • references/EXAMPLE-python.md - python example project code

  • references/EXAMPLE-laravel.md - laravel example project code

  • references/EXAMPLE-ruby-on-rails.md - ruby-on-rails example project code

  • references/EXAMPLE-ruby.md - ruby example project code

  • references/EXAMPLE-android.md - android example project code

  • references/EXAMPLE-swift.md - swift example project code

  • references/EXAMPLE-react-native.md - react-native example project code

  • references/EXAMPLE-expo.md - expo example project code

  • references/next-js.md - Next.js - docs

  • references/react-router-v6.md - React router v6 - docs

  • references/react-router-v7-framework-mode.md - React router v7 framework mode (remix v3) - docs

  • references/react-router-v7-data-mode.md - React router v7 data mode - docs

  • references/react-router-v7-declarative-mode.md - React router v7 declarative mode - docs

  • references/nuxt-js-3-6.md - Nuxt.js (v3.0 to v3.6) - docs

  • references/nuxt-js.md - Nuxt.js - docs

  • references/vue-js.md - Vue.js - docs

  • references/tanstack-start.md - Tanstack start - docs

  • references/svelte.md - Svelte - docs

  • references/astro.md - Astro - docs

  • references/angular.md - Angular - docs

  • references/django.md - Django - docs

  • references/flask.md - Flask - docs

  • references/python.md - Python - docs

  • references/posthog-python.md - PostHog python SDK

  • references/laravel.md - Laravel - docs

  • references/ruby-on-rails.md - Ruby on rails - docs

  • references/ruby.md - Ruby - docs

  • references/android.md - Android - docs

  • references/ios.md - Ios - docs

  • references/react-native.md - React native - docs

  • references/identify-users.md - Identify users - docs

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 docs: Follow the framework reference's initialization and capture patterns exactly.

Files

references/posthog-node.md

PostHog Node.js SDK

SDK Version: 5.28.5

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

  • 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 key

  • options? (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 personal API key
// With personal API key
const client = new PostHogBackendClient(
  'your-api-key',
  {
    host: 'https://app.posthog.com',
    personalApiKey: 'your-personal-api-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:

  • any

  • undefined

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 set

  • value (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 } (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'
  }
})

identify()

Release Tag: public

Identify a user and set their properties.

Parameters
  • { distinctId, properties, disableGeoip } (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 } (IdentifyMessage)

Returns
  • Promise<void>

Examples
// Basic immediate identify
await client.identifyImmediate({
  distinctId: 'user_123',
  properties: {
    name: 'John Doe',
    email: '[email protected]'
  }
})

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

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 capture

  • distinctId? (string) - Optional user distinct ID

  • additionalProperties? (Record<string | number, any>) - Optional additional properties to include

  • uuid? (EventMessage['uuid'])

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 capture

  • distinctId? (string) - Optional user distinct ID

  • additionalProperties? (Record<string | number, any>) - Optional additional properties to include

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 events

enable()

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 events

Feature flags methods
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: public

Get the value of a feature flag for a specific user.

Parameters
  • key (string) - The feature flag key

  • distinctId (string) - The user's distinct ID

  • options? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation

Returns

Union of:

  • Promise<FeatureFlagValue

  • undefined>

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 is disabled or not found
}
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
})

getFeatureFlagPayload()

Release Tag: public

Get the payload for a feature flag.

Parameters
  • key (string) - The feature flag key

  • distinctId (string) - The user's distinct ID

  • matchValue? (FeatureFlagValue) - Optional match value to get payload for

  • options? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation

Returns

Union of:

  • Promise<JsonType

  • undefined>

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.

Parameters
  • key (string) - The feature flag key

  • options? (FlagEvaluationOptions) - Optional configuration for flag evaluation

Returns

Union of:

  • Promise<FeatureFlagResult

  • undefined>

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<JsonType

  • undefined>

Examples
// Get remote config payload
const payload = await client.getRemoteConfigPayload('flag-key')
if (payload) {
  console.log('Remote config payload:', payload)
}

isFeatureEnabled()

Release Tag: public

Check if a feature flag is enabled for a specific user.

Parameters
  • key (string) - The feature flag key

  • distinctId (string) - The user's distinct ID

  • options? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluation

Returns

Union of:

  • Promise<boolean

  • undefined>

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 {
  // Feature is disabled
  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 server 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 seconds

Context methods
getContext()

Release Tag: public

Get the current context data.

Returns

Union of:

  • ContextData

  • undefined

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 context

  • options? (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 an API key, 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/posthog/integration/skills/all · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
PostHog/skills

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 omnibus-instrument-product-analytics.zip