Create user context for the JavaScript SDK v6
Describes the OptimizelyUserContext object, which lets you to make flag decisions and track events for a user context for the Optimizely Feature Experimentation JavaScript (Browser) SDK.
Warning
This content covers the Feature Experimentation JavaScript (Browser) SDK v6 features currently in pre-production testing and is subject to change before release
For the latest released version, see JavaScript (Browser) SDK.
Create a user for which you can make flag decisions and track events. The user context is returned as a runtime object that is not otherwise persisted. The purpose of this method is to set a user context once, so you do not have to specify the user each time you make a flag decision or track an event. You can define multiple user contexts.
If you have Real-Time Segments for Feature Experimentation configured, you can evaluate if your user would qualify for a real-time audience segment.
Minimum SDK version
v6.0.0+
createUserContext
This call creates a user context for flag decisions and events. You can call this method on the Optimizely client instance, even when it is not fully configured yet.
// Option 1 - Create a user, then set attributes.
const user = optimizely.createUserContext('user123');
user.setAttribute('is_logged_in', false);
user.setAttribute('app_version', '1.3.2');
// Option 2 – Pass attributes when creating the user.
const attributes = {
is_logged_in: false,
app_version: '1.3.2'
}
const user = optimizely.createUserContext('user123', attributes);
The following table lists the required and optional parameters:
Parameter | Type | Description |
---|---|---|
userId required | string | The ID of the user. |
attributes optional | object | A map of custom key-value string pairs specifying attributes for the user that are used for audience targeting. See the following section for more details. |
Audience attributes
You can set custom audience attributes for the user, which you can then use to Target audiences. You can pass strings, numbers, booleans, and null as custom user attribute values. If you want to target audiences based on the version of your application that they are using, you can also pass in a string formatted as a semantic version, then define a version
audience condition in the Optimizely app.
Important
During audience evaluation, if you do not pass a valid attribute value for a given audience condition, for example, if you pass a string when the audience condition requires a Boolean, or if you simply forget to pass a value, then that condition will be skipped. The SDK logs include warnings when this occurs.
OptimizelyUserContext
The following code shows the object definition for OptimizelyUserContext
:
interface OptimizelyUserContext {
// set an attribute for the user
setAttribute(key: string, value: unknown): void;
// return user attributes
getAttributes(): UserAttributes;
// make a decision about which flag variation the user buckets into for the flag key
decide(
key: string,
options: OptimizelyDecideOption[] = []
): OptimizelyDecision;
// Same as decide except it returns a promise
decideAsync(
key: string,
options?: OptimizelyDecideOption[]
): Promise<OptimizelyDecision>;
// make decisions about which flag variations the user buckets into for flag keys
decideForKeys(
keys: string[],
options: OptimizelyDecideOption[] = [],
): { [key: string]: OptimizelyDecision };
// Same as decideForKeys except it returns a promise.
decideForKeysAsync(
keys: string[],
options?: OptimizelyDecideOption[]
): Promise<Record<string, OptimizelyDecision>>;
// make decisions about which flag variations the user buckets into for all flags
decideAll(
options: OptimizelyDecideOption[] = []
): { [key: string]: OptimizelyDecision };
// Same as decideAll except it returns promise.
decideAllAsync(
options?: OptimizelyDecideOption[]
): Promise<Record<string, OptimizelyDecision>>;
// track user event
trackEvent(eventName: string, eventTags?: EventTags): void;
// Sets the forced decision (variationKey) for a given decision context
setForcedDecision(context: OptimizelyDecisionContext, decision: OptimizelyForcedDecision): boolean;
// Returns the forced decision for a given decision context
getForcedDecision(context: OptimizelyDecisionContext): OptimizelyForcedDecision | null;
// Removes the forced decision for a given decision context
removeForcedDecision(context: OptimizelyDecisionContext): boolean;
// Removes all forced decisions bound to this user context
removeAllForcedDecisions(): boolean;
//
// The following methods require Real-Time Segments for Feature Experimentation.
// See note below code sample.
//
// An array of segment names that the user is qualified for.
// The result of **fetchQualifiedSegments()** will be saved here.
// Can be nil if not properly updated with fetchQualifiedSegments().
//
// You can read and write directly to the qualified segments array.
// This allows for bypassing the remote fetching process from ODP
// or for utilizing your own fetching service.
let qualifiedSegments = [];
// Fetch all qualified segments for the user context.
//
// The segments fetched will be saved in **qualifiedSegments** and can be accessed any time.
// On failure, **qualifiedSegments** will be nil and one of these errors will be returned:
// - OptimizelyError.invalidSegmentIdentifier
// - OptimizelyError.fetchSegmentsFailed(String)
//
// - Parameters:
// - options: A set of options for fetching qualified segments (optional).
// - completionHandler: A completion handler to be called with the fetch result.
// On success, it will pass a non-nil segments array (can be empty) with a nil error.
// On failure, it will pass a non-nil error with a nil segments array.
fetchQualifiedSegments(options = [], completionHandler)
// Check is the user qualified for the given segment.
// - Parameter segment: the segment name to check qualification for.
// - Returns: true if qualified.
isQualifiedFor(segment)
}
Note
You must configure Real-Time Segments for Feature Experimentation to access the
qualifiedSegments
array andfetchQualifiedSegments()
andisQualifiedFor()
methods.
Properties
The following table shows attributes for the OptimizelyUserContext object:
Attribute | Type | Comment |
---|---|---|
userId | String | The ID of the user |
attributes | Map | A map of custom key-value pairs specifying attributes for the user that are used for audience targeting. You can pass the map with the user ID when you create the user. |
qualifiedSegments | Array | An array of segment names that the user is qualified for. Requires Real-Time Segments for Feature Experimentation. The result of the fetchQualifiedSegments() array is saved here. Can be nil if not properly updated with fetchQualifiedSegments() . You can read and write directly to the qualified segments array. This lets you for bypass the remote fetching process from ODP or utilize your own fetching service. |
Methods
The following table shows methods for the OptimizelyUserContext object:
Method | Comment |
---|---|
setAttribute | Pass a custom user attribute as a key-value pair to the user context. |
decide | Returns a decision result for a flag key for a user. The decision result is returned in an OptimizelyDecision object, and contains all data required to deliver the flag rule. See Decide methods. |
decideAsync | Returns a promise that resolves in decision result for a given flag key and a user context, which contains all data required to deliver the flag. See Decide methods . |
decideAll | Returns decisions for all active (unarchived) flags for a user. See Decide methods. |
decideAllAsync | Returns a promise that resolves in an object of decision results for all active flag keys. See Decide methods . |
decideForKeys | Returns a map of flag decisions for specified flag keys. See Decide methods. |
decideForKeysAsync | Returns a promise that resolves in an object of decision results for multiple flag keys and a user context. See Decide methods . |
trackEvent | Tracks a conversion event (in other words, an action a user takes) for a user. Logs an error message if the specified event key doesn't match any existing events. See Track Event. |
setForcedDecision | Forces a user into a specific variation. See Set Forced Decision. |
getForcedDecision | Returns what variation the user was forced into. See Get Forced Decision. |
removeForcedDecision | Removes a user from a specific forced variation. See Remove Forced Decision. |
removeAllForcedDecisions | Removes a user from all forced variations. See Remove All Forced Decisions. |
fetchQualifiedSegments ** | Fetch all qualified segments for the user context. See fetchQualfiedSegments. |
isQualifiedFor ** | Check if the user is qualified for the given segment. See isQualifiedFor. |
** Requires Real-Time Segments for Feature Experimentation.
See also
Source files
The language and platform source files containing the implementation for the JavaScript SDK are available on GitHub.
Updated 5 days ago