AGENTIC MEMORY

Skills

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

← Back to Skills

feature-flags-react

PostHog feature flags for React applications

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

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

Ask your assistant

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

references/adding-feature-flag-code.md · 72000

flag-key')) { // Do something differently for this user // Optional: fetch the payload final matchedFlagPayload = await Posthog().getFeatureFlagPayload('flag-key'); }


### Multivariate feature flags

Dart

PostHog AI

```dart
if (await Posthog().getFeatureFlag('flag-key') == 'variant-key') { // replace 'variant-key' with the key of your variant
  // Do something differently for this user
  // Optional: fetch the payload
  final matchedFlagPayload = await Posthog().getFeatureFlagPayload('flag-key');
}

Ensuring flags are loaded before usage

To use the onFeatureFlags callback, you must set up the SDK manually by disabling the com.posthog.posthog.AUTO_INIT mode.

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:

Dart

PostHog AI

final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';
config.onFeatureFlags = () async {
  if (await Posthog().isFeatureEnabled('flag-key')) {
    // do something
  }
};
await Posthog().setup(config);

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:

Dart

PostHog AI

await Posthog().reloadFeatureFlags();

Java

Boolean feature flags

Java

PostHog AI

if (posthog.isFeatureEnabled("distinct_id_of_your_user", "flag-key")) {
    // Do something differently for this user
    // Optional: fetch the payload
    Object matchedFlagPayload = posthog.getFeatureFlagPayload("distinct_id_of_your_user", "flag-key");
}

Multivariate feature flags

Java

PostHog AI

if ("variant-key".equals(posthog.getFeatureFlag("distinct_id_of_your_user", "flag-key"))) { // replace 'variant-key' with the key of your variant
    // Do something differently for this user
    // Optional: fetch the payload
    Object matchedFlagPayload = posthog.getFeatureFlagPayload("distinct_id_of_your_user", "flag-key");
}

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:

Java

PostHog AI

import com.posthog.server.PostHogFeatureFlagOptions;
posthog.getFeatureFlag(
    "distinct_id_of_the_user",
    "flag-key",
    PostHogFeatureFlagOptions
        .builder()
        .defaultValue(false)
        .group("your_group_type", "your_group_id")
        .group("another_group_type", "your_group_id")
        .groupProperty("your_group_type", "group_property_name", "value")
        .groupProperty("another_group_type", "group_property_name", "value")
        .personProperty("property_name", "value")
        .build());

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.

Rust

There are 2 steps to implement feature flags in Rust:

Step 1: Evaluate the feature flag value

Boolean feature flags

Rust

PostHog AI

let is_enabled = client.is_feature_enabled(
    "flag-key".to_string(),
    "distinct_id_of_your_user".to_string(),
    None, // groups
    None, // person_properties
    None, // group_properties
).await.unwrap();
if is_enabled {
    // Do something differently for this user
}

Multivariate feature flags

Rust

PostHog AI

use posthog_rs::FlagValue;
match client.get_feature_flag(
    "flag-key".to_string(),
    "distinct_id_of_your_user".to_string(),
    None, // groups
    None, // person_properties
    None, // group_properties
).await.unwrap() {
    Some(FlagValue::String(variant)) => {
        if variant == "variant-key" {
            // Do something for this variant
        }
    }
    Some(FlagValue::Boolean(enabled)) => {
        // Handle boolean flag
    }
    None => {
        // Flag not found or disabled
    }
}

Step 2: Include feature flag information in your events

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:

Rust

PostHog AI

let mut event = Event::new("event_name", "distinct_id_of_your_user");
event.insert_prop("$feature/feature-flag-key", "variant-key").unwrap();
client.capture(event).unwrap();

Method 2: Fetch and include all flags

Rust

PostHog AI

let (flags, _) = client.get_feature_flags(
    "distinct_id_of_your_user".to_string(),
    None, None, None
).await.unwrap();
let mut event = Event::new("event_name", "distinct_id_of_your_user");
for (key, value) in flags {
    let prop_key = format!("$feature/{}", key);
    match value {
        FlagValue::Boolean(b) => event.insert_prop(&prop_key, b).unwrap(),
        FlagValue::String(s) => event.insert_prop(&prop_key, s).unwrap(),
    };
}
client.capture(event).unwrap();

Fetching all flags for a user

You can fetch all flag values for a single user by calling get_feature_flags().

This is useful when you need to fetch multiple flag values and don't want to make multiple requests.

Rust

PostHog AI

let (flags, payloads) = client.get_feature_flags(
    "distinct_id_of_your_user".to_string(),
    None, // groups
    None, // person_properties
    None, // group_properties
).await.unwrap();
for (key, value) in flags {
    println!("Flag {}: {:?}", key, value);
}

Feature flag payloads

You can retrieve additional data associated with a feature flag using payloads:

Rust

PostHog AI

let payload = client.get_feature_flag_payload(
    "flag-key".to_string(),
    "distinct_id_of_your_user".to_string()
).await.unwrap();
if let Some(data) = payload {
    println!("Payload: {}", data);
}

With person properties

You can include person properties for more targeted flag evaluation:

Rust

PostHog AI

use std::collections::HashMap;
use serde_json::json;
let mut person_props = HashMap::new();
person_props.insert("plan".to_string(), json!("enterprise"));
person_props.insert("country".to_string(), json!("US"));
let flag = client.get_feature_flag(
    "premium-feature".to_string(),
    "distinct_id_of_your_user".to_string(),
    None, // groups
    Some(person_props),
    None, // group_properties
).await.unwrap();

With groups (B2B)

For B2B applications with group-based flags:

Rust

PostHog AI

use std::collections::HashMap;
use serde_json::json;
let mut groups = HashMap::new();
groups.insert("company".to_string(), "company-123".to_string());
let mut group_props = HashMap::new();
let mut company_props = HashMap::new();
company_props.insert("size".to_string(), json!(500));
group_props.insert("company".to_string(), company_props);
let flag = client.get_feature_flag(
    "b2b-feature".to_string(),
    "distinct_id_of_your_user".to_string(),
    Some(groups),
    None, // person_properties
    Some(group_props),
).await.unwrap();

Blocking client

If you're using the blocking client (with default-features = false), the API is the same but without .await:

Rust

PostHog AI

let is_enabled = client.is_feature_enabled(
    "flag-key".to_string(),
    "distinct_id_of_your_user".to_string(),
    None, None, None
).unwrap();

Error handling

When using the PostHog SDK, handle potential errors that may occur during feature flag operations:

Rust

PostHog AI

match client.get_feature_flag(
    "flag-key".to_string(),
    "distinct_id_of_your_user".to_string(),
    None, None, None
).await {
    Ok(Some(value)) => {
        // Use the flag value
        println!("Flag value: {:?}", value);
    }
    Ok(None) => {
        // Flag not found or disabled
        println!("Flag not found");
    }
    Err(e) => {
        // Handle the error appropriately
        eprintln!("Error fetching feature flag: {}", e);
        // Fall back to default behavior
    }
}

Elixir

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

Elixir

PostHog AI

iex> PostHog.FeatureFlags.check("example-feature-flag-1", "user123")
{:ok, true}

It will attempt to take distinct_id from the context if it's not provided.

Elixir

PostHog AI

iex> PostHog.set_context(%{distinct_id: "user123"})
:ok
iex> PostHog.FeatureFlags.check("example-feature-flag-1")
{:ok, true}

Multivariate feature flags

Elixir

PostHog AI

iex> PostHog.FeatureFlags.check("example-feature-flag-1", "user123")
{:ok, "variant2"}

Errors

We'll return an error if the feature flag doesn't exist.

Elixir

PostHog AI

iex> PostHog.FeatureFlags.check("example-feature-flag-3", "user123")
{:error, %PostHog.UnexpectedResponseError{message: "Feature flag example-feature-flag-3 was not found in the response", response: ...}}

You can also use PostHog.FeatureFlags.check!/2 if you're feeling adventurous or running a script and prefer errors to be raised instead.

.NET

There are 2 steps to implement feature flags in .NET:

Step 1: Evaluate the feature flag value

Boolean feature flags

C#

PostHog AI

if (await posthog.IsFeatureEnabledAsync(
    "flag-key",
    "distinct_id_of_your_user"))
{
    // Feature is enabled
}
else
{
    // Feature is disabled
}

Multivariate feature flags

C#

PostHog AI

var flag = await posthog.GetFeatureFlagAsync(
    "flag-key",
    "distinct_id_of_your_user"
);
// replace "variant-key" with the key of your variant
if (flag is { VariantKey: "variant-key"} ) {
    // Do something differently for this user
    // Optional: fetch the payload
    var matchedPayload = flag.Payload;
}

Note: The GetFeatureFlagAsync method returns a nullable FeatureFlag object. If the flag is not found or evaluating it is inconclusive, it returns null. However, there is an implicit conversion to bool to make comparisons easier.

C#

PostHog AI

if (await posthog.GetFeatureFlagAsync(
    "flag-key",
    "distinct_id_of_your_user")
)
{
    // Do something differently for this user
}

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:

C#

PostHog AI

posthog.Capture(
    "distinct_id_of_your_user",
    "event_name",
    properties: new() {
        // replace feature-flag-key with your flag key.
        // Replace "variant-key" with the key of your variant
        ["$feature/feature-flag-key"] = "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.

C#

PostHog AI

posthog.Capture(
    "distinct_id_of_your_user",
    "event_name",
    properties: null,
    groups: null,
    sendFeatureFlags: true
);

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.

C#

PostHog AI

var flags = await posthog.GetAllFeatureFlagsAsync(
    "distinct_id_of_your_user"
);

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:

  1. You call posthog.GetFeatureFlagAsync() or posthog.IsFeatureEnabledAsync(), AND
  2. 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_called events to be sent again when calling GetFeatureFlagAsync or IsFeatureEnabledAsync. PostHog is built to handle this, and so duplicate $feature_flag_called events 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:

C#

PostHog AI

var isMyFlagEnabled = await posthog.IsFeatureEnabledAsync(
    "flag-key",
    "distinct_id_of_your_user",
    options: new FeatureFlagOptions
    {
        SendFeatureFlagEvents = true
    }
);
// will not send `$feature_flag_called` events

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:

C#

PostHog AI

// Overriding Person Properties
var personFlag = await posthog.GetFeatureFlagAsync(
    "flag-key",
    "distinct_id_of_the_user",
    personProperties: new() {["property_name"] = "value"});
// Overriding Group Properties
var groupFlag = await posthog.GetFeatureFlagAsync(
    "flag-key",
    "distinct_id_of_the_user",
    options: new FeatureFlagOptions
    {
        Groups = [
            new Group("your_group_type", "your_group_id")
            {
                ["group_property_name"] = "your group value"
            },
            new Group(
                "another_group_type",
                "another_group_id")
                {
                    ["group_property_name"] = "another group value"
                }
        ]
    });
// Overriding both Person and Group Properties
var bothFlag = await posthog.GetFeatureFlagAsync(
    "flag-key",
    "distinct_id_of_the_user",
    options: new FeatureFlagOptions
    {
        PersonProperties = new() { ["property_name"] = "value" },
        Groups = [
            new Group("your_group_type", "your_group_id")
            {
                ["group_property_name"] = "your group value"
            },
            new Group(
                "another_group_type",
                "another_group_id")
                {
                    ["group_property_name"] = "another group value"
                }
        ]
    });

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.

API

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

PostHog AI

Terminal

# Basic request (flags only)
curl -v -L --header "Content-Type: application/json" -d '  {
    "api_key": "<ph_project_token>",
    "distinct_id": "distinct_id_of_your_user",
    "groups" : {
        "group_type": "group_id"
    }
}' "https://us.i.posthog.com/flags?v=2"
# With configuration (flags + PostHog config)
curl -v -L --header "Content-Type: application/json" -d '  {
    "api_key": "<ph_project_token>",
    "distinct_id": "distinct_id_of_your_user",
    "groups" : {
        "group_type": "group_id"
    }
}' "https://us.i.posthog.com/flags?v=2&config=true"

Python

import requests
import json
# Basic request (flags only)
url = "https://us.i.posthog.com/flags?v=2"
headers = {
    "Content-Type": "application/json"
}
payload = {
    "api_key": "<ph_project_token>",
    "distinct_id": "user distinct id",
    "groups": {
        "group_type": "group_id"
    }
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.json())
# With configuration (flags + PostHog config)
url_with_config = "https://us.i.posthog.com/flags?v=2&config=true"
response_with_config = requests.post(url_with_config, headers=headers, data=json.dumps(payload))
print(response_with_config.json())

Node.js

import fetch from "node-fetch";
async function sendFlagsRequest() {
    const headers = {
        "Content-Type": "application/json",
    };
    const payload = {
        api_key: "<ph_project_token>",
        distinct_id: "user distinct id",
        groups: {
            group_type: "group_id",
        },
    };
    // Basic request (flags only)
    const url = "https://us.i.posthog.com/flags?v=2";
    const response = await fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(payload),
    });
    const data = await response.json();
    console.log(data);
    // With configuration (flags + PostHog config)
    const urlWithConfig = "https://us.i.posthog.com/flags?v=2&config=true";
    const responseWithConfig = await fetch(urlWithConfig, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(payload),
    });
    const dataWithConfig = await responseWithConfig.json();
    console.log(dataWithConfig);
}
sendFlagsRequest();

Note: The groups key is only required for group-based feature flags. If you use it, replace group_type and group_id with the values for your group such as company: "Twitter".

Using evaluation context tags and runtime filtering without SDKs

When making direct API calls to the /flags endpoint, you can control which flags are evaluated using evaluation context tags and runtime filtering.

Evaluation contexts

To filter flags by evaluation context, include the evaluation_contexts field in your request body:

Note: The legacy parameter evaluation_environments is also supported for backward compatibility.

PostHog AI

Terminal

curl -v -L --header "Content-Type: application/json" -d '  {
    "api_key": "<ph_project_token>",
    "distinct_id": "distinct_id_of_your_user",
    "evaluation_contexts": ["production", "web"]
}' "https://us.i.posthog.com/flags?v=2"

Python

import requests
import json
url = "https://us.i.posthog.com/flags?v=2"
headers = {
    "Content-Type": "application/json"
}
payload = {
    "api_key": "<ph_project_token>",
    "distinct_id": "user distinct id",
    "evaluation_contexts": ["production", "web"]
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.json())

JavaScript

const response = await fetch("https://us.i.posthog.com/flags?v=2", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        api_key: "<ph_project_token>",
        distinct_id: "user-distinct-id",
        evaluation_contexts: ["production", "web"]
    }),
});
const data = await response.json();

Only flags where at least one evaluation tag matches (or flags with no tags at all) will be returned. For example:

  • Flag with evaluation context tags ["production", "api", "backend"] + request with ["production", "web"] = ✅ Flag evaluates ("production" matches)
  • Flag with evaluation context tags ["staging", "api"] + request with ["production", "web"] = ❌ Flag doesn't evaluate (no tags match)
  • Flag with evaluation context tags ["web", "mobile"] + request with ["production", "web"] = ✅ Flag evaluates ("web" matches)
  • Flag with no evaluation context tags = ✅ Always evaluates