Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev guideRecipesAPI Reference
Dev guideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Create a user context using the JavaScript (Node) SDK

Describes the create user context method for the JavaScript (Node) SDK, which creates a user context for flag decisions and events in Optimizely Feature Experimentation.

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 don't have to specify the user each time you make a flag decision or track an event. You can define multiple user contexts.

Version

SDK v4.5 and higher

Description

This call creates a user context for flag decisions and events. You can call this method successfully on the Optimizely client instance, even when the instance is not fully configured yet.

Parameters

The following table lists the required and optional parameters:

ParameterTypeDescription
userId
required
stringThe ID of the user.
attributes
optional
mapA 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're 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, note that if you don't 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 will include warnings when this occurs.

Returns

Returns an OptimizelyUserContext object. For details, see OptimizelyUserContext.

Example

// 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);

See Also

OptimizelyUserContext

Source files

The language and platform source files containing the implementation for the JavaScript (Node) SDK are available on GitHub.