AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-feature-flags

Add PostHog feature flags to gate new functionality. Use after implementing features or reviewing PRs to ensure safe rollouts with feature flag controls. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-feature-flags at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 26

references/adding-feature-flag-code.md

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

Adding feature flag code

Canonical URL: https://posthog.com/docs/feature-flags/adding-feature-flag-code

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

Once you've created your feature flag in PostHog, the next step is to add your code:

Web

Boolean feature flags

const result = posthog.getFeatureFlagResult('flag-key')
if (result?.enabled) {
    // Do something differently for this user

    // Optional: fetch the payload from the same evaluation result
    const matchedFlagPayload = result?.payload
}

Multivariate feature flags

const result = posthog.getFeatureFlagResult('flag-key')
if (result?.variant == 'variant-key') { // replace 'variant-key' with the key of your variant
    // Do something differently for this user

    // Optional: fetch the payload from the same evaluation result
    const matchedFlagPayload = result?.payload
}

Inspecting all feature flags

You can inspect all currently loaded feature flags with getAllFeatureFlags(). It returns each flag's key, enabled state, variant, and payload, and does not send a $feature_flag_called event, so calling it won't affect your experiment results or flag usage analytics:

for (const flag of posthog.getAllFeatureFlags()) {
    console.log(flag.key, flag.enabled, flag.variant, flag.payload)
}

Ensuring flags are loaded before usage

Every time a user loads a page, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in your chosen persistence option (local storage by default).

This means that for most pages, the feature flags are available immediately — except for the first time a user visits.

To handle this, you can use the onFeatureFlags callback to wait for the feature flag request to finish:

posthog.onFeatureFlags(function (flags, flagVariants, { errorsLoading }) {
    // feature flags are guaranteed to be available at this point
    if (posthog.isFeatureEnabled('flag-key')) {
        // do something
    }
})

Callback parameters

The onFeatureFlags callback receives the following parameters:

  • flags: string[]: An object containing the feature flags that apply to the user.

  • flagVariants: Record<string, string | boolean>: An object containing the variants that apply to the user.

  • { errorsLoading }: { errorsLoading?: boolean }: An object containing a boolean indicating if an error occurred during the request to load the feature flags. This is true if the request timed out or if there was an error. It will be false or undefined if the request was successful.

You won't usually need to use these, but they are useful if you want to be extra careful about feature flags not being loaded yet because of a network error and/or a network timeout (see feature_flag_request_timeout_ms).

Evaluating only specific flags

By default, the JavaScript SDK requests that every eligible feature flag be evaluated for the current user. If you'd only like to evaluate and return a subset of flags, pass flag_keys when initializing PostHog:

posthog.init('<ph_project_token>', {
  api_host: 'https://us.i.posthog.com',
  defaults: '2026-08-30',
  flag_keys: ['checkout-flow', 'new-dashboard'],
})

PostHog scopes evaluation and the response to those keys for this SDK instance. Dependency flags required to evaluate requested flags may also be evaluated and returned. Leave flag_keys unset to evaluate all eligible flags.

Reloading feature flags

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:

posthog.reloadFeatureFlags()

Overriding server properties

Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})

Note: These are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation.

Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading:

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

At any point, you can reset these properties by calling resetPersonPropertiesForFlags:

posthog.resetPersonPropertiesForFlags()

The same holds for group properties:

// set properties for a group
posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})

// reset properties for a given group:
posthog.resetGroupPropertiesForFlags('company')

// reset properties for all groups:
posthog.resetGroupPropertiesForFlags()

Note: You don't need to add the group names here, since these properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset.

Automatic overrides

Whenever you call posthog.identify with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call posthog.group().

Default overridden properties

By default, we always override some properties based on the user IP address.

The list of properties that this overrides:

  1. $geoip_city_name
  2. $geoip_country_name
  3. $geoip_country_code
  4. $geoip_continent_name
  5. $geoip_continent_code
  6. $geoip_postal_code
  7. $geoip_time_zone

This enables any geolocation-based flags to work without manually setting these properties.

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

Feature flag 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
}

React

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.

| Hook | Description | | --- | --- | | useFeatureFlagEnabled | Returns 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. | | useFeatureFlagVariantKey | Returns the variant key of the feature flag. This sends a $feature_flag_called event. | | useActiveFeatureFlags | Returns an array of active feature flags. This does not send a $feature_flag_called event. | | useFeatureFlagPayload | Returns 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
}

Node.js

There are two steps to implement feature flags in Node:

Step 1: Evaluate flags once

Call client.evaluateFlags() once for the user, then read values from the returned snapshot.

Boolean feature flags

const flags = await client.evaluateFlags('distinct_id_of_your_user')

if (flags.isEnabled('flag-key')) {
    // Do something differently for this user
    // Optional: fetch the payload
    const matchedFlagPayload = flags.getFlagPayload('flag-key')
}

Multivariate feature flags

const flags = await client.evaluateFlags('distinct_id_of_your_user')
const enabledVariant = flags.getFlag('flag-key')

if (enabledVariant === 'variant-key') { // replace 'variant-key' with the key of your variant
    // Do something differently for this user
    // Optional: fetch the payload
    const matchedFlagPayload = flags.getFlagPayload('flag-key')
}

flags.getFlag() returns the variant string for multivariate flags, true for enabled boolean flags, false for disabled flags, and undefined when the flag wasn't returned by the evaluation.

Note: client.isFeatureEnabled(), client.getFeatureFlag(), client.getFeatureFlagPayload(), and capture({ sendFeatureFlags: true }) still work during the migration period, but they're deprecated. Prefer evaluateFlags() for new code.

Step 2: Include feature flag information when capturing events

If you want use your feature flag to breakdown or filter events in your insights, you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event.

Note: This step is only required for events captured using our server-side SDKs or API.

There are two methods you can use to include feature flag information in your events:

Method 1: Pass the evaluated flags snapshot to capture()

Pass the same flags object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another /flags request.

const flags = await client.evaluateFlags('distinct_id_of_your_user')

if (flags.isEnabled('flag-key')) {
    // Do something differently for this user
}

client.capture({
    distinctId: 'distinct_id_of_your_user',
    event: 'event_name',
    flags,
})

By default, this attaches every flag in the snapshot using $feature/<flag-key> properties and $active_feature_flags.

To reduce event property bloat, pass a filtered snapshot:

// Attach only flags accessed with isEnabled() or getFlag() before this call
client.capture({
    distinctId: 'distinct_id_of_your_user',
    event: 'event_name',
    flags: flags.onlyAccessed(),
})

// Attach only specific flags
client.capture({
    distinctId: 'distinct_id_of_your_user',
    event: 'event_name',
    flags: flags.only(['checkout-flow', 'new-dashboard']),
})

onlyAccessed() is order-dependent. If you call it before accessing any flags with isEnabled() or getFlag(), no feature flag properties are attached.

Method 2: Include the $feature/feature_flag_name property manually

In the event properties, include $feature/feature_flag_name: variant_key:

client.capture({
    distinctId: 'distinct_id_of_your_user',
    event: 'event_name',
    properties: {
        // Replace feature-flag-key with your flag key and 'variant-key' with the key of your variant
        '$feature/feature-flag-key': 'variant-key',
    },
})

Evaluating only specific flags

By default, evaluateFlags() evaluates every flag for the user. If you only need a few flags, pass flagKeys to request only those flags:

const flags = await client.evaluateFlags('distinct_id_of_your_user', {
    flagKeys: ['checkout-flow', 'new-dashboard'],
})

Sending $feature_flag_called events

Capturing $feature_flag_called events enables PostHog to know when a flag was accessed by a user and provide analytics and insights on the flag. With evaluateFlags(), the SDK sends this event when you call flags.isEnabled() or flags.getFlag() for a flag.

The SDK deduplicates these events per (distinct_id, flag, value) in a local cache. If you reinitialize the PostHog client, the cache resets and $feature_flag_called events may be sent again. PostHog handles duplicates, so duplicate $feature_flag_called events don't affect your analytics.

flags.getFlagPayload() doesn't send $feature_flag_called events and doesn't count as an access for onlyAccessed().

Advanced: Overriding server properties

Sometimes, you may want to evaluate feature flags using person properties, groups, or group properties that haven't been ingested yet, or were set incorrectly earlier.

You can provide properties to evaluate the flag with by using the person properties, groups, and group properties arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server.

For example:

const flags = await client.evaluateFlags('distinct_id_of_the_user', {
    personProperties: {
        property_name: 'value',
    },
    groups: {
        your_group_type: 'your_group_id',
        another_group_type: 'your_group_id',
    },
    groupProperties: {
        your_group_type: {
            group_property_name: 'value',
        },
        another_group_type: {
            group_property_name: 'value',
        },
    },
})

if (flags.isEnabled('flag-key')) {
    // Do something differently for this user
}

Overriding GeoIP properties

By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties.

You can override GeoIP properties by including them in the person_properties parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location.

The following GeoIP properties can be overridden:

  • $geoip_country_code
  • $geoip_country_name
  • $geoip_city_name
  • $geoip_city_confidence
  • $geoip_continent_code
  • $geoip_continent_name
  • $geoip_latitude
  • $geoip_longitude
  • $geoip_postal_code
  • $geoip_subdivision_1_code
  • $geoip_subdivision_1_name
  • $geoip_subdivision_2_code
  • $geoip_subdivision_2_name
  • $geoip_subdivision_3_code
  • $geoip_subdivision_3_name
  • $geoip_time_zone

Simply include any of these properties in the person_properties parameter alongside your other person properties when calling feature flags.

Request timeout

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

const client = new PostHog('<ph_project_token>', {
    host: 'https://us.i.posthog.com',
    featureFlagsRequestTimeoutMs: 3000, // Time in milliseconds. Defaults to 3000 (3 seconds).
})

Python

There are two steps to implement feature flags in Python:

Step 1: Evaluate flags once

Call posthog.evaluate_flags() once for the user, then read values from the returned snapshot.

Boolean feature flags

flags = posthog.evaluate_flags("distinct_id_of_your_user")

if flags.is_enabled("flag-key"):
    # Do something differently for this user
    # Optional: fetch the payload
    matched_flag_payload = flags.get_flag_payload("flag-key")

Multivariate feature flags

flags = posthog.evaluate_flags("distinct_id_of_your_user")

enabled_variant = flags.get_flag("flag-key")

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 = flags.get_flag_payload("flag-key")

flags.get_flag() returns the variant string for multivariate flags, True for enabled boolean flags, False for disabled flags, and None when the flag wasn't returned by the evaluation.

Note: posthog.feature_enabled(), posthog.get_feature_flag(), `posthog.ge