### Install Go SDK using go get Source: https://docs.developers.optimizely.com/feature-experimentation/docs/install-sdk-go Use this command to install the Optimizely Feature Experimentation Go SDK. For v2, append '/v2' to the path. ```go go get github.com/optimizely/go-sdk // for v2: go get github.com/optimizely/go-sdk/v2 ``` -------------------------------- ### Install Optimizely Go SDK Source: https://docs.developers.optimizely.com/feature-experimentation/docs/go-quickstart Install the Optimizely Feature Experimentation Go SDK using the go get command. This is the first step to integrating Optimizely into your Go project. ```shell go get github.com/optimizely/go-sdk/v2 ``` -------------------------------- ### Install Dependencies and Run Next.js (NPM) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/vercel-functions Install project dependencies and start the Next.js development server using NPM. ```shell npm install npm run dev ``` -------------------------------- ### Basic C# SDK Initialization Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-csharp Instantiates the Optimizely SDK with an SDK key. This is the simplest way to get started. ```csharp using OptimizelySDK; public class Program { public static void Main(string[] args) { var sdkKey = args[0]; var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey); } } ``` -------------------------------- ### Install Dependencies and Run Next.js (Yarn) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/vercel-functions Install project dependencies and start the Next.js development server using Yarn. ```shell yarn yarn dev ``` -------------------------------- ### Install Go SDK from CLI Source Source: https://docs.developers.optimizely.com/feature-experimentation/docs/install-sdk-go Install the Optimizely Feature Experimentation Go SDK by fetching from source, navigating to the directory, and running 'go install'. For v2, append '/v2' to the path. ```go go get github.com/optimizely/go-sdk // for v2: go get github.com/optimizely/go-sdk/v2 cd $GOPATH/src/github.com/optimizely/go-sdk go install ``` -------------------------------- ### Install Node Modules Source: https://docs.developers.optimizely.com/feature-experimentation/docs/akamai-edgeworkers Installs the necessary Node.js modules for the project. Run this after downloading the starter kit. ```shell npm install ``` -------------------------------- ### Install with pnpm Source: https://docs.developers.optimizely.com/feature-experimentation/docs/install-sdk-javascript-node Use this command to install the SDK using pnpm. ```shell pnpm add @optimizely/optimizely-sdk ``` -------------------------------- ### Install with npm Source: https://docs.developers.optimizely.com/feature-experimentation/docs/install-sdk-javascript-node Use this command to install the SDK using npm. ```shell npm install --save @optimizely/optimizely-sdk ``` -------------------------------- ### Full Client Creation Example in React Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-the-react-native-sdk This snippet demonstrates how to create a fully configured Optimizely client instance in a React application. It includes setup for project configuration management, event processing, ODP integration, VUID tracking, custom logging, and error notification. ```jsx import { createInstance, createPollingProjectConfigManager, createBatchEventProcessor, createOdpManager, createVuidManager, createLogger, createErrorNotifier, DEBUG, } from '@optimizely/react-sdk'; const optimizely = createInstance({ projectConfigManager: createPollingProjectConfigManager({ sdkKey: 'YOUR_SDK_KEY', autoUpdate: true, updateInterval: 60000, }), eventProcessor: createBatchEventProcessor({ batchSize: 10, flushInterval: 2000, }), odpManager: createOdpManager(), vuidManager: createVuidManager({ enableVuid: true }), logger: createLogger({ logLevel: DEBUG }), errorNotifier: createErrorNotifier({ handleError: (error) => console.error('Custom error handler', error), }), }); ``` -------------------------------- ### Install with yarn Source: https://docs.developers.optimizely.com/feature-experimentation/docs/install-sdk-javascript-node Use this command to install the SDK using yarn. ```shell yarn add @optimizely/optimizely-sdk ``` -------------------------------- ### Basic Initialization with SDK Key Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-go Instantiates a client that syncs the datafile in the background using an SDK key. Ensure you handle potential errors during client creation. ```go import optly "github.com/optimizely/go-sdk" // for v2: "github.com/optimizely/go-sdk/v2" // Instantiates a client that syncs the datafile in the background optlyClient, err := optly.Client("SDK_KEY_HERE") if err != nil{ // handle error } ``` -------------------------------- ### Optimizely Go SDK Quickstart Application Source: https://docs.developers.optimizely.com/feature-experimentation/docs/go-quickstart A sample Go application demonstrating Optimizely Feature Experimentation. Replace YOUR_SDK_KEY with your actual Optimizely SDK key. This code initializes the client, creates random users, and decides flag variations. ```go // Package main // package main import ( "fmt" "math/rand" "time" optly "github.com/optimizely/go-sdk/v2" "github.com/optimizely/go-sdk/v2/pkg/logging" ) func main() { logging.SetLogLevel(logging.LogLevelError) // this Optimizely initialization is synchronous. for other methods see the Go SDK reference if optimizelyClient, err := optly.Client("YOUR_SDK_KEY"); err == nil { // -------------------------------- // to get rapid demo results, generate random users. Each user always sees the same variation unless you reconfigure the flag rule. // -------------------------------- rand.Seed(time.Now().UnixNano()) flagsStatus := "off" for i := 0; i < 10; i++ { userID := fmt.Sprintf("%v", rand.Intn(8999)+1000) // -------------------------------- // Create hardcoded user & bucket user into a flag variation // -------------------------------- user := optimizelyClient.CreateUserContext(userID, nil) // "product_sort" corresponds to a flag key in your Optimizely project decision := user.Decide("product_sort", nil) // did decision fail with a critical error? if decision.VariationKey == "" { fmt.Printf("\ndecision error: %q", decision.Reasons) } // get a dynamic configuration variable // "sort_method" corresponds to a variable key in your Optimizely project sortMethod := decision.Variables.ToMap()["sort_method"] // -------------------------------- // Mock what the user sees with print statements (in production, use flag variables to implement feature configuration) // -------------------------------- // always returns false until you enable a flag rule in your Optimizely project if decision.Enabled { // Keep count how many users had the flag enabled flagsStatus = "on" } fmt.Printf("\n\nFlag %s. User number %v saw flag variation: %s and got products sorted by: %v config variable as part of flag rule: %s", flagsStatus, user.GetUserID(), decision.VariationKey, sortMethod, decision.RuleKey) } if flagsStatus == "off" { fmt.Println("Flag was off for everyone. Some reasons could include:") fmt.Println("1. Your sample size of users was too small. Rerun, or increase the iterations in the FOR loop") fmt.Println("2. Check your SDK key. Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON.") if config, err := optimizelyClient.ConfigManager.GetConfig(); err == nil { fmt.Printf("\ncheck your key at https://app.optimizely.com/v2/projects/%s/settings/implementation", config.GetProjectID()) } } } else { fmt.Println("Optimizely client invalid. Verify in Settings>Environments that you used the primary environment's SDK key") } } ``` -------------------------------- ### Create Local Environment File Source: https://docs.developers.optimizely.com/feature-experimentation/docs/vercel-functions Copy the example environment file to create a local configuration. Remember to add your SDK key. ```shell cp .env.example .env.local ``` -------------------------------- ### Initialize with SDK Key Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-javascript Initialize the SDK using only the SDK key. The datafile will be automatically downloaded. ```javascript const optimizely = optimizelySdk.createInstance({ sdkKey: "YOUR_SDK_KEY" }); ``` -------------------------------- ### Configure Python Flask Webhook Endpoint Source: https://docs.developers.optimizely.com/feature-experimentation/docs/configure-webhooks Example of a simple Python Flask server endpoint to receive POST requests from Optimizely webhooks. Ensure you have Flask installed (`pip install flask`). ```python # Simple Python Flask webhook example # Requires installing flask: 'pip install flask' import os from flask import Flask, request, abort app = Flask(__name__) # Route to accept webhook notifications from Optimizely @app.route('/webhooks/optimizely', methods=['POST']) def index(): print(""" [Optimizely] Webhook request received! The Optimizely datafile has been updated. Re-download the datafile and re-instantiate the Optimizely SDK for the changes to take effect """) return 'Webhook Received' @app.route('/') def hello_world(): return 'Optimizely Webhook Example' if __name__ == "__main__": host = os.getenv('HOST', '0.0.0.0') port = int(os.getenv('PORT', 3000)) print('Example App Running on http://' + str(host) + ':' + str(port)) app.run(host=host, port=port) ``` -------------------------------- ### Initialize Optimizely Client and Run Experiment Source: https://docs.developers.optimizely.com/feature-experimentation/docs/go-quickstart This snippet shows how to initialize the Optimizely client with your SDK key and run a basic experiment. It includes setting the log level and handling potential client initialization errors. Ensure you replace '' with your actual SDK key. ```go // Package main // package main import ( "fmt" "math/rand" "strings" "time" optly "github.com/optimizely/go-sdk/v2" "github.com/optimizely/go-sdk/v2/pkg/client" "github.com/optimizely/go-sdk/v2/pkg/logging" ) func main() { logging.SetLogLevel(logging.LogLevelError) // For more instantiation configuration, see the Go SDK reference optimizelyClient, err := optly.Client("") if err != nil { fmt.Println("Optimizely client invalid. Verify in Settings>Environments that you used the primary environment's SDK key") return } // -------------------------------- // OPTIONAL: Add a notification listener so you can integrate with third-party analytics platforms // -------------------------------- // onDecision := func(notif notification.DecisionNotification) { // // Access type on decisionObject to get type of decision // // if notif.Type == notification.Flag { // // if serializedJsonInfo, err := json.Marshal(notif.DecisionInfo); err == nil { // // fmt.Printf("\n Feature flag access related information: %s", string(serializedJsonInfo)) // // // Send data to analytics provider here // // } // // } // } // notificationID, err := optimizelyClient.DecisionService.OnDecision(onDecision) runExperiment(optimizelyClient) } func runExperiment(client *client.OptimizelyClient) { flagsStatus := "off" rand.Seed(time.Now().UnixNano()) for i := 0; i < 5; i++ { // to get rapid demo results, generate random users. Each user always sees the same variation unless you reconfigure the flag rule. userID := fmt.Sprintf("%v", rand.Intn(8999)+1000) // Create hardcoded user & bucket user into a flag variation user := client.CreateUserContext(userID, nil) // "product_sort" corresponds to a flag key in your Optimizely project decision := user.Decide("product_sort", nil) // did decision fail with a critical error? if decision.VariationKey == "" { fmt.Printf("\ndecision error: %q", decision.Reasons) } // get a dynamic configuration variable // "sort_method" corresponds to a variable key in your Optimizely project sortMethod := decision.Variables.ToMap()["sort_method"] if decision.Enabled { flagsStatus = "on" } // Mock what the user sees with print statements (in production, use flag variables to implement feature configuration) // always returns false until you enable a flag rule in your Optimizely project fmt.Printf("\n\nFlag %s. User number %v saw flag variation: %s and got products sorted by: %v config variable as part of flag rule: %s", flagsStatus, user.GetUserID(), decision.VariationKey, sortMethod, decision.RuleKey) mockPurchase(user) } if config, err := client.ConfigManager.GetConfig(); err == nil { if flagsStatus == "off" { fmt.Printf("\n\nFlag was off for everyone. Some reasons could include:" + "\n1. Your sample size of users was too small. Rerun, or increase the iterations in the FOR loop" + "\n2. By default you have 2 keys for 2 project environments (dev/prod). Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON." + "\nCheck your key at https://app.optimizely.com/v2/projects/" + config.GetProjectID() + "/settings/implementation") } else { fmt.Println("\n\nDone with your mocked A/B test.") fmt.Printf("Check out your report at https://app.optimizely.com/v2/projects/%s/reports", config.GetProjectID()) fmt.Println("\nBe sure to select the environment that corresponds to your SDK key") } } } // mock tracking a user event so you can see some experiment reports func mockPurchase(user client.OptimizelyUserContext) { fmt.Printf("\nPretend that user %s made a purchase? y/n\n", user.UserID) var answer string fmt.Scanln(&answer) if strings.EqualFold(answer, "y") { // track a user event you defined in the Optimizely app user.TrackEvent("purchase", nil) fmt.Printf("Optimizely recorded a purchase in experiment results for user %s", user.UserID) } else { fmt.Printf("Optimizely didn't record a purchase in experiment results for user %s", user.UserID) } } ``` -------------------------------- ### Initialize Optimizely SDK and Create User Context (JavaScript) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/use-forced-bucketing Shows the basic setup for the Optimizely JavaScript SDK, including creating a project config manager and an Optimizely client instance. It then demonstrates creating a user context with attributes. ```javascript import { createPollingProjectConfigManager, createInstance, } from "@optimizely/optimizely-sdk"; const projectConfigManager = createPollingProjectConfigManager({ sdkKey: "YOUR_SDK_KEY", }); const optimizely = createInstance({ projectConfigManager, }); if (optimizely) { optimizely.onReady().then(() => { const attributes = { logged_in: true }; const user = optimizely.createUserContext('user123', attributes); if (!user) { throw new Error('failed to create user context'); } let result, decision, forcedDecision; ``` -------------------------------- ### useDecision Hook in v3 Source: https://docs.developers.optimizely.com/feature-experimentation/docs/upgrade-the-react-native-sdk-from-v3-to-v4 Example of using the useDecision hook in v3 to get feature flag decisions. ```jsx const [decision, clientReady, didTimeout] = useDecision( 'flag-key', { autoUpdate: true, timeout: 500, decideOptions: [OptimizelyDecideOption.INCLUDE_REASONS] }, { overrideUserId: 'other-user', overrideAttributes: { plan: 'gold' } } ); if (!clientReady) return ; if (decision.enabled) return ; ``` -------------------------------- ### Configure Node.js Express Webhook Endpoint Source: https://docs.developers.optimizely.com/feature-experimentation/docs/configure-webhooks Example of a simple Node.js Express server endpoint to receive POST requests from Optimizely webhooks. Ensure you have Express installed (`npm install --save express`). ```javascript // Simple Node Express webhook example // Requires installing express: 'npm install --save express' const express = require('express'); const app = express(); /** * Optimizely Webhook Route * Route to accept webhook notifications from Optimizely **/ app.post('/webhooks/optimizely', (req, res) => { console.log(` [Optimizely] Webhook request received! The Optimizely datafile has been updated. Re-download the datafile and re-instantiate the Optimizely SDK for the changes to take effect `); res.send('Webhook Received'); }); app.get('/', (req, res) => res.send('Optimizely Webhook Example')) const HOST = process.env.HOST || '0.0.0.0'; const PORT = process.env.PORT || 8080; app.listen(PORT, HOST); console.log(`Example App Running on http://${HOST}:${PORT}`); ``` -------------------------------- ### Initialize with Datafile Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-javascript Initialize the SDK using only a provided datafile. The SDK will use this datafile to start. ```javascript const optimizely = optimizelySdk.createInstance({ datafile: YOUR_DATAFILE }); ``` -------------------------------- ### Initialize OptimizelyClient (Basic) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-flutter Initialize the Optimizely client without optional parameters. This is the most basic way to get started with the SDK. ```dart // Initializing OptimizelyClient without optional parameters var flutterSDK = OptimizelyFlutterSdk(""); var response = await flutterSDK.initializeClient(); // flag decision var user = await flutterSDK.createUserContext(userId: ""); var decideResponse = await user!.decide(""); ``` -------------------------------- ### Create React App and Install SDK Source: https://docs.developers.optimizely.com/feature-experimentation/docs/react-quickstart Use Create React App to scaffold a new React project and then install the Optimizely React SDK using npm. ```shell npx create-react-app optimizely-react-quickstart cd optimizely-react-quickstart npm install @optimizely/react-sdk ``` -------------------------------- ### Full Code Example for Forced Decisions Source: https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-ruby Demonstrates setting, getting, and removing forced decisions for flags, A/B tests, and delivery rules using the Optimizely Ruby SDK. This example requires the SDK to be initialized with a valid SDK key. ```ruby require 'optimizely' require 'optimizely/optimizely_factory' optimizely = Optimizely::OptimizelyFactory.default_instance('sdk_key') user = optimizely.create_user_context('test_user', attributes) flag_context = Optimizely::OptimizelyUserContext::OptimizelyDecisionContext.new('flag-1', nil) flag_and_ab_test_context = Optimizely::OptimizelyUserContext::OptimizelyDecisionContext.new('flag-1','ab-test-1') flag_and_delivery_rule_context = Optimizely::OptimizelyUserContext::OptimizelyDecisionContext.new('flag-1','delivery-1') variation_a_forced_decision = Optimizely::OptimizelyUserContext::OptimizelyForcedDecision.new('variation-a') variation_b_forced_decision = Optimizely::OptimizelyUserContext::OptimizelyForcedDecision.new('variation-b') variation_on_forced_decision = Optimizely::OptimizelyUserContext::OptimizelyForcedDecision.new('on') # set a forced decision for a flag success = user.set_forced_decision(flag_context, variation_a_forced_decision) decision = user.decide('flag-1') # set a forced decision for an ab-test rule success = user.set_forced_decision(flag_and_ab_test_context, variation_b_forced_decision) decision = user.decide('flag-1') # set a forced variation for a delivery rule success = user.set_forced_decision(flag_and_delivery_rule_context, variation_on_forced_decision) decision = user.decide('flag-1') # get forced variations forced_decision = user.get_forced_decision(flag_context) puts "[ForcedDecision] variation_key = #{forced_decision}" # remove forced variations success = user.remove_forced_decision(flag_and_ab_test_context) success = user.remove_all_forced_decisions ``` -------------------------------- ### Run Optimizely Agent from Source (Linux/macOS) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/setup-optimizely-agent Execute this command to start the Optimizely Agent with default configuration after setup on Linux and macOS. ```Shell make run ``` -------------------------------- ### Download Starter Kit with wget Source: https://docs.developers.optimizely.com/feature-experimentation/docs/akamai-edgeworkers Downloads the Optimizely and Akamai EdgeWorkers starter kit using wget. This command fetches the main branch and extracts the contents, stripping the top-level directory. ```shell wget --no-check-certificate https://github.com/optimizely/akamai-edgeworker-starter-kit/tarball/main -O - | tar --strip-components=1 -zx ``` -------------------------------- ### Full JavaScript SDK Example with Forced Decisions Source: https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-javascript-node This comprehensive example demonstrates setting, getting, and removing forced decisions for flags and rules using the JavaScript SDK. It includes user context creation, decision making, and managing all forced decisions. ```javascript const { createInstance } = require('@optimizely/optimizely-sdk'); const optimizely = createInstance({ sdkKey: '' }); if (optimizely) { optimizely.onReady().then(({ success, reason }) => { if (!success) { throw new Error(reason); } const attributes = { logged_in: true }; const user = optimizely.createUserContext('user123', attributes); if (!user) { throw new Error('failed to create user context'); } let result, decision, forcedDecision; // set a forced decision for a flag result = user.setForcedDecision({flagKey: 'flag-1'}, {variationKey: 'off'}); decision = user.decide('flag-1'); // set a forced decision for an ab-test rule result = user.setForcedDecision({flagKey: 'flag-2', ruleKey: 'ab-test-1'}, {variationKey: 'variation-b'}); decision = user.decide('flag-2'); // set a forced variation for a delivery rule result = user.setForcedDecision({flagKey: 'flag-3', ruleKey: 'delivery-1'}, {variationKey: 'on'}); decision = user.decide('flag-3'); // get forced variations forcedDecision = user.getForcedDecision({flagKey: 'flag-2'}); // remove forced variations result = user.removeForcedDecision({flagKey: 'flag-2', ruleKey: 'ab-test-1'}); user.removeAllForcedDecisions(); user.decideAll(); }).catch((err) => { console.log(err); // handle error }); } else { // handle instantiation error } ``` -------------------------------- ### Initialize with SDK Key and Datafile Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-javascript Initialize the SDK with both an SDK key and a datafile. The SDK uses the provided datafile initially and then downloads the latest version in the background. ```javascript const optimizely = optimizelySdk.createInstance({ sdkKey: "YOUR_SDK_KEY", datafile: YOUR_DATAFILE }); ``` -------------------------------- ### v3 Client Initialization Source: https://docs.developers.optimizely.com/feature-experimentation/docs/upgrade-the-react-native-sdk-from-v3-to-v4 Example of how to create an Optimizely SDK instance in v3. ```jsx import { createInstance } from '@optimizely/react-sdk'; const optimizely = createInstance({ sdkKey: '', datafile: window.optimizelyDatafile, eventBatchSize: 10, eventFlushInterval: 2000, }); ``` -------------------------------- ### Get Boolean Variable (iOS) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/set-up-segment Example of retrieving a boolean variable from Optimizely on iOS. This is used when sending experiment data as properties on a track call. ```swift let myVariable = try? optimizely.getFeatureVariableBoolean(featureKey: "", variableKey: "", userId: "") ``` -------------------------------- ### Get Current Environment Configuration Source: https://docs.developers.optimizely.com/feature-experimentation/docs/evaluate-rest-apis Retrieve the manifest of the current working environment using the /v1/config endpoint. This example iterates through the features map in the response. ```python resp = s.get('http://localhost:8080/v1/config') env = resp.json() for key in env['featuresMap']: print(key) ``` -------------------------------- ### Initialize Datadog and Optimizely SDK (JavaScript) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/configure-datadog Sets up the Optimizely SDK and the StatsD client for Datadog. Replace 'YOUR_SDK_KEY' with your actual Optimizely SDK key. ```javascript const { createInstance, createPollingProjectConfigManager, NOTIFICATION_TYPES, } = require("@optimizely/optimizely-sdk"); const { StatsD } = require("hot-shots"); const OPTIMIZELY_SDK_KEY = 'YOUR_SDK_KEY'; const projectConfigManager = createPollingProjectConfigManager({ sdkKey: OPTIMIZELY_SDK_KEY, }) const optimizely = createInstance({ projectConfigManager, }); // Initialize hot-shots StatsD client const statsd = new StatsD({ host: "localhost", port: 8125, }); ``` -------------------------------- ### Initialize Optimizely Client with Default Event Dispatcher Source: https://docs.developers.optimizely.com/feature-experimentation/docs/configure-event-dispatcher-csharp Initialize the Optimizely client with the default event dispatcher. This is useful for basic setups or when starting with customization. ```csharp using OptimizelySDK; using OptimizelySDK.Event.Dispatcher; using OptimizelySDK.Logger; var datafile = "YOUR_JSON_DATAFILE"; var optimizely = new Optimizely( datafile: datafile, eventDispatcher: new DefaultEventDispatcher(new DefaultLogger())); ``` -------------------------------- ### Instantiate with SDK Key and Datafile Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-the-react-native-sdk Use the provided datafile immediately and then fetch and poll for updates in the background. This is useful for quick initialization with existing data. ```jsx React import { createInstance, createPollingProjectConfigManager, createBatchEventProcessor, } from '@optimizely/react-sdk'; const optimizely = createInstance({ projectConfigManager: createPollingProjectConfigManager({ sdkKey: 'YOUR_SDK_KEY', datafile: optimizelyDatafile, autoUpdate: true, }), eventProcessor: createBatchEventProcessor(), }); ``` -------------------------------- ### Full C# SDK Example for Forced Decisions Source: https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-csharp Demonstrates how to use Optimizely C# SDK methods to set, get, and remove forced decisions for flags and rules. This example covers setting decisions for a flag, an AB test rule, and a delivery rule, as well as retrieving and removing them. ```csharp var Optimizely = OptimizelyFactory.NewDefaultInstance(""); var attributes = new UserAttributes(); var user = Optimizely.CreateUserContext(RandomUserId(), attributes); var flagContext = new OptimizelyDecisionContext("flag-1", null); var flagAndABTestContext = new OptimizelyDecisionContext("flag-1", "ab-test-1"); var flagAndDeliveryRuleContext = new OptimizelyDecisionContext("flag-1", "delivery-1"); var variationAForcedDecision = new OptimizelyForcedDecision("variation-a"); var variationBForcedDecision = new OptimizelyForcedDecision("variation-b"); var variationOnForcedDecision = new OptimizelyForcedDecision("on"); // set a forced decision for a flag var success = user.SetForcedDecision(flagContext, variationAForcedDecision); var decision = user.Decide("flag-1"); // set a forced decision for an ab-test rule success = user.SetForcedDecision(flagAndABTestContext, variationBForcedDecision); decision = user.Decide("flag-1"); // set a forced variation for a delivery rule success = user.SetForcedDecision(flagAndDeliveryRuleContext, variationOnForcedDecision); decision = user.Decide("flag-1"); // get forced variations var forcedDecision = user.GetForcedDecision(flagContext); Console.WriteLine(string.Format("ForcedDecision variationKey = {0}", forcedDecision.VariationKey)); // remove forced variations success = user.RemoveForcedDecision(flagAndABTestContext); success = user.RemoveAllForcedDecisions(); ``` -------------------------------- ### Instantiate Optimizely SDK with SDK Key (NPM) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-javascript Initialize the Optimizely SDK by providing your project's SDK Key directly to the createInstance method. This is a straightforward way to set up the SDK for use. ```javascript import { createInstance } from '@optimizely/optimizely-sdk'; const optimizely = createInstance({ sdkKey: 'YOUR_SDK_KEY', // Provide the sdkKey of your desired environment here }); ``` -------------------------------- ### Get Boolean Variable (Android) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/set-up-segment Example of retrieving a boolean variable from Optimizely on Android. Pass 'false' to reduce track events if regularly accessing live variables. ```java Boolean myVariable = optimizelyClient.getVariableBoolean("myVariable", userId, false); ``` -------------------------------- ### Server-Side JavaScript Integration with Segment Source: https://docs.developers.optimizely.com/feature-experimentation/docs/set-up-segment This Node.js example demonstrates how to integrate the Optimizely SDK with Segment for tracking feature flag decisions and experiment views. Ensure you have the necessary SDKs installed. ```javascript //Node server-side example const optimizelySdk = require('@optimizely/optimizely-sdk'); const optimizelyEnums = require('@optimizely/optimizely-sdk').enums; const Analytics = require('analytics-node'); const analytics = new Analytics('YOUR_WRITE_KEY'); const optimizely = optimizelySdk.createInstance({ sdkKey: '', }); const segmentDecision = (decisionObject) => { const type = decisionObject.type //When a decision is generated by a Feature Flag, dispatch an event named Feature Flag, with properties denoting the feature key and other decision information if (type == "feature") { const info = decisionObject.decisionInfo; const featureKeyString = info.featureKey; const enabled = info.featureEnabled; const attributes = decisionObject.attributes; analytics.track('Feature Flag', { "key": featureKeyString, "enabled": enabled, info, attributes }); //If the Feature Flag decision is a result of a feature test, dispatch an additional Experiment Viewed semantic event (https://segment.com/docs/connections/spec/ab-testing/) if (info.source == "feature-test") { const experimentKeyString =info.sourceInfo.experimentKey; const experimentVarString = info.sourceInfo.variationKey; analytics.track('Experiment Viewed', { 'experiment_name': experimentKeyString, 'variation_name': experimentVarString }) } } } const listenerId = optimizely.notificationCenter.addNotificationListener( optimizelyEnums.NOTIFICATION_TYPES.DECISION, segmentDecision, ); ``` -------------------------------- ### Initialize Optimizely Client with Default Settings (C#) Source: https://docs.developers.optimizely.com/feature-experimentation/docs/event-batching-csharp This basic example shows how to initialize the Optimizely client with a given SDK key. It uses default settings for event batching. ```csharp using OptimizelySDK; public static class Program { public static void Main(string[] args) { var sdkKey = args[0]; // Returns Optimizely Client OptimizelyFactory.NewDefaultInstance(sdkKey); } } ``` -------------------------------- ### Configure Flag Variations with Variables in PHP Source: https://docs.developers.optimizely.com/feature-experimentation/docs/php-quickstart Retrieve and use flag variables to dynamically configure feature flag variations. This example shows how to get the 'sort_method' variable if the flag is enabled. ```php $enabled = $decision->getEnabled(); if ($enabled) { // "sort_method" corresponds to variable key you define in Optimizely app $sortMethod = $decision->getVariables()['sort_method']; printf("sort_method %s", $sortMethod); } ``` -------------------------------- ### Basic Decide Request with Decide Options Source: https://docs.developers.optimizely.com/feature-experimentation/docs/configure-cmab-caching-for-agent Send a POST request to the /v1/decide endpoint with specific decide options. This example includes options to get decision reasons and exclude variables. ```bash curl -X POST https://your-agent-host:8080/v1/decide \ -H "X-Optimizely-SDK-Key: YOUR_SDK_KEY" \ -H "Content-Type: application/json" \ -d '{ "userId": "user123", "decideOptions": ["INCLUDE_REASONS", "EXCLUDE_VARIABLES"], "decisionContext": { "flagKey": "my-cmab-flag" } }' ``` -------------------------------- ### Run Sample Go Application Source: https://docs.developers.optimizely.com/feature-experimentation/docs/go-quickstart Execute the Go sample application from your terminal. This command starts the application that integrates with Optimizely. ```go go run optimizely-go-quickstart.go ``` -------------------------------- ### Migrate Android API Usage: Java Examples Source: https://docs.developers.optimizely.com/feature-experimentation/docs/migrate-from-older-versions-android Demonstrates the migration of Optimizely Full Stack (Legacy) Android SDK methods to Optimizely Feature Experimentation APIs using Java. Includes examples for creating user contexts, checking feature enablement, activating experiments, retrieving feature variables, getting all enabled features, and tracking events. ```java // Prereq for new methods: create a user Map attributes = new HashMap<>(); attributes.put("is_logged_in", true); OptimizelyUserContext user = optimizelyClient.createUserContext("user123", attributes); // Is Feature Enabled // old method boolean enabled = optimizelyClient.isFeatureEnabled("flag_1", "user123", attributes); // new method OptimizelyDecision decision = user.decide("flag_1"); enabled = decision.getEnabled(); // Activate & Get Variation // old method Variation variation = optimizelyClient.activate("experiment_1", "user123", attributes); // new method String variationKey = decision.getVariationKey(); // Get All Feature Variables // old method OptimizelyJSON json = optimizelyClient.getAllFeatureVariables("flag_1", "user123", attributes); // new method json = decision.getVariables(); // Get Enabled Features // old method List enabledFlags = optimizelyClient.getEnabledFeatures("user123", attributes); // new method List options = Arrays.asList(OptimizelyDecideOption.ENABLED_FLAGS_ONLY); Map decisions = user.decideAll(options); Set enabledFlagsSet = decisions.keySet(); // Track // old method Map tags = new HashMap<>(); tags.put("purchase_count", 2); optimizelyClient.track("my_purchase_event_key", "user123", attributes, tags); // new method user.trackEvent("my_purchase_event_key", tags) ``` -------------------------------- ### Initialize with NPM Source: https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-the-javascript-sdk-v6 Instantiate the Optimizely client using an SDK key with NPM. This example shows how to configure the polling project config manager, event processor, and ODP manager. ```javascript import { createBatchEventProcessor, createInstance, createOdpManager, createPollingProjectConfigManager, } from "@optimizely/optimizely-sdk"; const SDK_KEY="YOUR_SDK_KEY"; const pollingConfigManager = createPollingProjectConfigManager({ sdkKey: SDK_KEY, autoUpdate: true, updateInterval: 60000, // 1 minute }); const batchEventProcessor = createBatchEventProcessor(); const odpManager = createOdpManager(); const optimizelyClient = createInstance({ projectConfigManager: pollingConfigManager, eventProcessor: batchEventProcessor, odpManager: odpManager, }); optimizelyClient .onReady().then(() => { console.log("Client is ready"); // Do something }).catch((err) => { console.error("Error initializing Optimizely client:", err); // Handle error }); ``` -------------------------------- ### Migrate Android API Usage: Kotlin Examples Source: https://docs.developers.optimizely.com/feature-experimentation/docs/migrate-from-older-versions-android Demonstrates the migration of Optimizely Full Stack (Legacy) Android SDK methods to Optimizely Feature Experimentation APIs using Kotlin. Includes examples for creating user contexts, checking feature enablement, activating experiments, retrieving feature variables, getting all enabled features, and tracking events. ```kotlin // Prereq for new methods: create a user val attributes: MutableMap = HashMap() attributes["is_logged_in"] = true val user = optimizelyClient.createUserContext("user123", attributes) // Is Feature Enabled // old method var enabled = optimizelyClient.isFeatureEnabled("flag_1", "user123", attributes) // new method val decision = user!!.decide("flag_1") enabled = decision.enabled // Activate & Get Variation // old method val variation = optimizelyClient.activate("experiment_1", "user123", attributes) // new method val variationKey = decision.variationKey // Get All Feature Variables // old method var json = optimizelyClient.getAllFeatureVariables("flag_1", "user123", attributes) // new method json = decision.variables // Get Enabled Features // old method val enabledFlags = optimizelyClient.getEnabledFeatures("user123", attributes) // new method val options = Arrays.asList(OptimizelyDecideOption.ENABLED_FLAGS_ONLY) val decisions = user.decideAll(options) val enabledFlagsSet: Set = decisions.keys // Track // old method val tags: MutableMap = HashMap() tags["purchase_count"] = 2 optimizelyClient.track("my_purchase_event_key", "user123", attributes, tags) // new method user.trackEvent("my_purchase_event_key", tags) ``` -------------------------------- ### Create Project Directory Source: https://docs.developers.optimizely.com/feature-experimentation/docs/python-quickstart Create a new directory for your Optimizely Python quickstart project. ```shell mkdir optimizely-python-quickstart ``` -------------------------------- ### Accessing Optimizely Client with useOptimizelyClient Source: https://docs.developers.optimizely.com/feature-experimentation/docs/useoptimizely-client-for-the-react-native-sdk Use the useOptimizelyClient hook within a component wrapped by OptimizelyProvider to get the Optimizely Client instance. This example shows how to use the client to create a user context and make a decision for a flag. ```jsx import { Text, TouchableOpacity } from 'react-native'; import { useOptimizelyClient } from '@optimizely/react-sdk'; function MyComponent() { const client = useOptimizelyClient(); const handlePress = () => { if (client) { const user = client.createUserContext('user-123', { plan: 'gold' }); const decision = user.decide('flag-key'); console.log('Decision:', decision); } }; return ( Check Flag ); } ``` -------------------------------- ### Accessing Optimizely Client with useOptimizelyClient Source: https://docs.developers.optimizely.com/feature-experimentation/docs/useoptimizely-client-for-the-react-sdk Use this hook within a component wrapped by OptimizelyProvider to get the Optimizely Client instance. This example shows how to use the client to create a user context and make a decision for a feature flag. ```jsx import { useOptimizelyClient } from '@optimizely/react-sdk'; function MyComponent() { const client = useOptimizelyClient(); const handleClick = () => { if (client) { const user = client.createUserContext('user-123', { plan: 'gold' }); const decision = user.decide('flag-key'); console.log('Decision:', decision); } }; return ; } ``` -------------------------------- ### Retrieve All Active Flag Decisions for a User Source: https://docs.developers.optimizely.com/feature-experimentation/docs/decide-methods-javascript Use `decideAll` to get decisions for all active flags for a user, useful for pre-rendering content or controlling caches. This example shows how to retrieve all decisions and access individual flag decisions. ```javascript const attributes = { logged_in: true }; const user = optimizely.createUserContext('user123', attributes); // make decisions for all active (unarchived) flags in the project for a user let decisions = user.decideAll(); // or only for enabled flags decisions = user.decideAll([OptimizelyDecideOption.ENABLED_FLAGS_ONLY]); const flagKeys = Object.keys(decisions); const decisionForFlag1 = decisions['flag_1']; ```