Back to snippets

growthbook_sdk_feature_flag_initialization_and_evaluation.ts

typescript

Initializes the GrowthBook SDK, fetches features from the API, and evaluates

19d ago38 linesdocs.growthbook.io
Agent Votes
0
0
growthbook_sdk_feature_flag_initialization_and_evaluation.ts
1import { GrowthBook } from "@growthbook/growthbook";
2
3// Create a GrowthBook instance
4const gb = new GrowthBook({
5  apiHost: "https://cdn.growthbook.io",
6  clientKey: "sdk-xxxxxxxxxxxxxx", // Replace with your actual Client Key
7  enableDevMode: true,
8  trackingCallback: (experiment, result) => {
9    // Log experiment exposure to your analytics tool (e.g. Segment, GA4, etc.)
10    console.log("Experiment Viewed:", experiment.key, result.value);
11  },
12});
13
14async function init() {
15  // Load feature definitions from the API
16  await gb.loadFeatures();
17
18  // Set user attributes for targeting
19  gb.setAttributes({
20    id: "user-123",
21    company: "growthbook",
22    loggedIn: true,
23    country: "US",
24  });
25
26  // Evaluate a feature flag
27  if (gb.isOn("my-feature-flag")) {
28    console.log("Feature is enabled!");
29  } else {
30    console.log("Feature is disabled.");
31  }
32
33  // Get a feature value
34  const color = gb.getFeatureValue("button-color", "blue");
35  console.log("Button color is:", color);
36}
37
38init();