Adding experiment code

Last updated:

|

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:

// 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'}})

Since feature flags are not supported yet in our Java and Rust 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.

Questions? Ask Max AI.

It's easier than reading through 814 pages of documentation

Community questions

Was this page useful?

Next article

Testing and launching an experiment

Once you've written your code, it's a good idea to test that each variant behaves as you'd expect. If you find out your implementation had a bug after you've launched the experiment, you lose days of effort as the experiment results can no longer be trusted. The best way to do this is adding an optional override to your release conditions . For example, you can create an override to assign a user to the test variant if their email is your own (or someone in your team). To do this: Go to…

Read next article