Generated banner for Instrument Integration
Generated logo for Instrument Integration

Instrument Integration

PostHogOfficialCreated by PostHog

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

From the author

Add PostHog SDK integration to your application. Use when setting up PostHog for the first time or reviewing PRs that need PostHog initialization. Covers SDK installation, provider setup, and basic configuration for any framework.
— the description by PostHog

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/instrument-integration/download
  2. Unzip 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-ID and X-POSTHOG-SESSION-ID headers 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-get tool to retrieve the project's api_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-get MCP response for a region field — US maps to https://us.i.posthog.com, EU maps to https://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.local for Next.js, .env for 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 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-react-vite.md - react-vite 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-javascript-node.md - javascript-node example project code

  • references/EXAMPLE-javascript-web.md - javascript-web 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-php.md - php 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

  • references/react.md - React

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

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

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

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

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

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

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

  • references/tanstack-start.md - Tanstack start

  • references/svelte.md - Svelte

  • references/astro.md - Astro

  • references/angular.md - Angular

  • references/js.md - JavaScript web

  • references/posthog-js.md - PostHog JavaScript web SDK

  • references/node.md - Node.js

  • references/posthog-node.md - PostHog Node.js SDK

  • references/django.md - Django

  • references/flask.md - Flask

  • references/python.md - Python

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

  • references/dotnet.md - .net

  • references/elixir.md - Elixir

  • references/go.md - Go

  • references/laravel.md - Laravel

  • references/php.md - Php

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

  • references/ruby.md - Ruby

  • references/android.md - Android

  • references/ios.md - Ios

  • references/usage.md - Ios SDK usage

  • references/configuration.md - Ios SDK configuration

  • references/flutter.md - Flutter

  • references/react-native.md - React native

  • references/identify-users.md - Identify users

  • references/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

references/react.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

React

Canonical URL: https://posthog.com/docs/libraries/react

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.i.posthog.com instead of https://us.i.posthog.com (ingestion host), and use https://eu.posthog.com instead of https://us.posthog.com (app host for links).

On this page

  • Using a framework?

  • Install with the wizard

  • Installation

  • Identifying users

  • Usage

  • Feature flags

  • Experiments (A/B tests)

PostHog makes it easy to get data about traffic and usage of your React app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.

This guide walks you through an example integration of PostHog using vanilla React and the posthog-js library.

Using a framework?

Using React with a framework like Next.js, Remix, or React Router requires additional setup. Follow their respective guides instead:

Install with the wizard

Run this command in your project directory to add PostHog to your React project. The wizard detects your framework, installs the SDK, and sets up your first events.

npx @posthog/wizard

Or set it up manually by following the rest of this guide.

Installation

For React-based frameworks, we recommend the Next.js integration guide and Remix integration guide instead.

  1. Install posthog-js and @posthog/react using your package manager:

npm
npm install --save posthog-js @posthog/react
Yarn
yarn add posthog-js @posthog/react
pnpm
pnpm add posthog-js @posthog/react
Bun
bun add posthog-js @posthog/react

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

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

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

  1. Add your environment variables to your .env.local file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token and host in your project settings. If you're using Vite, prefixing variable names with VITE_ ensures they are accessible in the frontend.

.env.local

VITE_POSTHOG_PROJECT_TOKEN=<ph_project_token>
VITE_POSTHOG_HOST=https://us.i.posthog.com
  1. Integrate PostHog at the root of your app (such as main.jsx for Vite apps and root.tsx for React Router V7).

// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import posthog from 'posthog-js';
import { PostHogProvider } from '@posthog/react'

posthog.init(import.meta.env.VITE_POSTHOG_PROJECT_TOKEN, {
  api_host: import.meta.env.VITE_POSTHOG_HOST,
  defaults: '2026-08-30',
});

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <PostHogProvider client={posthog}>
      <App />
    </PostHogProvider>
  </StrictMode>,
)

Use the usePostHog hook in components

Inside React components, use the usePostHog hook to access PostHog. Outside components, you can import posthog directly, as long as it's the instance you initialized above. Events captured before posthog.init() runs are dropped.

Identifying users

Identifying users is required. Call posthog.identify('your-user-id') after login to link events to a known user. This is what connects frontend event captures, session replays, LLM traces, and error tracking to the same person — and lets backend events link back too.

Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like "anonymous" or "user", which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned.

Call posthog.reset() on logout, so the next person to use the browser doesn't inherit the last one's identity.

See our guide on identifying users for how to set this up.

Usage

PostHog provider

The React context provider makes it easy to access the posthog-js library in your app.

The provider takes an initialized and configured client instance like this:

// src/index.js
import posthog from 'posthog-js';
import { PostHogProvider} from '@posthog/react'

posthog.init(process.env.REACT_APP_PUBLIC_POSTHOG_PROJECT_TOKEN, {
  api_host: process.env.REACT_APP_PUBLIC_POSTHOG_HOST,
  defaults: '2026-08-30',
  // Optional: send PostHog session/user context to your backend
  tracing_headers: ['api.example.com'],
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <PostHogProvider client={posthog}>
      <App />
    </PostHogProvider>
  </React.StrictMode>
);
Calling PostHog methods

By default, the posthog-js library automatically captures pageviews, element clicks, inputs, and more. Autocapture can be tuned in with the configuration options.

To call PostHog methods for actions like identifying users, capturing events, using feature flags, or using other features, you can access the initialized posthog-js library using the usePostHog hook.

Using PostHog outside React components

Inside React components, use the usePostHog hook. It returns the client from the nearest PostHogProvider, so your components always use the instance you gave the provider.

Outside React components, such as in utility modules or API clients, you can import posthog from posthog-js directly, as long as it's the same instance you initialized and passed to PostHogProvider as shown above. Events captured before posthog.init() runs are dropped, so make sure initialization happens first. If you pass the provider a different client instance, import that instance instead.

All the methods of the library are available and can be used as described in the posthog-js documentation.

If your React app calls your own backend, tracing_headers adds X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID to matching fetch and XMLHttpRequest requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths.

import { usePostHog } from '@posthog/react'
import { useEffect } from 'react'
import { useUser, useLogin } from '../lib/user'

function App() {
    // `usePostHog`, like other React contexts, must be called at the top level of your component
    const posthog = usePostHog()
    const login = useLogin()
    const user = useUser()

    useEffect(() => {
        if (user) {
            // Identify sends an event, so you may want to limit how often you call it
            posthog?.identify(user.id, {
                email: user.email,
            })
            posthog?.group('company', user.company_id)
        }
    }, [posthog, user.id, user.email, user.company_id])

    const loginClicked = () => {
        posthog?.capture('clicked_log_in')
        login()
    }

    return (
        <div className="App">
            {/* Fire a custom event when the button is clicked */}
            <button onClick={() => posthog?.capture('button_clicked')}>Click me</button>
            {/* This button click event is autocaptured by default */}
            <button data-attr="autocapture-button">Autocapture buttons</button>
            {/* This button click event is not autocaptured */}
            <button className="ph-no-capture">Ignore certain elements</button>
            <button onClick={loginClicked}>Login</button>
        </div>
    )
}

export default App
TypeError: Cannot read properties of undefined

If you see the error TypeError: Cannot read properties of undefined (reading '...') this is likely because you tried to call a posthog function when posthog was not initialized (such as during the initial render). On purpose, we still render the children even if PostHog is not initialized so that your app still loads even if PostHog can't load.

To fix this error, add a check that posthog has been initialized such as:

useEffect(() => {
  posthog?.capture('test') // using optional chaining (recommended)

  if (posthog) {
    posthog.capture('test') // using an if statement
  }
}, [posthog])

Typescript helps protect against these errors.

Tracking element visibility

The PostHogCaptureOnViewed component enables you to automatically capture events when elements scroll into view in the browser. This is useful for tracking impressions of important content, monitoring user engagement with specific sections, or understanding which parts of your page users are actually seeing.

The component wraps your content and sends a $element_viewed event to PostHog when the wrapped element becomes visible in the viewport. It only fires once per component instance.

Basic usage:

import { PostHogCaptureOnViewed } from '@posthog/react'

function App() {
    return (
        <PostHogCaptureOnViewed name="hero-banner">
            <div>Your important content here</div>
        </PostHogCaptureOnViewed>
    )
}

With custom properties:

You can include additional properties with the event to provide more context:

<PostHogCaptureOnViewed
    name="product-card"
    properties={{
        product_id: '123',
        category: 'electronics',
        price: 299.99
    }}
>
    <ProductCard />
</PostHogCaptureOnViewed>

Tracking multiple children:

Use trackAllChildren to track each child element separately. This is useful for galleries or lists where you want to know which specific items were viewed:

<PostHogCaptureOnViewed
    name="product-gallery"
    properties={{ gallery_type: 'featured' }}
    trackAllChildren
>
    <ProductCard id="1" />
    <ProductCard id="2" />
    <ProductCard id="3" />
</PostHogCaptureOnViewed>

When trackAllChildren is enabled, each child element sends its own event with a child_index property indicating its position.

Custom intersection observer options:

You can customize when elements are considered "viewed" by passing options to the IntersectionObserver:

<PostHogCaptureOnViewed
    name="footer"
    observerOptions={{
        threshold: 0.5,  // Element is 50% visible
        rootMargin: '0px'
    }}
>
    <Footer />
</PostHogCaptureOnViewed>

The component passes all other props to the wrapper div, so you can add styling, classes, or other HTML attributes as needed.

Feature flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

There are two ways to implement feature flags in React:

  1. Using hooks.

  2. Using the <PostHogFeature> component.

Method 1: Using hooks

PostHog provides several hooks to make it easy to use feature flags in your React app.

HookDescription
useFeatureFlagEnabledReturns whether the feature flag is enabled. This sends a $feature_flag_called event. Without a default value, it returns boolean | undefined while flags are loading or absent. Pass an optional default value to return that value instead and narrow the return type to boolean.
useFeatureFlagVariantKeyReturns the variant key of the feature flag. This sends a $feature_flag_called event.
useActiveFeatureFlagsReturns an array of active feature flags. This does not send a $feature_flag_called event.
useFeatureFlagPayloadReturns the payload of the feature flag. This does not send a $feature_flag_called event. Always use this with useFeatureFlagEnabled or useFeatureFlagVariantKey.
Example 1: Using a boolean feature flag
import { useFeatureFlagEnabled, useFeatureFlagPayload } from '@posthog/react'

function App() {
  const showWelcomeMessage = useFeatureFlagEnabled('flag-key')
  const payload = useFeatureFlagPayload('flag-key')

  return (
    <div className="App">
      {
        showWelcomeMessage ? (
          <div>
            <h1>Welcome!</h1>
            <p>Thanks for trying out our feature flags.</p>
          </div>
        ) : (
          <div>
            <h2>No welcome message</h2>
            <p>Because the feature flag evaluated to false.</p>
          </div>
        )
      }
    </div>
  );
}

export default App;

To avoid handling undefined while flags are loading, pass a default value as the second argument:

const showWelcomeMessage = useFeatureFlagEnabled('flag-key', false)
Example 2: Using a multivariate feature flag
import { useFeatureFlagVariantKey } from '@posthog/react'

function App() {
  const variantKey = useFeatureFlagVariantKey('show-welcome-message')
  let welcomeMessage = ''
  if (variantKey === 'variant-a') {
    welcomeMessage = 'Welcome to the Alpha!'
  } else if (variantKey === 'variant-b') {
    welcomeMessage = 'Welcome to the Beta!'
  }

  return (
    <div className="App">
      {
        welcomeMessage ? (
          <div>
            <h1>{welcomeMessage}</h1>
            <p>Thanks for trying out our feature flags.</p>
          </div>
        ) : (
          <div>
            <h2>No welcome message</h2>
            <p>Because the feature flag evaluated to false.</p>
          </div>
        )
      }
    </div>
  );
}

export default App;
Example 3: Using a flag payload

Payload hook

The useFeatureFlagPayload hook does not send a $feature_flag_called event, which is required for the experiment to be tracked. To ensure the exposure event is sent, you should always use the useFeatureFlagPayload hook with either the useFeatureFlagEnabled or useFeatureFlagVariantKey hook.

import { useFeatureFlagEnabled, useFeatureFlagPayload } from '@posthog/react'

function App() {
  const variant = useFeatureFlagEnabled('show-welcome-message')
  const payload = useFeatureFlagPayload('show-welcome-message')

    return (
                <>
                {
                    variant ? (
                        <div className="welcome-message">
                            <h2>{payload?.welcomeTitle}</h2>
                            <p>{payload?.welcomeMessage}</p>
                        </div>
                    ) : <div>
                        <h2>No custom welcome message</h2>
                        <p>Because the feature flag evaluated to false.</p>
                    </div>
                }
        </>
    )
}
Method 2: Using the PostHogFeature component

The PostHogFeature component simplifies code by handling feature flag related logic.

It also automatically captures metrics, like how many times a user interacts with this feature.

Note: You still need the PostHogProvider at the top level for this to work.

Here is an example:

import { PostHogFeature } from '@posthog/react'

function App() {

    return (
        <PostHogFeature flag='show-welcome-message' match={true}>
            <div>
                <h1>Hello</h1>
                <p>Thanks for trying out our feature flags.</p>
            </div>
        </PostHogFeature>
    )
}
  • The match on the component can be either true, or the variant key, to match on a specific variant.

  • If you also want to show a default message, you can pass these in the fallback attribute.

If you wish to customise logic around when the component is considered visible, you can pass in visibilityObserverOptions to the feature. These take the same options as the IntersectionObserver API. By default, we use a threshold of 0.1.

Payloads

If your flag has a payload, you can pass a function to children whose first argument is the payload. For example:

import { PostHogFeature } from '@posthog/react'

function App() {

    return (
        <PostHogFeature flag='show-welcome-message' match={true}>
           {(payload) => {
                return (
                    <div>
                        <h1>{payload.welcomeMessage}</h1>
                        <p>Thanks for trying out our feature flags.</p>
                    </div>
                )
           }}
        </PostHogFeature>
    )
}
Request timeout

You can configure the feature_flag_request_timeout_ms parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.

posthog.init('<ph_project_token>', {
  api_host: 'https://us.i.posthog.com',
  defaults: '2026-08-30',
  feature_flag_request_timeout_ms: 3000 // Time in milliseconds. Default is 3000 (3 seconds).
}
)
Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

function handleFeatureFlag(client, flagKey, distinctId) {
    try {
        const isEnabled = client.isFeatureEnabled(flagKey, distinctId);
        console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`);
        return isEnabled;
    } catch (error) {
        console.error(`Error fetching feature flag '${flagKey}': ${error.message}`);
        // Optionally, you can return a default value or throw the error
        // return false; // Default to disabled
        throw error;
    }
}

// Usage example
try {
    const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123');
    if (flagEnabled) {
        // Implement new feature logic
    } else {
        // Implement old feature logic
    }
} catch (error) {
    // Handle the error at a higher level
    console.error('Feature flag check failed, using default behavior');
    // Implement fallback logic
}
Bootstrapping flags

Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.

To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.

For details on how to implement bootstrapping, see our bootstrapping guide.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

// You can either use the `useFeatureFlagVariantKey` hook,
// or you can use the feature flags component - /docs/libraries/react#feature-flags-react-component

// Method one: using the useFeatureFlagVariantKey hook
import { useFeatureFlagVariantKey } from '@posthog/react'

function App() {
    const variant = useFeatureFlagVariantKey('experiment-feature-flag-key')
    if (variant == 'variant-name') {
        // do something
    }
}

// Method two: using the feature flags component
import { PostHogFeature } from '@posthog/react'

function App() {
    return (
        <PostHogFeature flag='experiment-feature-flag-key' match={'variant-name'}>
            <!-- the component to show -->
        </PostHogFeature>
    )
}

// You can also test your code by overriding the feature flag:
// e.g., posthog.featureFlags.overrideFeatureFlags({ flags: {'experiment-feature-flag-key': 'test'}})

It's also possible to run experiments without using feature flags.

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