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
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).
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 a boolean indicating whether the feature flag is enabled. This sends a $feature_flag_called event. |
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
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 2 steps to implement feature flags in Node:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set sendFeatureFlags to true
The capture() method has an optional argument sendFeatureFlags, which is set to false by default. This parameter controls whether feature flag information is sent with the event.
Basic usage
Setting sendFeatureFlags to true will include feature flag information with the event:
Advanced usage (v5.5.0+)
As of version 5.5.0, sendFeatureFlags can also accept an options object for more granular control:
Performance considerations
With local evaluation: When local evaluation is configured, setting
sendFeatureFlags: truewill not make additional server requests. Instead, it uses the locally cached feature flags, and it provides an interface for including person and/or group properties needed to evaluate the flags in the context of the event, if required.Without local evaluation: PostHog will make an additional request to fetch feature flag information before capturing the event, which adds delay.
Breaking change in v5.5.0
Prior to version 5.5.0, feature flags were automatically sent with events when using local evaluation, even when sendFeatureFlags was not explicitly set. This behavior has been removed in v5.5.0 to be more predictable and explicit.
If you were relying on this automatic behavior, you must now explicitly set sendFeatureFlags: true to continue sending feature flags with your events.
Fetching all flags for a user
You can fetch all flag values for a single user by calling getAllFlags() or getAllFlagsAndPayloads().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
posthog.getFeatureFlag()orposthog.isFeatureEnabled(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callinggetFeatureFlagorisFeatureEnabled. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it, set the sendFeatureFlagEvents argument in your function call, like so:
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 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 2 steps to implement feature flags in Python:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set send_feature_flags to true
The capture() method has an optional argument send_feature_flags, which is set to false by default. This parameter controls whether feature flag information is sent with the event.
Basic usage
Setting send_feature_flags to True will include feature flag information with the event:
Advanced usage (v6.3.0+)
As of version 6.3.0, send_feature_flags can also accept a dictionary for more granular control:
Performance considerations
With local evaluation: When local evaluation is configured, setting
send_feature_flags: Truewill not make additional server requests. Instead, it uses the locally cached feature flags, and it provides an interface for including person and/or group properties needed to evaluate the flags in the context of the event, if required.Without local evaluation: PostHog will make an additional request to fetch feature flag information before capturing the event, which adds delay.
Breaking change in v6.3.0
Prior to version 6.3.0, feature flags were automatically sent with events when using local evaluation, even when send_feature_flags was not explicitly set. This behavior has been removed in v6.3.0 to be more predictable and explicit.
If you were relying on this automatic behavior, you must now explicitly set send_feature_flags=True to continue sending feature flags with your events.
Fetching all flags for a user
You can fetch all flag values for a single user by calling get_all_flags() or get_all_flags_and_payloads().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
posthog.get_feature_flag()orposthog.feature_enabled(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callingget_feature_flagorfeature_enabled. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it, set the send_feature_flag_events argument in your function call, like so:
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 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 2 steps to implement feature flags in PHP:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set send_feature_flags to true
The capture() method has an optional argument send_feature_flags, which is set to false by default. By setting this to true, feature flag information will automatically be sent with the event.
Note that by doing this, PostHog will make an additional request to fetch feature flag information before capturing the event. So this method is only recommended if you don't mind the extra API call and delay.
Fetching all flags for a user
You can fetch all flag values for a single user by calling getAllFlags().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
getFeatureFlag()orisFeatureEnabled(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callinggetFeatureFlagorisFeatureEnabled. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it, set the sendFeatureFlagEvents argument in your function call, like so:
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 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 2 steps to implement feature flags in Ruby:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set send_feature_flags to true
The capture() method has an optional argument send_feature_flags, which is set to false by default. This parameter controls whether feature flag information is sent with the event.
Basic usage
Setting send_feature_flags to true will include feature flag information with the event:
Advanced usage (v3.1.0+)
As of version 3.1.0, send_feature_flags can also accept a hash for more granular control:
Performance considerations
With local evaluation: When local evaluation is configured, setting
send_feature_flags: truewill not make additional server requests. Instead, it uses the locally cached feature flags, and it provides an interface for including person and/or group properties needed to evaluate the flags in the context of the event, if required.Without local evaluation: PostHog will make an additional request to fetch feature flag information before capturing the event, which adds delay.
Breaking change in v3.1.0
Prior to version 3.1.0, feature flags were automatically sent with events when using local evaluation, even when send_feature_flags was not explicitly set. This behavior has been removed in v3.1.0 to be more predictable and explicit.
If you were relying on this automatic behavior, you must now explicitly set send_feature_flags: true to continue sending feature flags with your events.
Fetching all flags for a user
You can fetch all flag values for a single user by calling get_all_flags() or get_all_flags_and_payloads().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
posthog.get_feature_flag()orposthog.is_feature_enabled(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callingget_feature_flagoris_feature_enabled. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it, set the send_feature_flag_events argument in your function call, like so:
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 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 2 steps to implement feature flags in Go:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set SendFeatureFlags to true
The Capture struct has an optional field SendFeatureFlags, which is set to false by default. This parameter controls whether feature flag information is sent with the event.
Basic usage
Setting SendFeatureFlags to true will include feature flag information with the event:
Advanced usage (v1.6.1+)
As of version 1.6.1, SendFeatureFlags can also accept a SendFeatureFlagsOptions struct for more granular control:
Performance considerations
With local evaluation: When local evaluation is configured, setting
SendFeatureFlags: truewill not make additional server requests. Instead, it uses the locally cached feature flags, and it provides an interface for including person and/or group properties needed to evaluate the flags in the context of the event, if required.Without local evaluation: PostHog will make an additional request to fetch feature flag information before capturing the event, which adds delay.
Breaking change in v1.6.1
Prior to version 1.6.1, feature flags were automatically sent with events when using local evaluation, even when SendFeatureFlags was not explicitly set. This behavior has been removed in v1.6.1 to be more predictable and explicit.
If you were relying on this automatic behavior, you must now explicitly set SendFeatureFlags: true to continue sending feature flags with your events.
Fetching all flags for a user
You can fetch all flag values for a single user by calling GetAllFlags().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
GetFeatureFlag()orIsFeatureEnabled(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callingGetFeatureFlagorIsFeatureEnabled. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it (pre v1.6.1), set the SendFeatureFlagEvents argument in your function call, like so:
Versions after v1.6.1 have this feature disabled by default.
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 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 ways to implement feature flags in React Native:
- Using hooks.
- Loading the flag directly.
Method 1: Using hooks
Example 1: Boolean feature flags
Example 2: Multivariate feature flags
Method 2: Loading the flag directly
Reloading flags
PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.
If want to manually trigger a refresh, you can call reloadFeatureFlagsAsync():
Or when you want to trigger the reload, but don't care about the result:
Feature flag caching
The React Native SDK caches feature flag values in AsyncStorage. Cached values persist indefinitely with no TTL until updated by a successful API call. This enables offline support and reduces latency, but means inactive users may see stale flag values from their last session.
For example, if a user last opened your app when a flag was false, that value remains cached even after you roll it out to 100%. When they reopen the app, the SDK returns the cached false first, then fetches the fresh true value from the API.
To ensure fresh flag values:
Or clear cached values for inactive users:
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 in the case when PostHog's servers are too slow to respond. By default, this is set at 10 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:
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 that 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.
Boolean feature flags
Multivariate feature flags
Ensuring flags are loaded before usage
Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.
This means that for most screens, 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:
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:
Boolean feature flags
Multivariate feature 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:
Ensuring flags are loaded before usage
Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.
This means that for most screens, the feature flags are available immediately – except for the first time a user visits.
To handle this, you can use the didReceiveFeatureFlags notification to wait for the feature flag request to finish:
Alternatively, you can use the completion block of the reloadFeatureFlags(_:) method. This allows you to execute logic immediately after the flags are reloaded:
Boolean feature flags
Multivariate feature flags
Ensuring flags are loaded before usage
To use the
onFeatureFlagscallback, you must set up the SDK manually by disabling thecom.posthog.posthog.AUTO_INITmode.
Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.
This means that for most screens, the feature flags are available immediately – except for the first time a user visits.
To handle this, you can use the onFeatureFlags callback in your config to be notified when flags are loaded:
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:
Boolean feature flags
Multivariate feature flags
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.
Feature flags are not supported yet in our community-maintained Rust SDK. However, you can integrate them into your project by using the PostHog API.
PostHog.FeatureFlags.check/2 is the main function for checking a feature flag in Elixir. More documentation on it can be found in the HexPM Docs.
Boolean feature flags
It will attempt to take distinct_id from the context if it's not provided.
Multivariate feature flags
Errors
We'll return an error if the feature flag doesn't exist.
You can also use PostHog.FeatureFlags.check!/2 if you're feeling adventurous or running a script and prefer errors to be raised instead.
There are 2 steps to implement feature flags in .NET:
Step 1: Evaluate the feature flag value
Boolean feature flags
Multivariate feature flags
Note: The
GetFeatureFlagAsyncmethod returns a nullableFeatureFlagobject. If the flag is not found or evaluating it is inconclusive, it returnsnull. However, there is an implicit conversion to bool to make comparisons easier.
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: Include the $feature/feature_flag_name property
In the event properties, include $feature/feature_flag_name: variant_key:
Method 2: Set send_feature_flags to true
The Capture() method has an optional argument sendFeatureFlags, which is set to false by default. By setting this to true, feature flag information will automatically be sent with the event.
Note that by doing this, PostHog will make an additional request to fetch feature flag information before capturing the event. So this method is only recommended if you don't mind the extra API call and delay.
Fetching all flags for a user
You can fetch all flag values for a single user by calling GetAllFeatureFlagsAsync().
This is useful when you need to fetch multiple flag values and don't want to make multiple requests.
Sending $feature_flag_called events
Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:
- You call
posthog.GetFeatureFlagAsync()orposthog.IsFeatureEnabledAsync(), AND - It's a new user, or the value of the flag has changed.
Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing
$feature_flag_calledevents to be sent again when callingGetFeatureFlagAsyncorIsFeatureEnabledAsync. PostHog is built to handle this, and so duplicate$feature_flag_calledevents won't affect your analytics.
You can disable automatically the additional request to capture $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.
To disable it, set the sendFeatureFlagsEvent option in your function call, like so:
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.
There are 3 steps to implement feature flags using the PostHog API:
Step 1: Evaluate the feature flag value using flags
flags is the endpoint used to determine if a given flag is enabled for a certain user or not.
Request
Note: The
groupskey is only required for group-based feature flags. If you use it, replacegroup_typeandgroup_idwith the values for your group such ascompany: "Twitter".
Using evaluation environment tags and runtime filtering without SDKs
When making direct API calls to the /flags endpoint, you can control which flags are evaluated using evaluation environment tags and runtime filtering.
Evaluation environments
To filter flags by evaluation environment, include the evaluation_environments field in your request body:
Only flags where at least one evaluation tag matches (or flags with no tags at all) will be returned. For example:
- Flag with evaluation environment tags
["production", "api", "backend"]+ request with["production", "web"]= ✅ Flag evaluates ("production" matches) - Flag with evaluation environment tags
["staging", "api"]+ request with["production", "web"]= ❌ Flag doesn't evaluate (no tags match) - Flag with evaluation environment tags
["web", "mobile"]+ request with["production", "web"]= ✅ Flag evaluates ("web" matches) - Flag with no evaluation environment tags = ✅ Always evaluates (backward compatibility)
Runtime detection
Evaluation runtime (server vs. client) is automatically detected based on your request headers and user-agent. This determines which flags are available based on their runtime setting (server-only, client-only, or all).
How runtime is detected:
User-Agent patterns - The system analyzes the User-Agent header:
- Client-side patterns:
Mozilla/,Chrome/,Safari/,Firefox/,Edge/(browsers), or mobile SDKs likeposthog-android/,posthog-ios/,posthog-react-native/,posthog-flutter/ - Server-side patterns:
posthog-python/,posthog-ruby/,posthog-php/,posthog-java/,posthog-go/,posthog-node/,posthog-dotnet/,posthog-elixir/,python-requests/,curl/
- Client-side patterns:
Browser-specific headers - Presence of these headers indicates client-side:
OriginheaderRefererheaderSec-Fetch-ModeheaderSec-Fetch-Siteheader
Default behavior - If runtime can't be determined, the system includes flags with no runtime requirement and those set to "all"
Examples of runtime detection:
Combining evaluation environment tags and runtime filtering
Both features work together as sequential filters:
This allows precise control over which flags are evaluated in different contexts, helping optimize costs and improve security by ensuring flags only evaluate where intended.
Response
The response varies depending on whether you include the config=true query parameter:
Basic response (/flags?v=2)
Use this endpoint when you only need to evaluate feature flags. It returns a response with just the flag evaluation results:
Full response with configuration (/flags?v=2&config=true)
Use this endpoint when you need both feature flag evaluation and PostHog configuration information (useful for client-side SDKs that need to initialize PostHog):
Note:
errorsWhileComputingFlagswill returntrueif we didn't manage to compute some flags (for example, if there's an ongoing incident involving flag evaluation).This enables partial updates to currently active flags in your clients.
Quota limiting
If your organization exceeds its feature flag quota, the /flags endpoint will return a modified response with quotaLimited.
For basic response (/flags?v=2):
For full response with configuration (/flags?v=2&config=true):
When you receive a response with quotaLimited containing "feature_flags", it means:
- Your feature flag evaluations have been temporarily paused because you've exceeded your feature flag quota
- If you want to continue evaluating feature flags, you can increase your quota in your billing settings under Feature flags & Experiments or contact support
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.
To do this, include the $feature/feature_flag_name property in your event:
Step 3: Send a $feature_flag_called event
To track usage of your feature flag and view related analytics in PostHog, submit the $feature_flag_called event whenever you check a feature flag value in your code.
You need to include two properties with this event:
$feature_flag_response: This is the name of the variant the user has been assigned to e.g., "control" or "test"$feature_flag: This is the key of the feature flag in your experiment.
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.
To override the GeoIP properties used to evaluate a feature flag, provide an IP address in the HTTP_X_FORWARDED_FOR when making your /flags request:
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