Omnibus Instrument Product Analytics
PostHogOfficialCreated by PostHog
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/posthog/omnibus-instrument-product-analytics/downloadUnzip 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-IDandX-POSTHOG-SESSION-IDheaders 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 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-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-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-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.js - docsreferences/react-router-v6.md- React router v6 - docsreferences/react-router-v7-framework-mode.md- React router v7 framework mode (remix v3) - docsreferences/react-router-v7-data-mode.md- React router v7 data mode - docsreferences/react-router-v7-declarative-mode.md- React router v7 declarative mode - docsreferences/nuxt-js-3-6.md- Nuxt.js (v3.0 to v3.6) - docsreferences/nuxt-js.md- Nuxt.js - docsreferences/vue-js.md- Vue.js - docsreferences/tanstack-start.md- Tanstack start - docsreferences/svelte.md- Svelte - docsreferences/astro.md- Astro - docsreferences/angular.md- Angular - docsreferences/django.md- Django - docsreferences/flask.md- Flask - docsreferences/python.md- Python - docsreferences/posthog-python.md- PostHog python SDKreferences/laravel.md- Laravel - docsreferences/ruby-on-rails.md- Ruby on rails - docsreferences/ruby.md- Ruby - docsreferences/android.md- Android - docsreferences/ios.md- Ios - docsreferences/react-native.md- React native - docsreferences/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
- ATTRIBUTION.mdAdded by AutoGineer966 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.5 KiB
- references/EXAMPLE-android.md49.7 KiB
- references/EXAMPLE-angular.md23.4 KiB
- references/EXAMPLE-astro-hybrid.md26.8 KiB
- references/EXAMPLE-astro-ssr.md26.7 KiB
- references/EXAMPLE-astro-static.md19.4 KiB
- references/EXAMPLE-astro-view-transitions.md23.1 KiB
- references/EXAMPLE-django.md30.0 KiB
- references/EXAMPLE-expo.md35.5 KiB
- references/EXAMPLE-fastapi.md40.9 KiB
- references/EXAMPLE-flask.md32.0 KiB
- references/EXAMPLE-javascript-node.md9.0 KiB
- references/EXAMPLE-javascript-web.md11.7 KiB
- references/EXAMPLE-laravel.md59.5 KiB
- references/EXAMPLE-next-app-router.md17.3 KiB
- references/EXAMPLE-next-pages-router.md18.9 KiB
- references/EXAMPLE-nuxt-3.6.md22.1 KiB
- references/EXAMPLE-nuxt-4.md28.7 KiB
- references/EXAMPLE-python.md11.6 KiB
- references/EXAMPLE-react-native.md46.4 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.2 KiB
- references/EXAMPLE-react-tanstack-router-code-based.md19.2 KiB
- references/EXAMPLE-react-tanstack-router-file-based.md18.0 KiB
- references/EXAMPLE-react-vite.md12.4 KiB
- references/EXAMPLE-ruby-on-rails.md37.6 KiB
- references/EXAMPLE-ruby.md10.3 KiB
- references/EXAMPLE-sveltekit.md18.4 KiB
- references/EXAMPLE-swift.md18.6 KiB
- references/EXAMPLE-tanstack-start.md28.4 KiB
- references/EXAMPLE-vue-3.md17.9 KiB
- references/android.md21.7 KiB
- references/angular.md12.5 KiB
- references/astro.md8.3 KiB
- references/django.md6.7 KiB
- references/flask.md2.9 KiB
- references/identify-users.md8.1 KiB
- references/ios.md5.4 KiB
- references/js.md12.3 KiB
- references/laravel.md2.1 KiB
- references/next-js.md12.5 KiB
- references/node.md28.8 KiB
- references/nuxt-js-3-6.md6.6 KiB
- references/nuxt-js.md7.2 KiB
- references/posthog-js.md42.3 KiB
- references/posthog-node.md23.4 KiB
- references/posthog-python.md31.3 KiB
- references/python.md31.1 KiB
- references/react-native.md43.8 KiB
- references/react-router-v6.md11.6 KiB
- references/react-router-v7-data-mode.md11.4 KiB
- references/react-router-v7-declarative-mode.md11.6 KiB
- references/react-router-v7-framework-mode.md14.9 KiB
- references/react.md18.5 KiB
- references/ruby-on-rails.md10.6 KiB
- references/ruby.md18.9 KiB
- references/svelte.md7.2 KiB
- references/tanstack-start.md5.1 KiB
- references/vue-js.md9.1 KiB
references/posthog-python.md
PostHog Python SDK
SDK Version: 7.0.1
Integrate PostHog into any python application.
Categories
Initialization
Identification
Capture
Error Tracking
Feature flags
Contexts
Events
Client management
PostHog
This is the SDK reference for the PostHog Python SDK. You can learn more about example usage in the Python SDK documentation. You can also follow Flask and Django guides to integrate PostHog into your project.
Initialization methods
Client()
Release Tag: public
Initialize a new PostHog client instance.
Parameters
project_api_key?(str) - The project API key.host(any) - The host to use for the client.debug(bool) - Whether to enable debug mode.max_queue_size(int)send(bool)on_error(any)flush_at(int)flush_interval(float)gzip(bool)max_retries(int)sync_mode(bool)timeout(int)thread(int)poll_interval(int)personal_api_key(any)disabled(bool)disable_geoip(bool)historical_migration(bool)feature_flags_request_timeout_seconds(int)super_properties(any)enable_exception_autocapture(bool)log_captured_exceptions(bool)project_root(any)privacy_mode(bool)before_send(any)flag_fallback_cache_url(any)enable_local_evaluation(bool)capture_exception_code_variables(bool)code_variables_mask_patterns(any)code_variables_ignore_patterns(any)
Returns
None
Examples
from posthog import Posthog
posthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')Identification methods
alias()
Release Tag: public
Create an alias between two distinct IDs.
Parameters
previous_id?(str) - The previous distinct ID.distinct_id?(str) - The new distinct ID to alias to.timestamp(any) - The timestamp of the event.uuid(any) - A unique identifier for the event.disable_geoip(any) - Whether to disable GeoIP for this event.
Returns
None
Examples
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')group_identify()
Release Tag: public
Identify a group and set its properties.
Parameters
group_type?(str) - The type of group (e.g., 'company', 'team').group_key?(str) - The unique identifier for the group.properties?(dict[str, Any]) - A dictionary of properties to set on the group.timestamp(datetime) - The timestamp of the event.uuid?(str) - A unique identifier for the event.disable_geoip?(bool) - Whether to disable GeoIP for this event.distinct_id(Number) - The distinct ID of the user performing the action.
Returns
Optional[str]
Examples
posthog.group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})set()
Release Tag: public
Set properties on a person profile.
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
# Set with distinct id
posthog.set(distinct_id='user123', properties={'name': 'Max Hedgehog'})set_once()
Release Tag: public
Set properties on a person profile only if they haven't been set before.
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})Capture methods
capture()
Release Tag: public
Captures an event manually. Learn about capture best practices
Parameters
event?(str) - The event name to capture.kwargs?(Unpack[OptionalCaptureArgs])
Returns
Optional[str]
Examples
Anonymous event
# Anonymous event
posthog.capture('some-anon-event')Context usage
# Context usage
from posthog import identify_context, new_context
with new_context():
identify_context('distinct_id_of_the_user')
posthog.capture('user_signed_up')
posthog.capture('user_logged_in')
posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')Set event properties
# Set event properties
posthog.capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)Page view event
# Page view event
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})Error Tracking methods
capture_exception()
Release Tag: public
Capture an exception for error tracking.
Parameters
exception?(BaseException) - The exception to capture.kwargs?(Unpack[OptionalCaptureArgs])
Returns
None
Examples
try:
# Some code that might fail
pass
except Exception as e:
posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)Feature flags methods
feature_enabled()
Release Tag: public
Check if a feature flag is enabled for a user.
Parameters
key?(any) - The feature flag key.distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip(any) - Whether to disable GeoIP for this request.
Returns
None
Examples
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')get_all_flags()
Release Tag: public
Get all feature flags for a user.
Parameters
distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
Optional[dict[str, Union[bool, str]]]
Examples
posthog.get_all_flags('distinct_id_of_your_user')get_all_flags_and_payloads()
Release Tag: public
Get all feature flags and their payloads for a user.
Parameters
distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
FlagsAndPayloads
Examples
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')get_feature_flag()
Release Tag: public
Get multivariate feature flag value for a user.
Parameters
key?(any) - The feature flag key.distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip(any) - Whether to disable GeoIP for this request.
Returns
Union[bool, str, any]
Examples
enabled_variant = posthog.get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key': # replace 'variant-key' with the key of your variant
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')get_feature_flag_payload()
Release Tag: public
Get the payload for a feature flag.
Parameters
key?(any) - The feature flag key.distinct_id?(any) - The distinct ID of the user.match_value(bool) - The specific flag value to get payload for.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip(any) - Whether to disable GeoIP for this request.
Returns
None
Examples
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')get_feature_flags_and_payloads()
Release Tag: public
Get feature flags and payloads for a user by calling decide.
Parameters
distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
FlagsAndPayloads
Examples
result = posthog.get_feature_flags_and_payloads('<distinct_id>')get_feature_payloads()
Release Tag: public
Get feature flag payloads for a user by calling decide.
Parameters
distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
dict[str, str]
Examples
payloads = posthog.get_feature_payloads('<distinct_id>')get_feature_variants()
Release Tag: public
Get feature flag variants for a user by calling decide.
Parameters
distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
dict[str, Union[bool, str]]
get_flags_decision()
Release Tag: public
Get feature flags decision.
Parameters
distinct_id(Number) - The distinct ID of the user.groups?(dict) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.disable_geoip(any) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
Returns
FlagsResponse
Examples
decision = posthog.get_flags_decision('user123')load_feature_flags()
Release Tag: public
Load feature flags for local evaluation.
Returns
None
Examples
posthog.load_feature_flags()Other methods
flush()
Release Tag: public
Force a flush from the internal queue to the server. Do not use directly, call shutdown() instead.
Returns
None
Examples
posthog.capture('event_name')
posthog.flush() # Ensures the event is sent immediatelyget_feature_flag_result()
Release Tag: public
Get a FeatureFlagResult object which contains the flag result and payload for a key by evaluating locally or remotely depending on whether local evaluation is enabled and the flag can be locally evaluated. This also captures the $feature_flag_called event unless send_feature_flag_events is False.
Parameters
key?(any) - The feature flag key.distinct_id?(any) - The distinct ID of the user.groups(any) - A dictionary of group information.person_properties(any) - A dictionary of person properties.group_properties(any) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip(any) - Whether to disable GeoIP for this request.
Returns
Optional[FeatureFlagResult]
Examples
flag_result = posthog.get_feature_flag_result('flag-key', 'distinct_id_of_your_user')
if flag_result and flag_result.get_value() == 'variant-key':
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = flag_result.payloadjoin()
Release Tag: public
End the consumer thread once the queue is empty. Do not use directly, call shutdown() instead.
Returns
None
Examples
posthog.join()shutdown()
Release Tag: public
Flush all messages and cleanly shutdown the client. Call this before the process ends in serverless environments to avoid data loss.
Returns
None
Examples
posthog.shutdown()Contexts methods
new_context()
Release Tag: public
Create a new context for managing shared state. Learn more about contexts.
Parameters
fresh(bool) - Whether to create a fresh context that doesn't inherit from parent.capture_exceptions(bool) - Whether to automatically capture exceptions in this context.
Returns
None
Examples
with posthog.new_context():
identify_context('<distinct_id>')
posthog.capture('event_name')PostHog Module Functions
Global functions available in the PostHog module
Identification methods
alias()
Release Tag: public
Associate user behaviour before and after they e.g. register, login, or perform some other identifying action.
Notes:
To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?". Particularly useful for associating user behaviour before and after they e.g. register, login, or perform some other identifying action.
Parameters
previous_id?(any) - The unique ID of the user beforedistinct_id?(any) - The current unique idtimestamp(any) - Optional timestamp for the eventuuid(any) - Optional UUID for the eventdisable_geoip(any) - Whether to disable GeoIP lookup
Returns
None
Examples
# Alias user
from posthog import alias
alias(previous_id='distinct_id', distinct_id='alias_id')group_identify()
Release Tag: public
Set properties on a group.
Parameters
group_type?(any) - Type of your groupgroup_key?(any) - Unique identifier of the groupproperties(any) - Properties to set on the grouptimestamp(any) - Optional timestamp for the eventuuid(any) - Optional UUID for the eventdisable_geoip(any) - Whether to disable GeoIP lookup
Returns
None
Examples
# Group identify
from posthog import group_identify
group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})identify_context()
Release Tag: public
Identify the current context with a distinct ID.
Parameters
distinct_id?(str) - The distinct ID to associate with the current context and its children
Returns
None
Examples
from posthog import identify_context
identify_context("user_123")set()
Release Tag: public
Set properties on a user record.
Notes:
This will overwrite previous people property values. Generally operates similar to capture, with distinct_id being an optional argument, defaulting to the current context's distinct ID. If there is no context-level distinct ID, and no override distinct_id is passed, this function will do nothing. Context tags are folded into $set properties, so tagging the current context and then calling set will cause those tags to be set on the user (unlike capture, which causes them to just be set on the event).
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
# Set person properties
from posthog import capture
capture(
'distinct_id',
event='event_name',
properties={
'$set': {'name': 'Max Hedgehog'},
'$set_once': {'initial_url': '/blog'}
}
)set_once()
Release Tag: public
Set properties on a user record, only if they do not yet exist.
Notes:
This will not overwrite previous people property values, unlike set. Otherwise, operates in an identical manner to set.
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
# Set property once
from posthog import capture
capture(
'distinct_id',
event='event_name',
properties={
'$set': {'name': 'Max Hedgehog'},
'$set_once': {'initial_url': '/blog'}
}
)Events methods
capture()
Release Tag: public
Capture anything a user does within your system.
Notes:
Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up. A capture call requires an event name to specify the event. We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on. Capture takes a number of optional arguments, which are defined by the OptionalCaptureArgs type.
Parameters
event?(str) - The event name to specify the event **kwargs: Optional arguments including:kwargs?(Unpack[OptionalCaptureArgs])
Returns
Optional[str]
Examples
Context and capture usage
# Context and capture usage
from posthog import new_context, identify_context, tag_context, capture
# Enter a new context (e.g. a request/response cycle, an instance of a background job, etc)
with new_context():
# Associate this context with some user, by distinct_id
identify_context('some user')
# Capture an event, associated with the context-level distinct ID ('some user')
capture('movie started')
# Capture an event associated with some other user (overriding the context-level distinct ID)
capture('movie joined', distinct_id='some-other-user')
# Capture an event with some properties
capture('movie played', properties={'movie_id': '123', 'category': 'romcom'})
# Capture an event with some properties
capture('purchase', properties={'product_id': '123', 'category': 'romcom'})
# Capture an event with some associated group
capture('purchase', groups={'company': 'id:5'})
# Adding a tag to the current context will cause it to appear on all subsequent events
tag_context('some-tag', 'some-value')
capture('another-event') # Will be captured with `'some-tag': 'some-value'` in the properties dictSet event properties
# Set event properties
from posthog import capture
capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)capture_exception()
Release Tag: public
Capture exceptions that happen in your code.
Notes:
Capture exception is idempotent - if it is called twice with the same exception instance, only a occurrence will be tracked in posthog. This is because, generally, contexts will cause exceptions to be captured automatically. However, to ensure you track an exception, if you catch and do not re-raise it, capturing it manually is recommended, unless you are certain it will have crossed a context boundary (e.g. by existing a with posthog.new_context(): block already). If the passed exception was raised and caught, the captured stack trace will consist of every frame between where the exception was raised and the point at which it is captured (the "traceback"). If the passed exception was never raised, e.g. if you call posthog.capture_exception(ValueError("Some Error")), the stack trace captured will be the full stack trace at the moment the exception was captured. Note that heavy use of contexts will lead to truncated stack traces, as the exception will be captured by the context entered most recently, which may not be the point you catch the exception for the final time in your code. It's recommended to use contexts sparingly, for this reason. capture_exception takes the same set of optional arguments as capture.
Parameters
exception(BaseException) - The exception to capture. If not provided, the current exception is captured viasys.exc_info()kwargs?(Unpack[OptionalCaptureArgs])
Returns
None
Examples
# Capture exception
from posthog import capture_exception
try:
risky_operation()
except Exception as e:
capture_exception(e)Feature flags methods
feature_enabled()
Release Tag: public
Use feature flags to enable or disable features for users.
Notes:
You can call posthog.load_feature_flags() before to make sure you're not doing unexpected requests.
Parameters
key?(any) - The feature flag keydistinct_id?(any) - The user's distinct IDgroups(any) - Groups mappingperson_properties(any) - Person propertiesgroup_properties(any) - Group propertiesonly_evaluate_locally(bool) - Whether to evaluate only locallysend_feature_flag_events(bool) - Whether to send feature flag eventsdisable_geoip(any) - Whether to disable GeoIP lookup
Returns
None
Examples
# Boolean feature flag
from posthog import feature_enabled, get_feature_flag_payload
is_my_flag_enabled = feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')feature_flag_definitions()
Release Tag: public
Returns loaded feature flags.
Notes:
Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.
Returns
None
Examples
from posthog import feature_flag_definitions
definitions = feature_flag_definitions()get_all_flags()
Release Tag: public
Get all flags for a given user.
Notes:
Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.
Parameters
distinct_id?(any) - The user's distinct IDgroups(any) - Groups mappingperson_properties(any) - Person propertiesgroup_properties(any) - Group propertiesonly_evaluate_locally(bool) - Whether to evaluate only locallydisable_geoip(any) - Whether to disable GeoIP lookup
Returns
Optional[dict[str, FeatureFlag]]
Examples
# All flags for user
from posthog import get_all_flags
get_all_flags('distinct_id_of_your_user')get_feature_flag()
Release Tag: public
Get feature flag variant for users. Used with experiments.
Notes:
groups are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. group_properties take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}.
Parameters
key?(any) - The feature flag keydistinct_id?(any) - The user's distinct IDgroups(any) - Groups mapping from group type to group keyperson_properties(any) - Person propertiesgroup_properties(any) - Group properties in format { group_type_name: { group_properties } }only_evaluate_locally(bool) - Whether to evaluate only locallysend_feature_flag_events(bool) - Whether to send feature flag eventsdisable_geoip(any) - Whether to disable GeoIP lookup
Returns
Optional[FeatureFlag]
Examples
# Multivariate feature flag
from posthog import get_feature_flag, get_feature_flag_payload
enabled_variant = get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key':
matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')load_feature_flags()
Release Tag: public
Load feature flag definitions from PostHog.
Returns
None
Examples
from posthog import load_feature_flags
load_feature_flags()Client management methods
flush()
Release Tag: public
Tell the client to flush all queued events.
Returns
None
Examples
from posthog import flush
flush()join()
Release Tag: public
Block program until the client clears the queue. Used during program shutdown. You should use shutdown() directly in most cases.
Returns
None
Examples
from posthog import join
join()shutdown()
Release Tag: public
Flush all messages and cleanly shutdown the client.
Returns
None
Examples
from posthog import shutdown
shutdown()Other methods
get_feature_flag_result()
Release Tag: public
Get a FeatureFlagResult object which contains the flag result and payload. This method evaluates a feature flag and returns a FeatureFlagResult object containing: - enabled: Whether the flag is enabled - variant: The variant value if the flag has variants - payload: The payload associated with the flag (automatically deserialized from JSON) - key: The flag key - reason: Why the flag was enabled/disabled Example: python result = posthog.get_feature_flag_result('beta-feature', 'distinct_id') if result and result.enabled: # Use the variant and payload print(f"Variant: {result.variant}") print(f"Payload: {result.payload}")
Parameters
key?(any)distinct_id?(any)groups(any)person_properties(any)group_properties(any)only_evaluate_locally(bool)send_feature_flag_events(bool)disable_geoip(any)
Returns
None
get_remote_config_payload()
Release Tag: public
Get the payload for a remote config feature flag.
Parameters
key?(any) - The key of the feature flag
Returns
None
set_capture_exception_code_variables_context()
Release Tag: public
Set whether code variables are captured for the current context.
Parameters
enabled?(bool)
Returns
None
set_code_variables_ignore_patterns_context()
Release Tag: public
Variable names matching these patterns will be ignored completely when capturing code variables.
Parameters
ignore_patterns?(list)
Returns
None
set_code_variables_mask_patterns_context()
Release Tag: public
Variable names matching these patterns will be masked with *** when capturing code variables.
Parameters
mask_patterns?(list)
Returns
None
Contexts methods
new_context()
Release Tag: public
Create a new context scope that will be active for the duration of the with block.
Parameters
fresh(bool) - Whether to start with a fresh context (default: False)capture_exceptions(bool) - Whether to capture exceptions raised within the context (default: True)client(any) - Optional Posthog client instance to use for this context (default: None)
Returns
None
Examples
from posthog import new_context, tag, capture
with new_context():
tag("request_id", "123")
capture("event_name", properties={"property": "value"})scoped()
Release Tag: public
Decorator that creates a new context for the function.
Parameters
fresh(bool) - Whether to start with a fresh context (default: False)capture_exceptions(bool) - Whether to capture and track exceptions with posthog error tracking (default: True)
Returns
None
Examples
from posthog import scoped, tag, capture
@scoped()
def process_payment(payment_id):
tag("payment_id", payment_id)
capture("payment_started")set_context_session()
Release Tag: public
Set the session ID for the current context.
Parameters
session_id?(str) - The session ID to associate with the current context and its children
Returns
None
Examples
from posthog import set_context_session
set_context_session("session_123")tag()
Release Tag: public
Add a tag to the current context.
Parameters
name?(str) - The tag keyvalue?(Any) - The tag value
Returns
None
Examples
from posthog import tag
tag("user_id", "123")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 or PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download omnibus-instrument-product-analytics.zip