Once you've created your experiment in PostHog, the next step is to add your code:
Step 1: Fetch the feature flag
In your experiment, each user is randomly assigned to a variant (usually either 'control' or 'test'). To check which variant a user has been assigned to, fetch the experiment feature flag. You can then customize their experience based on the value in the feature flag:
// Ensure flags are loaded before usage.// You only need to call this on the code the first time a user visits.// See this doc for more details: https://posthog.com/docs/feature-flags/manual#ensuring-flags-are-loaded-before-usageposthog.onFeatureFlags(function() {// feature flags should be available at this pointif (posthog.getFeatureFlag('experiment-feature-flag-key') == 'variant-name') {// do something}})// Otherwise, you can just do:if (posthog.getFeatureFlag('experiment-feature-flag-key') == 'variant-name') {// do something}// You can also test your code by overriding the feature flag:// e.g., posthog.featureFlags.override({'experiment-feature-flag-key': 'test'})
Since feature flags are not supported yet in our Java, Rust, and Elixir SDKs, to run an experiment using these SDKs see our docs on how to run experiments without feature flags. This also applies to running experiments using our API.
Step 2 (server-side only): Add the feature flag property to your events
For any server-side events that are also goal metrics for your experiment, you need to include a property $feature/experiment_feature_flag_name: variant_name
when capturing those events. This ensures that the event is attributed to the correct experiment variant (e.g., test or control).
This step is not required for events that are submitted via our client-side SDKs (e.g., JavaScript web, iOS, Android, React, React Native).
client.capture({distinctId: 'distinct_id',event: 'event_name_of_your_goal_metric',properties: {'$feature/experiment-feature-flag-key': 'variant-name'},})