Running Experiments with the SDK
Running an experiment directly in code
Section titled “Running an experiment directly in code”GrowthBook gives you two ways to run an A/B experiment:
- Feature-flag experiments — you create a Feature in the GrowthBook UI, attach an Experiment rule, and read the variation with
gb.getFeatureValue(). The assignment logic lives in GrowthBook. - Inline experiments with
gb.run()— you define the entire experiment in your code and pass it to the SDK. No feature rule needed in the UI.
gb.run() is useful when you want to experiment on something that does not map cleanly to a feature flag, or when you are prototyping quickly and do not need a full GrowthBook UI setup.
The result object
Section titled “The result object”gb.run() returns a result object with three key properties:
| Property | Type | Description |
|---|---|---|
result.value | string / number / boolean | The variation value assigned to the current user |
result.inExperiment | boolean | true if the user was successfully assigned to a variation bucket |
result.variationId | number | The 0-based index of the assigned variation |
When result.inExperiment is false, the user fell outside the experiment (e.g. traffic coverage is less than 100 %, or the experiment is stopped). In that case result.value is always the first element in the variations array — your safe default.
Inline experiment example
Section titled “Inline experiment example”The snippet below initialises the SDK and calls gb.run() to assign a user to a button-colour variation:
import { GrowthBook } from '@growthbook/growthbook';
const gb = new GrowthBook({
apiHost: 'https://cdn.growthbook.io',
clientKey: 'sdk-YOUR_KEY',
});
await gb.init({ timeout: 2000 });
const result = gb.run({
key: 'button-color-test',
variations: ['blue', 'green'],
});
if (result.inExperiment) {
console.log('Variation:', result.value);
// result.value is 'blue' or 'green'
} else {
// User is not in the experiment — use default
console.log('Not in experiment');
}