Adding feature flag code
Once you've created your feature flag in PostHog, the next step is to add your code:
Boolean feature flags
Multivariate feature flags
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:
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:
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 istrueif the request timed out or if there was an error. It will befalseorundefinedif 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 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:
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:
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:
At any point, you can reset these properties by calling resetPersonPropertiesForFlags:
The same holds for group properties:
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:
$geoip_city_name$geoip_country_name$geoip_country_code$geoip_continent_name$geoip_continent_code$geoip_postal_code$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.
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:
There are two ways to implement feature flags in React:
- Using hooks.
- 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
To avoid handling undefined while flags are loading, pass a default value as the second argument:
Example 2: Using a multivariate feature flag
Example 3: Using a flag payload
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.
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
PostHogProviderat the top level for this to work.
Here is an example:
The
matchon the component can be eithertrue, 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
fallbackattribute.
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:
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.
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:
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
Multivariate feature flags
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(), andcapture({ sendFeatureFlags: true })still work during the migration period, but they're deprecated. PreferevaluateFlags()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.
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:
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:
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:
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:
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.
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
Multivariate feature flags
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.get_feature_flag_payload(), andposthog.capture(send_feature_flags=True)still work during the migration period, but they're deprecated. Preferposthog.evaluate_flags()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.
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:
only_accessed() is order-dependent. If you call it before accessing any flags with is_enabled() or get_flag(), 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:
Evaluating only specific flags
By default, posthog.evaluate_flags() evaluates every flag for the user. If you only need a few flags, pass flag_keys to request only those flags:
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 posthog.evaluate_flags(), the SDK sends this event when you call flags.is_enabled() or flags.get_flag() 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.get_flag_payload() doesn't send $feature_flag_called events and doesn't count as an access for only_accessed().
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:
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 feature_flags_request_timeout_seconds 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.
There are two steps to implement feature flags in PHP:
Step 1: Evaluate flags once
Call PostHog::evaluateFlags() once for the user, then read values from the returned snapshot.
Boolean feature flags
Multivariate feature flags
$flags->getFlag() returns the variant string for multivariate flags, true for enabled boolean flags, false for disabled flags, and null when the flag wasn't returned by the evaluation.
You can also call $flags->getKeys() to list the evaluated flag keys, or $flags->getEventProperties() to get the $feature/<flag-key> and $active_feature_flags properties that would be attached to a captured event.
Note:
PostHog::isFeatureEnabled(),PostHog::getFeatureFlag(),PostHog::getFeatureFlagPayload(), andcapture(['send_feature_flags' => true])still work during the migration period, but they're deprecated. PreferevaluateFlags()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.
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:
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:
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:
Optional evaluation parameters
evaluateFlags() also accepts optional parameters for local evaluation and GeoIP behavior:
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 (flag key, distinct_id) 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:
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 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 if PostHog's servers are too slow to respond. By default, this is set to 3 seconds.
There are two steps to implement feature flags in Ruby:
Step 1: Evaluate flags once
Call posthog.evaluate_flags() once for the user, then read values from the returned snapshot.
Boolean feature flags
Multivariate feature flags
flags.get_flag() returns the variant string for multivariate flags, true for enabled boolean flags, false for disabled flags, and nil when the flag wasn't returned by the evaluation.
Note:
posthog.is_feature_enabled(),posthog.get_feature_flag(),posthog.get_feature_flag_result(),posthog.get_feature_flag_payload(), andcapture({ ..., send_feature_flags: true })still work during the migration period, but they're deprecated. Preferevaluate_flags()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.
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:
only_accessed is order-dependent. If you call it before accessing any flags with enabled?() or get_flag(), 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:
Evaluating only specific flags
By default, evaluate_flags() evaluates every flag for the user. If you only need a few flags, pass flag_keys to request only those flags:
Evaluating locally only
If you want to skip the remote /flags request and only use locally cached definitions, pass only_evaluate_locally: true:
Disabling GeoIP for flag evaluation
Pass disable_geoip: true to disable GeoIP lookup for remote flag evaluation:
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 evaluate_flags(), the SDK sends this event when you call flags.enabled?() or flags.get_flag() 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.get_flag_payload() doesn't send $feature_flag_called events and doesn't count as an access for only_accessed.
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:
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 feature_flag_request_timeout_seconds 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.
There are two steps to implement feature flags in Go:
Step 1: Evaluate flags once
Call client.EvaluateFlags() once for the user, then read values from the returned snapshot.
Boolean feature flags
Multivariate feature flags
flags.GetFlag() returns the variant string for multivariate flags, true for enabled boolean flags, false for disabled flags, and nil when the flag wasn't returned by the evaluation.
Note:
client.IsFeatureEnabled(),client.GetFeatureFlag(),client.GetFeatureFlagPayload(), andCapture.SendFeatureFlagsstill work during the migration period, but they're deprecated. PreferEvaluateFlags()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.
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:
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:
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:
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:
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 FeatureFlagRequestTimeout 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.
There are two ways to implement feature flags in React Native:
- Using hooks.
- Loading the flag directly.