Create user context for the JavaScript SDK v6+
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 Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation configured, you can evaluate if your user would qualify for a real-time audience segmentreal-time audience segment.
Minimum SDK version
v6.0.0+
For versions 5.3.5 and below, see JavaScript (Browser) SDKJavaScript (Browser) SDK or JavaScript (Node) SDKJavaScript (Node) SDK. See the SDK compatibility matrixSDK compatibility matrix documentation for a list of current SDK releases and the features they support.
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. It will return an instance of OptimizelyUserContext or throw an error if the provided arguments are invalid.
// 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` _optional_ | string | The ID of the user. If VUID is not enabled, then `userId` must be provided, otherwise an error will be thrown. If VUID is enabled, it can be omitted when `createUserContext` is called after `onReady()` fulfils. Calling `createUserContext` without an `userId` before `onReady()` fulfils will throw an error even when VUID is enabled. |
`attributes` _optional_ | object | A map of custom key-value 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 audiencesTarget 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 forget to pass a value, then that condition is skipped. The SDK logsSDK 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 Audiences for Feature Experimentation.
// See note following this code sample.
//
// An array of segment names that the user is qualified for.
// The result of **fetchQualifiedSegments()** is saved here.
// Can be null if not properly updated with fetchQualifiedSegments().
//
// You can read and write directly to the qualified audience segments array.
// This lets you bypass the remote fetching process from ODP
// or use your own fetching service.
qualifiedSegments: string[] = [];
// Fetch all qualified segments for the user context.
//
// The segments fetched are saved in **qualifiedSegments** and can be accessed any time.
// On failure, **qualifiedSegments** is null and one of the following errors are returned:
// - OptimizelyError.invalidSegmentIdentifier
// - OptimizelyError.fetchSegmentsFailed(String)
//
// - Parameters:
// - options: (Optional) A set of options for fetching qualified segments.
// - Returns: A Promise that resolves to true if segments were fetched successfully.
fetchQualifiedSegments(options?: string[]): Promise<boolean>;
// Check if 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 Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation to access the qualifiedSegments array and fetchQualifiedSegments() and isQualifiedFor() 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](https://support.optimizely.com/hc/en-us/articles/38683417490957). 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 Audiences for Feature Experimentation](https://docs.developers.optimizely.com/feature-experimentation/docs/real-time-audiences-for-feature-experimentation). The result of the `fetchQualifiedSegments()` array is saved here. Can be null if not properly updated with `fetchQualifiedSegments()`. You can read and write directly to the qualified segments array. This lets you bypass the remote fetching process from ODP or use 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 methodsDecide 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 methodsDecide methods. |
decideAll | Returns decisions for all active (unarchived) flags for a user. See Decide methodsDecide methods. |
decideAllAsync | Returns a promise that resolves in an object of decision results for all active flag keys. See Decide methodsDecide methods. |
decideForKeys | Returns a map of flag decisions for specified flag keys. See Decide methodsDecide methods. |
decideForKeysAsync | Returns a promise that resolves in an object of decision results for multiple flag keys and a user context. See Decide methodsDecide 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 EventTrack Event. |
setForcedDecision | Forces a user into a specific variation. See Set Forced DecisionSet Forced Decision. |
getForcedDecision | Returns what variation the user was forced into. See Get Forced DecisionGet Forced Decision. |
removeForcedDecision | Removes a user from a specific forced variation. See Remove Forced DecisionRemove Forced Decision. |
removeAllForcedDecisions | Removes a user from all forced variations. See Remove All Forced DecisionsRemove All Forced Decisions. |
fetchQualifiedSegments | Fetch all qualified audience segments for the user context. See fetchQualifiedSegments. |
isQualifiedFor | Check if the user is qualified for the given segment. See isQualifiedFor. |
** Requires Real-Time Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation.
Source files
The language and platform source files containing the implementation for the JavaScript SDK are available on GitHub.