Example usage of the JavaScript (Node) SDK
A code example of how to use the Optimizely Feature Experimentation JavaScript (Node) SDK to evaluate feature flags, activate A/B tests, or feature tests.
Once you have installed the JavaScript (Node) SDK, import the Optimizely Feature Experimentation library into your code, get your project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.
This example demonstrates the basic usage of each of these concepts:
-
Evaluate a flag with the key
product_sort
using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely Feature Experimentation to record that the current user has been exposed to the experiment. -
Conditionally execute your feature code. You have a couple of options:
- Fetch the flag enabled state, then check a configuration variable on the flag called
sort_method
. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method variable they should see. - Fetch on the flag variation, then run 'control' or 'treatment' code.
- Use event tracking to track an event called
purchased
. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely Feature Experimentation through the customizable event dispatcher so Optimizely can count it in your results page.
const { createInstance } = require('@optimizely/optimizely-sdk');
const optimizely = createInstance({
sdkKey: '<YOUR_SDK_KEY>' // Provide the sdkKey of your desired environment here
});
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');
}
const decision = user.decide('product_sort');
const variationKey = decision['variationKey'];
if (variationKey === null) {
console.log(' decision error: ', decision['reasons']);
}
const enabled = decision['enabled'];
if (enabled) {
const sortMethod = decision.variables['sort_method'];
// execute code for sort method value
}
if (variationKey === 'control') {
// Execute code for control constiation
} else if (variationKey === 'treatment') {
// Execute code for treatment constiation
}
// Track an event
user.trackEvent('purchased');
}).catch((err) => {
// handle error
});
} else {
// there was an error creating the instance, handle error
};
Updated 10 months ago