Adding experiment code

Once you've created your experiment in PostHog, the next step is to add your code.

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:

Only getFeatureFlag() counts as an exposure

You must use getFeatureFlag() (or its framework equivalent like useFeatureFlagVariantKey()) to check variants. Other methods like getAllFlags(), getFeatureFlags(), or getFeatureFlagPayload() alone do not record an exposure event. Users evaluated with those methods won't be included in your experiment results.

// 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: /docs/feature-flags/manual#ensuring-flags-are-loaded-before-usage
posthog.onFeatureFlags(function() {
// feature flags should be available at this point
if (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.overrideFeatureFlags({ flags: {'experiment-feature-flag-key': 'test'}})

To run an experiment using our API (without any SDK), see our docs on how to run experiments without feature flags.

Community questions

Was this page useful?

Questions about this page? or post a community question.