references/adding-feature-flag-code.md · 48000
turned 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.
flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{
DistinctId: "distinct_id_of_your_user",
})
if err != nil {
// Handle error
}
if flags.IsEnabled("flag-key") {
// Do something differently for this user
}
client.Enqueue(posthog.Capture{
DistinctId: "distinct_id_of_your_user",
Event: "event_name",
Flags: 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.Enqueue(posthog.Capture{
DistinctId: "distinct_id_of_your_user",
Event: "event_name",
Flags: flags.OnlyAccessed(),
})
// Attach only specific flags
client.Enqueue(posthog.Capture{
DistinctId: "distinct_id_of_your_user",
Event: "event_name",
Flags: flags.Only([]string{"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.Enqueue(posthog.Capture{
DistinctId: "distinct_id_of_your_user",
Event: "event_name",
Properties: posthog.NewProperties().
Set("$feature/feature-flag-key", "variant-key"), // replace feature-flag-key with your flag key. Replace "variant-key" with the key of your variant
})
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:
flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{
DistinctId: "distinct_id_of_your_user",
FlagKeys: []string{"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:
flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{
DistinctId: "distinct_id_of_the_user",
Groups: posthog.NewGroups().
Set("your_group_type", "your_group_id").
Set("another_group_type", "your_group_id"),
PersonProperties: posthog.NewProperties().
Set("property_name", "value"),
GroupProperties: map[string]posthog.Properties{
"your_group_type": posthog.NewProperties().
Set("group_property_name", "value"),
"another_group_type": posthog.NewProperties().
Set("group_property_name", "value"),
},
})
if err != nil {
// Handle error
}
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 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.
// import "time"
client, _ := posthog.NewWithConfig(
os.Getenv("<ph_project_token>"),
posthog.Config{
PersonalApiKey: "your personal API key", // Optional, but much more performant. If this token is not supplied, then fetching feature flag values will be slower.
Endpoint: "https://us.i.posthog.com",
FeatureFlagRequestTimeout: 3 * time.Second, // Defaults to 3 seconds.
},
)
React Native
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
import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
const booleanFlag = useFeatureFlag('key-for-your-boolean-flag')
if (booleanFlag === undefined) {
// the response is undefined if the flags are being loaded
return null
}
// Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
return booleanFlag ? <Text>Testing feature 😄</Text> : <Text>Not Testing feature 😢</Text>
}
Example 2: Multivariate feature flags
import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
const multiVariantFeature = useFeatureFlag('key-for-your-multivariate-flag')
if (multiVariantFeature === undefined) {
// the response is undefined if the flags are being loaded
return null
} else if (multiVariantFeature === 'variant-name') { // replace 'variant-name' with the name of your variant
// Do something
}
// Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
return <div/>
}
Method 2: Loading the flag directly
// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.isFeatureEnabled('key-for-your-boolean-flag')
// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlag('key-for-your-boolean-flag')
// Multivariant feature flags are returned as a string
posthog.getFeatureFlag('key-for-your-multivariate-flag')
// Optional: fetch the payload (returns 'JsonType' or undefined if not loaded yet or if there was a problem loading)
posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.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 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:
posthog.onFeatureFlags((flags) => {
// feature flags are guaranteed to be available at this point
if (posthog.isFeatureEnabled('flag-key')) {
// do something
}
})
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():
posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))
Or when you want to trigger the reload, but don't care about the result:
posthog.reloadFeatureFlags()
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:
// Force refresh on app start
await posthog.reloadFeatureFlagsAsync()
Or clear cached values for inactive users:
if (lastActiveDate < migrationDate) {
posthog.reset() // Clears all cached data
}
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.
export const posthog = new PostHog('<ph_project_token>', {
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
host: 'https://us.i.posthog.com',
featureFlagsRequestTimeoutMs: 10000 // Time in milliseconds. Default is 10000 (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:
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
}
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 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:
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 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:
- $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.
Android
Boolean feature flags
import com.posthog.PostHog
val result = PostHog.getFeatureFlagResult("flag-key")
if (result?.enabled == true) {
// Do something differently for this user
// Optional: fetch the payload from the same evaluation result
val matchedFlagPayload = result.payload
}
Multivariate feature flags
import com.posthog.PostHog
val 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
val matchedFlagPayload = result.payload
}
Inspecting all feature flags
You can inspect all currently loaded feature flags with PostHog.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:
import com.posthog.PostHog
PostHog.getAllFeatureFlags()?.forEach { flag ->
println("${flag.key} ${flag.enabled} ${flag.variant} ${flag.payload}")
}
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:
import com.posthog.PostHog
import com.posthog.android.PostHogAndroidConfig
import com.posthog.PostHogOnFeatureFlags
// During SDK initialization
val config = PostHogAndroidConfig(apiKey = "<ph_project_token>").apply {
onFeatureFlags = PostHogOnFeatureFlags {
if (PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}
}
// And/or after the SDK is initialized
PostHog.reloadFeatureFlags {
if (PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}
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:
import com.posthog.PostHog
PostHog.reloadFeatureFlags()
Tracking feature usage
To track when someone sees or interacts with a feature, use captureFeatureView and captureFeatureInteraction.
import com.posthog.PostHog
PostHog.captureFeatureView("flag-key", flagVariant = "variant-key")
PostHog.captureFeatureInteraction("flag-key", flagVariant = "variant-key")
iOS
Boolean feature flags
if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"), result.enabled {
// Do something differently for this user
// Optional: fetch the payload from the same evaluation result
let matchedFlagPayload = result.payload
}
Multivariate feature flags
if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"), 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
let matchedFlagPayload = result.payload
}
Typed payloads
If your payload is a JSON object, you can decode it into a Decodable type:
struct FlagPayload: Decodable {
let title: String
}
if let result = PostHogSDK.shared.getFeatureFlagResult("flag-key"),
let payload = result.payloadAs(FlagPayload.self) {
// Use payload.title
}
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 flag in PostHogSDK.shared.getAllFeatureFlags() ?? [] {
print(flag.key, flag.enabled, flag.variant as Any, flag.payload as Any)
}
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:
PostHogSDK.shared.reloadFeatureFlags()
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 be notified when flags are loaded or change. It's available in version 3.89.0+:
let subscription = PostHogSDK.shared.onFeatureFlags { loaded in
if loaded.errorsLoading {
// Loading failed, so the flags are the last known values, which can be empty.
// Fall back to your default experience if you need fresh values.
return
}
if PostHogSDK.shared.isFeatureEnabled("flag-key") {
// do something
}
}
// Later, to stop receiving updates
subscription.unsubscribe()
The callback runs on the main thread. It's called when flags load – including from bootstrap values – and again each time they're reloaded, for example after reloadFeatureFlags(), reset(), or an identify() or group() call that changes the distinct ID or group. A reload doesn't have to change any values, so treat each call as "flags may have changed". If flags have already loaded when you register, it's called shortly afterwards with the current values. You can register before calling setup().
Callback parameters
The callback receives a PostHogFeatureFlagsLoaded object with the following properties:
-
flags: [String]: The keys of the enabled feature flags. -
variants: [String: Any]: The values of the enabled feature flags, keyed by flag key. A value istruefor an enabled boolean flag, or the variant key for a multivariate flag. -
errorsLoading: Bool:trueif the latest attempt to load feature flags failed, for example because the device is offline. The flags and variants then hold the last known values, which can be empty – for example, on a fresh install with no bootstrap values. In that case,isFeatureEnabledreturnsfalsebecause the flag is unknown, not because PostHog evaluated it as disabled.
On versions earlier than 3.89.0, observe the PostHogSDK.didReceiveFeatureFlags notification instead. Register the observer before calling setup():
let observer = NotificationCenter.default.addObserver(
forName: PostHogSDK.didReceiveFeatureFlags,
object: nil,
queue: .main
) { _ in
if PostHogSDK.shared.isFeatureEnabled("flag-key") {
// do something
}
}
// Later, to stop receiving updates
NotificationCenter.default.removeObserver(observer)
Alternatively, you can use the completion block of the reloadFeatureFlags(_:) method. This allows you to execute logic immediately after the flags are reloaded:
// Reload feature flags and check if a specific feature is enabled
PostHogSDK.shared.reloadFeatureFlags {
if PostHogSDK.shared.isFeatureEnabled("flag-key") {
// do something
}
}
Tracking feature usage
To track when someone sees or interacts with a feature, use captureFeatureView and captureFeatureInteraction.
PostHogSDK.shared.captureFeatureView(flag: "flag-key", flagVariant: "variant-key")
PostHogSDK.shared.captureFeatureInteraction(flag: "flag-key", flagVariant: "variant-key")
Flutter
Boolean feature flags
final result = await Posthog().getFeatureFlagResult('flag-key');
if (result != null && result.enabled) {
// Do something differently for this user
// Optional: fetch the payload from the same evaluation result
final matchedFlagPayload = result.payload;
}
Multivariate feature flags
final result = await Posthog().getFeatureFlagResult('flag-key');
if (result != null && 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
final matchedFlagPayload = result.payload;
}
Ensuring flags are loaded before usage
To use the
onFeatureFlagscallback, you must set up the SDK manually. On Android and iOS, disablecom.posthog.posthog.AUTO_INITfirst.
Every time a user opens the app, we send a request in