JavaScript SDK
The core JavaScript SDK
Section titled “The core JavaScript SDK”@growthbook/growthbook is the foundation package that works in any JavaScript environment — browser, Node.js, Deno, and edge workers (Cloudflare Workers, Vercel Edge, etc.). The React SDK and other framework wrappers are built on top of this package.
Installation
Section titled “Installation”npm install @growthbook/growthbookInitialisation
Section titled “Initialisation”Create a GrowthBook instance with your apiHost and clientKey, then call init(). The init() call fetches feature definitions from the GrowthBook CDN and caches them inside the instance. The optional timeout (in milliseconds) prevents the app from hanging if the network is slow — the SDK falls back to default values if the fetch does not complete in time.
import { GrowthBook } from '@growthbook/growthbook';
const gb = new GrowthBook({ apiHost: 'https://cdn.growthbook.io', clientKey: 'sdk-abc123',});
await gb.init({ timeout: 2000 });Setting user attributes
Section titled “Setting user attributes”Call gb.setAttributes() to give the SDK context about the current user. Attributes are used by targeting rules — for example, “show this flag only to users where country is 'US'” or “only premium accounts”. Pass any key-value pairs your rules reference.
gb.setAttributes({ id: 'user-abc', country: 'US', premium: true,});Always set attributes before evaluating flags so targeting rules have the context they need.
Evaluating flags
Section titled “Evaluating flags”gb.isOn('flag-key') returns a boolean — true if the flag is enabled for the current attributes, false otherwise.
gb.getFeatureValue('flag-key', fallback) returns a typed value. The second argument is the safe fallback returned when the flag is off, the key does not exist, or the type does not match.
Complete browser / vanilla example
Section titled “Complete browser / vanilla example”import { GrowthBook } from '@growthbook/growthbook';
const gb = new GrowthBook({
apiHost: 'https://cdn.growthbook.io',
clientKey: 'sdk-abc123',
});
// Fetch and cache feature definitions
await gb.init({ timeout: 2000 });
// Set user attributes for targeting
gb.setAttributes({
id: 'user-abc',
country: 'US',
premium: true,
});
// Boolean flag
if (gb.isOn('dark-mode')) {
document.body.classList.add('dark');
}
// Typed value with fallback
const theme = gb.getFeatureValue('ui-theme', 'light');
console.log('Theme:', theme);