---
title: Create user context for the JavaScript SDK v6+
slug: feature-experimentation/docs/optimizelyusercontext-for-the-javascript-sdk
docTags: 
createdAt: 2026-08-05T20:39:53.000Z
---

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 Experimentation](docId:6UBBxxRv331nBIVZ2lun8) configured, you can evaluate if your user would qualify for a [real-time audience segment](docId:7-qDl01uxXDPl5_jFVF1E).

## Minimum SDK version

v6.0.0+

For versions 5.3.5 and below, see [JavaScript (Browser) SDK](docId\:MXN8iOzOMT-fcdpbgwg8C) or [JavaScript (Node) SDK](docId:7WZjge5drvVl3_iYhV4IQ). See the [SDK compatibility matrix](docId:2shbZfPCkPAZ0mlZpL1TU) 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.

```typescript
// 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 audiences](docId\:UDBvr5a8WHNkyOqzPhOr9). 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](https://semver.org/), then define a `version`  audience condition in the Optimizely app.

:::hint{type="warning"}
**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 logs](docId\:ydbHWa-H5JsqIql3tXHPF) include warnings when this occurs.
:::

## `OptimizelyUserContext`

The following code shows the object definition for `OptimizelyUserContext`:

```typescript
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)
}
```

:::hint{type="info"}
**Note**
You must configure [Real-Time Audiences for Feature Experimentation](docId:6UBBxxRv331nBIVZ2lun8) 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 methods](docId\:SlmvozhQJ1rmI6AIIoqql).                                                           |
| `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](docId\:SlmvozhQJ1rmI6AIIoqql).                                                                                        |
| `decideAll`                | Returns decisions for all active (unarchived) flags for a user. See [Decide methods](docId\:SlmvozhQJ1rmI6AIIoqql).                                                                                                                                                                          |
| `decideAllAsync`           | Returns a promise that resolves in an object of decision results for all active flag keys. See [Decide methods](docId\:SlmvozhQJ1rmI6AIIoqql).                                                                                                                                               |
| `decideForKeys`            | Returns a map of flag decisions for specified flag keys. See [Decide methods](docId\:SlmvozhQJ1rmI6AIIoqql).                                                                                                                                                                                 |
| `decideForKeysAsync`       | Returns a promise that resolves in an object of decision results for multiple flag keys and a user context. See [Decide methods](docId\:SlmvozhQJ1rmI6AIIoqql).                                                                                                                              |
| `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](docId\:m3uU-JFwOjZgWUBjhQfn2).                                                                          |
| `setForcedDecision`        | Forces a user into a specific variation. See [Set Forced Decision](docId:_tJtaK1gdRH1Glk5esaAn).                                                                                                                                                                                             |
| `getForcedDecision`        | Returns what variation the user was forced into. See [Get Forced Decision](docId:_tJtaK1gdRH1Glk5esaAn).                                                                                                                                                                                     |
| `removeForcedDecision`     | Removes a user from a specific forced variation. See [Remove Forced Decision](docId:_tJtaK1gdRH1Glk5esaAn).                                                                                                                                                                                  |
| `removeAllForcedDecisions` | Removes a user from all forced variations. See [Remove All Forced Decisions](docId:_tJtaK1gdRH1Glk5esaAn).                                                                                                                                                                                   |
| `fetchQualifiedSegments`   | Fetch all qualified audience segments for the user context. See [fetchQualifiedSegments](https://docs.developers.optimizely.com/feature-experimentation/docs/real-time-segments-for-feature-experimentation-segment-qualification-methods-for-the-javascript-sdk-v6#fetchqualifiedsegments). |
| `isQualifiedFor`           | Check if the user is qualified for the given segment. See [isQualifiedFor](https://docs.developers.optimizely.com/feature-experimentation/docs/real-time-segments-for-feature-experimentation-segment-qualification-methods-for-the-javascript-sdk-v6#isqualifiedfor).                       |

\*\* Requires [Real-Time Audiences for Feature Experimentation](docId:6UBBxxRv331nBIVZ2lun8).

## Source files

The language and platform source files containing the implementation for the JavaScript SDK are available on [GitHub](https://github.com/optimizely/javascript-sdk/blob/master/lib/optimizely/index.ts).
