• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
    No results for ""
    EXPAND ALL

    EDIT ON GITHUB

    User and context configuration

    Read time: 32 minutes
    Last edited: Jan 27, 2023

    Overview

    This topic explains how to configure user and context objects in LaunchDarkly SDKs. These features are available for both client-side and server-side SDKs.

    Newer versions of LaunchDarkly SDKs replace users with contexts

    A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. To learn more, read Contexts.

    Creating contexts and evaluating flags based on them is supported in the latest major versions of some of our SDKs. For these SDKs, the code samples on this page include the two most recent versions.

    You can upgrade your SDKs at any time, but the ability to target by context, or review context instances that have encountered flags in your application, is only available for customers in the contexts Early Access Program (EAP). If you want access to this feature, join the EAP.

    If you are using the latest version of an SDK and are not part of the EAP, your application can send contexts to LaunchDarkly and they will appear on the Users list.

    Configuring context objects

    Every LaunchDarkly SDK lets you configure context or user objects to return specific data to LaunchDarkly. Any attributes you pass to LaunchDarkly become available on the Contexts or Users list. The attribute values determine which variation of a feature flag the customer receives.

    The object's key is the only mandatory attribute. Keys are always transmitted to LaunchDarkly.

    Keys must be a string type. Keys must be unique, deterministic, and should not contain Personally Identifiable Information (PII). Keys must be consistent, which means the same person must correspond to the same key across different services to contribute to consistent flag evaluations and accurate Monthly Active Users (MAU). You can use a primary key, an email address, or a hash, as long as the same person always has the same key. We recommend using a hash if possible.

    Using built-in and custom attributes

    Attributes other than the key are optional. There are two types of attributes: built-in attributes, which are LaunchDarkly names, and custom attributes, which you can name anything you choose.

    When you work with an SDK that supports contexts, the only built-in attributes are kind, key, name, and anonymous.

    You can define additional attributes for a context by passing in a name and value for each. These additional attributes let you add targeting rules for your flags based on any data that you want to send to LaunchDarkly. Attribute values can be any JSON type, including boolean, number, string, array, or object. To learn more, read Context attributes.

    Custom and built-in attributes cannot share names

    If you create an attribute with a name already in use by a built-in attribute, the SDK will behave unpredictably during feature flag evaluation.

    When you work with an SDK that supports contexts, the only built-in attributes are kind, key, name, and anonymous. If you work with an SDK that only supports users, there are several additional built-in attributes. For a list of built-in attributes and their names, read Built-in user attributes.

    Using private attributes

    Each SDK lets you configure private attributes. You can use private attributes for targeting purposes, but these attributes are removed from data sent back to LaunchDarkly.

    Designating anonymous contexts

    Each SDK lets you designate anonymous contexts or users. Anonymous contexts or users don't appear on your Contexts or Users list, so you can't search for them, and you can't search for or autocomplete by their keys. If you use the same key for every anonymous context or user, you also can't use Experimentation, because tracking events are attributed to the context key.

    In client-side SDKs, if you don't provide a key or set it to null, and set anonymous to true, then the SDK generates a random key for you.

    If you want to reduce your client-side MAU, we recommend using the same key for every initialization and then replacing that with the actual key when you know who the user context is. This way LaunchDarkly counts the initialization key only once against your client-side MAU, instead of every time you initialize. However, you cannot use this method if you use Experimentation, because all contexts you include in an experiment must have a unique key.

    Details about each SDK's configuration are available in the SDK-specific sections below.

    • Client-side SDKs
    • Server-side SDKs

    Client-side SDKs

    Here are the configuration options for context and user entities in client-side SDKs.

    .NET (client-side)

    Expand .NET (client-side) code sample

    In the client-side .NET SDK, you can construct a simple Context, with a context kind of "user", that only has a key by calling Context.New. Alternatively, you can use Context.Builder, which allows setting all properties.

    Here's an example:

    Context context = Context.Builder("context-key-123abc")
    .Set("firstName", "Sandy")
    .Set("lastName", "Smith")
    .Set("email", "sandy@example.com")
    .Set("group", "microsoft")
    .Build();

    The argument to Builder is the context's key. The key should uniquely identify each context. You can use a primary key, an email address, or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is "context-key-123abc".

    Interpreting attribute types

    The optional name and kind attributes, which you can set with .Name() and .Kind(), expect string values. If the kind attribute is not specified, it is assumed to be "user." Other attribute values can be an JSON type, including booleans, numbers, strings, arrays, or objects. The SDK uses the LdValue type to represent arrays and objects. The client-side .NET SDK is strongly-typed, so be aware of this distinction.

    If an attribute is an object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the client-side .NET SDK


    You can optionally configure the client-side .NET SDK to treat some or all attributes as private attributes. Private attributes can be used for targeting purposes, but are removed from the data sent back to LaunchDarkly.

    In the client-side .NET SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • When creating the LaunchDarkly Configuration object, you can call the AllAttributesPrivate method, which takes in a boolean parameter. If true, all context attributes except the kind and key for all contexts are removed before the SDK sends the context to LaunchDarkly.
    • When creating the LaunchDarkly Configuration object, you can call the PrivateAttributes method, which takes any number of attribute names or slash-delimited paths to designated a JSON property within an attribute, such as /address/street. If any context has a custom or built-in attribute that matches one of these names, the SDK removes it before sending the context to LaunchDarkly.

    You can also mark attributes as private when building the user object by calling Private() on the context builder.

    For example:

    var context = Context.Builder("context-key-123abc")
    .Set("email", "sandy@example.com")
    .Private("email")
    .Build();

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous contexts in the client-side .NET SDK


    You can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    Context context = Context.Builder("context-key-123abc")
    .Anonymous(true)
    .Build();

    You still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

    If you don't use Experimentation, we recommend using the same context key for every initialization and then replacing that with the actual context key when you know who the end user is. This way LaunchDarkly counts the initialization context key only once against your MAU, instead of every time you initialize.

    In Android or iOS, you can also set a configuration option to have the SDK to create a key for an anonymous context for you.

    Here's how:

    Configuration config = Configuration.Builder("mobile-key-123abc")
    .GenerateAnonymousKeys(true)
    .Build();

    If you set this option, the SDK will generate a key for any context whose anonymous attribute is true. You must still specify a non-null key as a placeholder when you construct the Context, because the SDK does not allow a Context to exist with a null key. When you pass this context to SDK methods like Init or Identify, the SDK replaces the placeholder key with a generated key.

    In this example, the placeholder key is "unknown-context-key", but it could be any non-empty string:

    Context context = Context.Builder("unknown-context-key")
    .Anonymous(true)
    .Build();

    Android

    Expand Android code sample

    In the Android SDK, use a builder pattern to construct contexts.

    Here's an example:

    LDContext context = LDContext.builder("context-key-123abc")
    .set("email", "sandy@example.com")
    .set("firstName", "Sandy")
    .set("lastName", "Smith")
    .set("group", "Microsoft")
    .build();

    The argument to Builder is the context's key. The key should uniquely identify each context. You can use a primary key, an email address, or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is "context-key-123abc".

    Interpreting custom attribute types

    The optional name and kind attributes, which you can set with .name() and .kind(), expect string values. If the kind attribute is not specified, it is assumed to be "user." Other attributes values can be any JSON type, including boolean, number, string, array, or object. The Android SDK is strongly-typed, so be aware of this distinction.

    If an attribute is an object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the Android SDK


    You can optionally configure the Android SDK to treat some or all attributes as private context attributes. Private attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.

    In the Android SDK you can define private attributes for the entire LaunchDarkly client. When creating the LDConfig object, call the setPrivateAttributeNames method, which which takes in a set of custom or built-in attributes as a parameter. If any context has a custom or built-in attribute named in this set, the SDK removes it before sending the context to LaunchDarkly.

    Here's how to configure private attributes:

    LDConfig ldConfig = new LDConfig.Builder()
    .events(
    Components.sendEvents()
    .privateAttributes("name", "group")
    )
    .build();

    You can also mark attributes as private when building the context object by using the private versions of the builder methods to set the attributes. For example:

    LDContext context = LDContext.builder("context-key-123abc")
    .set("email", "sandy@example.com")
    .set("name", "Sandy")
    .set("group", "Microsoft")
    .privateAttributes("name", "group")

    When the SDK sends this context back to LaunchDarkly, it removes the name and group attributes.

    Anonymous users in the Android SDK


    You can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    LDContext context = LDContext.builder("context-key-123abc")
    .anonymous(true)
    .build();

    You can leave the key parameter in the Builder null or make it an empty string. The client will automatically set it to a LaunchDarkly-specific, device-unique string that is consistent between app restarts and device reboots.

    If you don't use Experimentation, we recommend using the same context key for every initialization and then replacing that with the actual context key when you know who the end user is. This way LaunchDarkly counts the initialization context key only once against your MAU, instead of every time you initialize.

    C/C++ (client-side)

    Expand C/C++ (client-side) code sample

    In the C/C++ (client-side) SDK, you can construct a user using LDUserNew.

    Here's an example:

    struct LDJSON *attributes, *groups;
    groups = LDNewArray();
    LDArrayPush(groups, LDNewText("Google"));
    LDArrayPush(groups, LDNewText("Microsoft"));
    attributes = LDNewObject();
    LDObjectSetKey("groups", groups);
    struct LDUser *user = LDUserNew("user-key-123abc");
    LDUserSetFirstName(user, "Sandy");
    LDUserSetLastName(user, "Smith");
    LDUserSetCustomAttributesJSON(user, attributes);

    The argument to LDUserNew is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Interpreting custom attribute types

    Most of the built-in attributes, like names and email addresses, expect string values. Custom attributes values can be booleans, numbers, strings, or arrays. If you enter a custom value on the Users list that looks like a number or a boolean, the SDK interprets it that way.

    Private user attributes in the C/C++ SDK


    You can optionally configure the C/C++ SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

    In the C/C++ SDK there are two ways to define private attributes for the LaunchDarkly client:

    • When creating the LDConfig object, you can set the allAttributesPrivate value to true. When you do this, all user attributes except the key are removed before the SDK sends the user to LaunchDarkly.
    • When creating the LDConfig object, you can configure a map of privateAttributeNames. If any user has a custom or built-in attribute named in this list, the SDK removes it before sending the user to LaunchDarkly.
    struct LDConfig *config = LDConfigNew("mobile-key-123abc");
    // Mark all attributes private
    LDConfigSetAllAttributesPrivate(config, true);

    Anonymous users in the C/C++ SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    struct LDUser *user = LDUserNew("user-key-123abc");
    LDUserSetAnonymous(user, true);

    We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

    Electron

    Expand Electron code sample
    Personally-identifying user keys

    By default, when the SDK requests feature flags from LaunchDarkly, it makes an HTTP GET request with the user properties encoded in the URL. If you do not want user keys or other properties to be in request URLs, enable the useReport option in your client configuration. The SDK sends user data in the body of an HTTP REPORT request instead.

    Here's an example of a user:

    const user = {
    key: 'user-key-123abc',
    firstName: 'Sandy',
    lastName: 'Smith',
    email: 'sandy@example.com',
    custom: {
    groups: ['Google', 'Microsoft']
    }
    };

    The key property is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Interpreting custom attribute types

    Most of the built-in attributes, like names and email addresses, expect string values. Custom attribute values can be booleans, numbers, strings, or arrays. If you enter a custom value on the Users list that looks like a number or a boolean, the SDK interprets it that way.

    Private user attributes in the Electron SDK


    You can optionally configure the SDK to treat all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but the SDK removes them from the user data sent back to LaunchDarkly.

    To mark all user attributes except the key as private, you can use the allAttributesPrivate option:

    const user = {
    key: 'user-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com'
    };
    const client = LDElectron.initialize('client-side-id-123abc', user, {
    allAttributesPrivate: true
    });

    In the above example, the SDK removes the name and email attributes.

    You can also specify an array of which attributes should be private with the privateAttributeNames option. You can configure this option on a per-user basis by specifying which attributes should be private in your user object.

    This option is configured in both the user object and the configuration object:

    const user = {
    key: 'user-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com',
    privateAttributeNames: ['email']
    };
    const client = LDElectron.initialize('client-side-id-123abc', user, {
    privateAttributeNames: ['email']
    });

    In the above example, the SDK sends only the key and name back to LaunchDarkly.

    Anonymous users in the Electron SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    // To create an anonymous user with an auto-generated key, specify
    // the "anonymous" property and omit the "key" property. The LaunchDarkly
    // client creates a unique key for this user and caches it locally.
    const anonymousUser = { anonymous: true };
    // You can also specify any key you want:
    const anonymousUser2 = { key: 'user-key-123abc', anonymous: true };

    We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

    Flutter

    Expand Flutter code sample

    In the Flutter SDK, use a builder pattern to construct users.

    Here's an example:

    LDUser user = LDUserBuilder('user-key-123abc')
    .email('sandy@example.com')
    .firstName('Sandy')
    .lastName('Smith')
    .custom('group', LDValue.ofString('microsoft'))
    .build();

    The argument to LDUserBuilder is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Interpreting custom attribute types

    Most of the built-in attributes, like names and email addresses, expect string values. Custom attributes values can be booleans, numbers, strings, or arrays. Custom attribute values in the Flutter SDK use the LDValue class to support the various underlying types for the values. If you enter a custom value on the Users list that looks like a number or a boolean, the SDK interprets it that way. The Flutter SDK is strongly-typed, so be aware of this distinction.

    Private user attributes in the Flutter SDK


    Optionally, you can configure the Flutter SDK to treat some or all user attributes as private user attributes. You can use private user attributes for targeting purposes. They are removed from the user data sent back to LaunchDarkly.

    In the Flutter SDK, you can define private attributes for the entire LaunchDarkly client. When you create the LDConfig object, you can call the setPrivateAttributeNames method, which which takes in a set of custom or built-in attributes as a parameter. If any user has a custom or built-in attribute named in this set, the SDK removes it before sending the user to LaunchDarkly.

    Set<String> privateAttributes =
    { 'name' // built-in attribute
    , 'group' // custom attribute
    };
    LDConfig ldConfig = new LDConfigBuilder()
    .setPrivateAttributeNames(privateAttributes)
    .build();

    You can also mark attributes as private when building the user object by using the private versions of the builder methods to set the attributes. For example:

    LDUser user = LDUserBuilder('user-key-123abc')
    .email('sandy@example.com')
    .privateName('Jane')
    .privateCustom('group', LDValue.ofString('microsoft'))
    .build();

    When the SDK sends this user back to LaunchDarkly, the name and group attributes are removed.

    Anonymous users in the Flutter SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    LDUser user = LDUserBuilder('user key')
    .anonymous(true)
    .build();

    We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

    iOS

    Expand iOS code sample

    You can pass optional properties to the context object in iOS:

    var contextBuilder = LDContextBuilder(key: "user-key-123abc")
    contextBuilder.trySetValue("name", .string("Sandy"))
    contextBuilder.trySetValue("email", .string("sandy@example.com"))
    let context = try contextBuilder.build().get()

    This example sets a key and adds the end user's full name and email address.

    The key property should uniquely identify each context. You can define additional attributes for a context by passing in a name and value for each. Additional attributes can be any JSON type, including boolean, number, string, array, or object. If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    To learn more about the specific context properties that are available in this SDK, read LDContextBuilder.

    Private attributes in the iOS SDK


    You can optionally configure the iOS SDK to treat some or all context attributes as private attributes. Private attributes can be used for targeting purposes, but are removed from the context data the SDK sends to LaunchDarkly.

    In the iOS SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • When creating the LDConfig object, you can set the allContextAttributesPrivate attribute to true.
    • When creating the LDConfig object, you can set the privateContextAttributes property to a list of References, such as [Reference("name"), Reference("/address/state")]. If any context has a custom or built-in attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    You can also mark attributes as private on a particular LDContext instance, for example:

    var contextBuilder = LDContextBuilder(key: "context-key-123abc")
    contextBuilder.trySetValue("name", .string("Sandy"))
    contextBuilder.trySetValue("group", .array([LDValue(stringLiteral: "microsoft")]))
    contextBuilder.addPrivateAttribute(Reference("name"))
    contextBuilder.addPrivateAttribute(Reference("group"))
    let context = try contextBuilder.build().get()

    Anonymous contexts in the iOS SDK


    You can declare an LDcontext to be an anonymous, not logged-in end user:

    var contextBuilder = LDContextBuilder(key: "context-key-123abc")
    contextBuilder.anonymous(true)
    let context = contextBuilder.build().get()
    // Or have the SDK use a device persistent key. This sets `isAnonymous` by default.
    let context = try LDContextBuilder().build().get()

    You must generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    We recommend using the same context key for every initialization and then replacing that with the actual context key when you know who the context is. This way LaunchDarkly counts the initialization context key only once against your MAU, instead of every time you initialize.

    JavaScript

    Expand JavaScript code sample

    Here's an example of a context:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    firstName: 'Sandy',
    lastName: 'Smith',
    email: 'sandy@example.com',
    groups: ['Google', 'Microsoft']
    };

    The key property should uniquely identify each context. You can use a primary key, an email address, or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is user-key-123abc.

    The optional name and kind attributes expect string values. If the kind attribute is not specified, it is assumed to be "user." Other attributes can be booleans, numbers, strings, arrays, or JSON objects. If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Personally-identifying context keys

    We recommend against using personally identifiable information (PII) in context keys. If the key attribute you rely on in your context JSON does contain PII, you should enable the useReport option by sending the evaluation context as a JSON base64 URL-encoded path parameter. When you enable useReport, the SDK fetches flag settings by sending the context JSON in the body of a REPORT request instead, hiding that information from request logs.

    Private attributes in the JavaScript SDK


    You can optionally configure the JavaScript SDK to treat all attributes as private context attributes. Private attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.

    To mark all attributes except the key as private in the JavaScript SDK, you can use the allAttributesPrivate option:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com'
    };
    const ldclient = ld.initialize('client-side-id-123abc', context, options = {
    allAttributesPrivate: true
    });

    In the above example, the name and email attributes are removed.

    You can configure this option either in the context object or in the configuration object, by specifying an array of attributes that should be private. In the context object, specify your array of attributes in the privateNames field of the reserved _meta property. In the configuration object, specify your array of attributes in the privateAttributeNames configuration option.

    Here's how:

    const context = {
    kind: 'user',
    key: 'context-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com',
    _meta: {
    privateAttributes: ['email']
    }
    };
    const ldclient = ld.initialize('client-side-id-123abc', context, options = {
    privateAttributes: ['email']
    });

    In the above example, the SDK sends only the context's key and name back to LaunchDarkly.

    Anonymous contexts in the JavaScript SDK


    You can distinguish logged-in end users from anonymous end users in the SDK.

    If you use multi-contexts, you can choose to make only some contexts anonymous.

    Here's how:

    // To create an anonymous context, specify the "anonymous" property and
    // omit the "key" property. In doing so, the LaunchDarkly client
    // auto-generates a unique identifier for this context. The
    // identifier is saved in local storage and reused in future
    // browser sessions to ensure a constant experience.
    const anonymousUserContext = {
    kind: 'user',
    anonymous: true
    };
    // A multi-context can contain both anonymous and non-anonymous contexts.
    // Here, the organization is not anonymous.
    const multiContext = {
    kind: 'multi',
    user: anonymousUserContext,
    org: {
    key: 'org-key',
    name: 'Example organization name'
    }
    }

    We recommend using the same context key for every initialization and then replacing that with the actual context key when you know who the logged-in end user is. This way LaunchDarkly counts the initialization context key only once against your MAU, instead of every time you initialize.

    Node.js (client-side)

    Expand Node.js (client-side) code sample
    Personally-identifying user keys

    By default, when the SDK requests feature flags from LaunchDarkly, it makes an HTTP GET request with the user properties encoded in the URL. If you do not want user keys or other properties to be in request URLs, enable the useReport option in your client configuration. The SDK sends user data in the body of an HTTP REPORT request instead.

    Here's an example of a user:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    firstName: 'Sandy',
    lastName: 'Smith',
    email: 'sandy@example.com',
    custom: {
    groups: ['Google', 'Microsoft']
    }
    };

    The key property is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Interpreting custom attribute types

    The kind and name attributes expect string values. Other attribute values can be booleans, numbers, strings, arrays, or JSON objects.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the Node.js SDK


    You can optionally configure the SDK to treat all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

    To mark all user attributes except the key as private in the JavaScript SDK, you can use the allAttributesPrivate option:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com'
    };
    const client = ld.initialize('client-side-id-123abc', context, {
    allAttributesPrivate: true
    });

    In the above example, the name and email attributes are removed.

    You can also specify an array of which attributes should be private with the privateAttributeNames option. You can configure this option on a per-user basis by specifying which attributes should be private in your user object.

    This option is configured in both the user object and the configuration object:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    name: 'Sandy Smith',
    email: 'sandy@example.com'
    privateAttributeNames: ['email']
    };
    const client = ld.initialize('client-side-id-123abc', context, {
    privateAttributeNames: ['email']
    });

    In the above example, the SDK sends only the user's key and name back to LaunchDarkly.

    Anonymous contexts in the Node.js SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    // To create an anonymous user with an auto-generated key, specify
    // the "anonymous" property and omit the "key" property. The LaunchDarkly
    // client creates a unique key for this user and caches it locally.
    const anonymousContext = { kind: 'user', anonymous: true };
    // You can also specify any key you want:
    const anonymousContext2 = { kind: 'user', key: "user-key-123abc", anonymous: true };

    We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

    React

    All user-related functionality provided by the JavaScript SDK is also available in the React SDK.

    Unlike the JavaScript SDK, the React SDK does not require a user object for initialization. If you do not specify one, the React SDK uses an anonymous user by default.

    React Native

    Expand React Native code sample

    Here is a complete user configuration object utilizing all available fields:

    let user = {
    key: '2fbfa269b78e24c8e967f482b89c939b',
    name: 'Sandy Smith',
    firstName: 'Sandy',
    lastName: 'Smith',
    email: 'sandy@example.net',
    anonymous: false,
    privateAttributeNames: ['name'],
    country: 'USA',
    avatar: 'avatar',
    ip: '192.0.2.1',
    secondary: '',
    custom: {'groups': 'users'}
    };

    The first attribute in the object is the user's key. In this case we've used the value 2fbfa269b78e24c8e967f482b89c939b. The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use any value such as a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

    Private user attributes in the React Native SDK


    Private attributes allow you to specify keys you do not want to send to the LaunchDarkly servers. You can use private context attributes for targeting purposes, but the SDK removes private context attributes from the data it sends to LaunchDarkly. When the SDK sends this user back to LaunchDarkly, it removes the name attribute.

    Anonymous user attributes in the React Native SDK


    The anonymous key lets you distinguish logged out or unregistered users while still using LaunchDarkly. Anonymous users work just like regular users, except that they do not appear on your Users page in LaunchDarkly. This prevents unauthenticated users from diluting useful data on the Users list.

    We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

    Roku

    Expand Roku code sample

    You can create a user object with:

    user = LaunchDarklyUser("user-key-123abc")

    User objects can be customized with:

    user.setFirstName(String)
    user.setLastName(String)
    user.setEmail(String)
    user.setName(String)
    user.setAvatar(String)
    user.setCustom(AssociativeArray)

    Private user attributes in the Roku SDK


    Users can have specific fields marked as private with:

    user.addPrivateAttribute(String)

    Anonymous users in the Roku SDK


    Designate an anonymous user with:

    user.setAnonymous(Boolean)

    Server-side SDKs

    Here are the configuration options for context and user entities in server-side SDKs:

    .NET (server-side)

    Expand .NET (server-side) code sample

    In the .NET SDK, the Context class has a New method for creating a simple context, with a context kind of "user" and with only a key. It has a Builder method for building a context with other properties.

    Here's an example:

    LDContext context = Context.Builder("context-key-123abc")
    .Set("firstName", "Sandy")
    .Set("lastName", "Smith")
    .Set("email", "sandy@example.com")
    .Set("groups", LdValue.ArrayOf(LdValue.Of("Google"), LdValue.Of("Microsoft")))
    .Build();

    The argument to Builder is the context's key. The key should uniquely identify each context. You can use a primary key, an email address, or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is context-key-123abc.

    Interpreting custom attribute types

    The optional name and kind attributes, which you can set with .Name() and .Kind(), expect string values. If the kind attribute is not specified, it is assumed to be "user". Other attribute values can be booleans, numbers, strings, arrays, or JSON objects. The SDK uses the LdValue type to represent arrays and objects. The .NET SDK is strongly-typed, so be aware of this distinction.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the .NET SDK


    You can optionally configure the .NET SDK to treat some or all context attributes as private attributes. You can use private context attributes for targeting purposes, but the SDK removes private context attributes from the data it sends to LaunchDarkly.

    In the server-side .NET SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • When creating the LaunchDarkly Configuration object, you can configure Events with AllAttributesPrivate, which takes in a boolean parameter. If true, the SDK removes all attributes for all contexts before sending the context to LaunchDarkly, except the key.
    • Or, you can configure Events with PrivateAttributes, which takes any number of attribute names or slash-delimited paths to designated a JSON property within an attribute, such as /address/street. If any context has a custom or built-in attribute that matches one of these names, the SDK removes it before sending the context to LaunchDarkly.

    You can also mark attributes as private when building the context object by calling Private() after setting the attribute on the context builder.

    For example:

    var context = Context.Builder("context-key-123abc")
    .Set("email", "sandy@example.com")
    .Private("email")
    .Build();

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous contexts in the .NET SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    var context = Context.Builder("context-key-123abc")
    .Anonymous(true)
    .Build();

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    Apex

    Expand Apex code sample

    Here's an example of a user:

    LDUser user = new LDUser.Builder('user-key-123abc')
    .setFirstName('Sandy')
    .setLastName('Smith')
    .setEmail('sandy@example.com')
    .setCustom(new LDValueObject.Builder()
    .set('groups', new LDValueArray.Builder()
    .add(LDValue.of('Google'))
    .add(LDValue.of('Microsoft'))
    .build()
    )
    .build()
    )
    .build();

    The argument to Builder is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Anonymous users in the Apex SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    LDUser user = new LDUser.Builder('abc123')
    .setAnonymous(true)
    .build();

    You still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

    Private user attributes in the Apex SDK


    Optionally, you can configure the Apex SDK to treat some or all user attributes as private user attributes. You can use private user attributes for targeting, but they are redacted from the user data sent back to LaunchDarkly.

    In the Apex SDK there are two ways to define private attributes for the LaunchDarkly client:

    • When creating the LDConfig object, you can use setAllAttributesPrivate(true). When you do this, all user attributes, except the key, are redacted before the SDK sends the user to LaunchDarkly.

      Here's how:

      LDConfig config = new LDConfig.Builder()
      .setAllAttributesPrivate(true)
      .build();
    • You can also define private attribute names on a per-user basis.

      Here's how:

      Set<String> privateAttributes = new Set<String>();
      privateAttributes.add('firstName');
      LDUser user = new LDUser.Builder('user-key-123abc')
      .setFirstName('alice')
      .setPrivateAttributeNames(privateAttributes)
      .build();

    C/C++ (server-side)

    Expand C/C++ (server-side) code sample

    Here's an example of a user:

    struct LDUser *user = LDUserNew("user-key-123abc");
    LDUserSetFirstName(user, "Sandy");
    LDUserSetLastName(user, "Smith");
    LDUserSetEmail(user, "sandy@example.com");
    struct LDJSON *tmp;
    struct LDJSON *custom = LDNewObject();
    struct LDJSON *groups = LDNewArray();
    tmp = LDNewText("Google");
    LDArrayPush(groups, tmp);
    tmp = LDNewText("Microsoft");
    LDArrayPush(groups, tmp);
    LDObjectSetKey(custom, "groups", groups);
    LDUserSetCustom(user, custom);

    The argument to LDUserNew is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    LDUserFree(user);

    When you are done with an LDUser ensure that you free the structure.

    Private user attributes in the C/C++ SDK


    You can optionally configure the C/C++ SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

    In the C/C++ SDK there are three ways to define private attributes for the LaunchDarkly client:

    • When creating the LDConfig object, you can use LDConfigSetAllAttributesPrivate. When you do this, all user attributes (except the key) for the user are removed before the SDK sends the user to LaunchDarkly.

    For example:

    LDConfigSetAllAttributesPrivate(config, true);
    • When creating the LDConfig object, you can list specific private attributes with LDConfigAddPrivateAttribute. If any user has a custom or built-in attribute named in this list, the SDK removes it before sending the user to LaunchDarkly.
    LDConfigAddPrivateAttribute(config, "email");
    • You can also define private attribute names on a per-user basis. For example:
    LDUserAddPrivateAttribute(user, "email");

    Anonymous users in the C/C++ SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    LDUserSetAnonymous(user, true);

    You still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

    Erlang

    Expand Erlang code sample

    Here's an example of a user:

    Map = #{
    key => <<"user-key-123abc">>,
    secondary => <<"secondary-123abc">>,
    ip => <<"198.51.100.0">>,
    country => <<"Canada">>,
    email => <<"sandy@example.com">>,
    first_name => <<"Sandy">>,
    last_name => <<"Smith">>,
    avatar => <<"avatar-123abc">>,
    name => <<"Sandy Smith">>,
    anonymous => false,
    <<"custom-key">> => <<"custom-value">>
    },
    User = ldclient_user:new_from_map(Map)

    The key property is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Anonymous users in the Erlang SDK


    Here's how to create anonymous users in the Erlang SDK:

    Key = <<"user-key-123abc">>,
    Anonymous = true,
    Map = #{
    key => Key,
    anonymous => Anonymous,
    },
    User = ldclient_user:new_from_map(Map)

    You must still generate a unique key for anonymous users. We recommend using Session IDs or UUIDs.

    Private user attributes in the Erlang SDK


    You can configure the Erlang SDK to treat some or all user attributes as private user attributes. You can use private user attributes to target users without sending data associated with that user back to LaunchDarkly.

    When you create the Options map, use the private_attributes key to set private user attributes. When you do this, the SDK does not send the user attributes you specify to LaunchDarkly.

    The SDK always sends the user key

    The user key is not optional. You cannot set it as a private user attribute.

    Here's how to set user attributes as private:

    ldclient:start_instance("sdk-key-123abc", your_instance, #{private_attributes => [email]})

    Go

    Expand Go code sample

    The Go SDK defines a Context struct and a Builder.

    Here's an example:

    import (
    "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
    "github.com/launchdarkly/go-sdk-common/v3/ldvalue"
    )
    // Context with only a key
    // by default, the context kind is "user"
    context1 := ldcontext.New("context-key-123abc")
    // Context with a key plus other attributes
    context2 := ldcontext.NewBuilder("context-key-456def").
    Kind("organization").
    Name("Global Health Services").
    SetString("email", "info@globalhealthexample.com").
    SetValue("address", ldvalue.ObjectBuild().
    SetString("street", "123 Main Street").
    SetString("city", "Springfield")).
    Build()

    The most common attribute is the context's key. In this case we used the strings "context-key-123abc" and "context-key-456def". The key is the only mandatory context attribute. The combination of the key and kind should also uniquely identify each context. You can set the kind, or, if you do not set it, LaunchDarkly assumes that the context kind is "user". You can use a primary key, a hash, or some other value, as long as the same context always has the same context. We recommend using a hash if possible.

    To learn more about the available attributes, read Context and Builder.

    Interpreting attribute types

    The kind and name attributes expect string values. Other attributes values can be booleans, numbers, strings, arrays, or JSON objects. These types are all represented by the ldvalue.Value type. The Go SDK is strongly-typed, so be aware of this distinction.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the Go SDK


    You can optionally configure the Go SDK to treat some or all context attributes as private attributes. You can use private context attributes for targeting purposes, but the SDK removes private context attributes from the data it sends to LaunchDarkly.

    In the Go SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • You can set the configuration option AllAttributesPrivate to true. If you enable this, the SDK removes all attributes for all contexts before it sends the context to LaunchDarkly, except the key and kind.
    • You can set the configuration option PrivateAttributeNames to a list of attribute names. If any user has a custom or built-in attribute named in this list, the SDK removes it before sending the user to LaunchDarkly.

    Here's how to to define private attributes:

    import (
    ld "github.com/launchdarkly/go-server-sdk/v6"
    "github.com/launchdarkly/go-server-sdk/v6/ldcomponents"
    )
    var config ld.Config
    // Make all attributes private for all contexts
    config.Events = ldcomponents.SendEvents().AllAttributesPrivate(true)
    // Or, make just the email and address attributes private for all contexts
    config.Events = ldcomponents.SendEvents().
    PrivateAttributes("email", "address")

    You can also define a set of private attributes on the context object itself. In this example, "email" and the "street" field of the "address" attribute are private for this context, in addition to any private attributes that were specified globally:

    import (
    "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
    )
    context := ldcontext.NewBuilder("context-key-123abc").
    Kind("organization").
    Name("Global Health Services").
    SetString("email", "info@globalhealthexample.com").
    SetValue("address", ldvalue.ObjectBuild().
    SetString("street", "123 Main Street").
    SetString("city", "Springfield")).
    Private("email").
    Private("/address/street").
    Build()

    Anonymous contexts in the Go SDK


    You can distinguish anonymous contexts in the SDK. Anonymous contexts are only intended for flag evaluations and are not indexed by LaunchDarkly. Anonymous contexts do not appear on the Contexts list. However, they are not excluded from event data, so setting a context as anonymous is not the same as setting its attributes as private. To learn more, read Anonymous contexts.

    Here's how:

    import (
    "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
    )
    // Anonymous context with only a key
    context1 := ldcontext.NewBuilder("context-key-123abc").Anonymous(true)
    // Anonymous context with a key plus other attributes
    context2 := ldcontext.NewBuilder("context-key-456def").
    Anonymous(true).
    SetString("country", "Canada").
    Build()

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    Haskell

    Expand Haskell code sample

    Here's an example of a user:

    {-# LANGUAGE OverloadedStrings #-}
    import LaunchDarkly.Server.User
    import Data.Function ((&))
    user :: User
    user = (makeUser "user-key-123abc")
    & setFirstName "Sandy"
    & setLastName "Smith"
    & setEmail "sandy@example.com"

    The argument to makeUser is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Private user attributes in the Haskell SDK


    Optionally, you can configure the Haskell SDK to treat some or all user attributes as private user attributes. You can use private user attributes for targeting purposes without sending data about the user associated with them back to LaunchDarkly.

    When you create the Config object, use configSetAllAttributesPrivate to set all user attributes as private. When you do this, all user attributes (except the key) are removed before the SDK sends the user to LaunchDarkly.

    Here's how:

    config' = configSetAllAttributesPrivate True config

    When you create the Config object, you can list specific private attributes with configSetPrivateAttributeNames. If any user has a custom or built-in attribute named in this list, the SDK removes it before sending the user to LaunchDarkly.

    Here's an example:

    import Data.Set (fromList)
    config' = configSetPrivateAttributeNames (fromList ["email"]) config

    You can also define private attribute names on a per-user basis.

    For example:

    import Data.Set (fromList)
    user' = userSetPrivateAttributeNames (fromList ["email"]) user

    Anonymous users in the Haskell SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    user` = userSetAnonymous True user

    You still must generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

    Java

    Expand Java code sample

    In the Java SDK, use a builder pattern to construct contexts.

    Here's an example:

    LDContext context = LDContext.builder("context-key-123abc")
    .set("firstName", "Sandy")
    .set("lastName", "Smith")
    .set("email", "sandy@example.com")
    .set("groups",
    LDValue.buildArray().add("Google").add("Microsoft").build())
    .build();

    The argument to Builder is the context's key. The key should uniquely identify each context. You can use a primary key or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is "context-key-123abc".

    Our Javadoc for ContextBuilder shows you all the attributes that LaunchDarkly supports by default.

    Interpreting custom attribute types

    The optional name and kind attributes expect string values. If the "kind" attribute is not specified, it is assumed to be "user." Other attributes values can be booleans, numbers, strings, arrays, or objects. If you pass a value that looks like a number or a boolean, the SDK interprets it that way. The Java SDK is strongly-typed, so be aware of this distinction.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private context attributes in the Java SDK


    You can optionally configure the Java SDK to treat some or all attributes as private context attributes. Private context attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.

    In the Java SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • When creating the LDConfig object, you can call the allAttributesPrivate method, which takes in a boolean parameter. If true, all context attributes except the key for all contexts are removed before the SDK sends the context to LaunchDarkly.
    • When creating the LDConfig object, you can call the privateAttributes method, which takes in a set of custom or built-in attributes as a parameter. If any context has a custom or built-in attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    Here's how to define private attributes:

    LDConfig configWithAllAttributesPrivate = new LDConfig.Builder()
    .events(
    Components.sendEvents()
    .allAttributesPrivate(true)
    )
    .build();
    LDConfig configWithSpecificAttributesPrivate = new LDConfig.Builder()
    .events(
    Components.sendEvents()
    .privateAttributes("name", "email", "someAttribute")
    )
    .build();

    You can also mark attributes as private when building the context object by calling the private builder method. For example:

    LDContext context = LDContext.builder("context-key-123abc")
    .set("email", "sandy@example.com")
    .private("email")
    .build();

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous users in the Java SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    LDContext context = LDContext.builder("context-key-123abc")
    .anonymous(true)
    .build();

    You still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this. Each unique user key registers a user in the system, so capture and reuse your anonymous user's key between requests.

    Lua

    Expand Lua code sample

    Here's an example of a user:

    local user = ld.makeUser({
    key = "user-key-123abc",
    firstName = "Sandy",
    lastName = "Smith",
    email = "sandy@example.com",
    custom = {
    groups = { "Google", "Microsoft" }
    }
    })

    The argument to ld.makeUser is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    To learn more about configuration options, read the API docs.

    Node.js (server-side)

    Expand Node.js (server-side) code sample

    In the Node.js SDK, contexts are JSON objects.

    Here's an example:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    firstName: 'Sandy',
    lastName: 'Smith',
    email: 'sandy@example.com',
    groups: ['Google', 'Microsoft'],
    };

    The key property is the user's key. The key should uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible. In this example the hash is "user-key-123abc".

    Interpreting custom attribute types

    The optional name and kind attributes expect string values. If the kind attribute is not specified, it is assumed to be "user." Other attribute values can be booleans, numbers, strings, arrays, or JSON objects. If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the Node.js SDK


    You can optionally configure the Node.js SDK to treat some or all attributes as private attributes. You can use private attributes for targeting purposes, but they are removed from the data sent back to LaunchDarkly.

    In the Node.js SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • In the LaunchDarkly config, you can set allAttributesPrivate to true. If you enable this, the SDK removes all user attributes for all users before sending the user to LaunchDarkly, except the key.
    • In the LaunchDarkly config object, you can define a list of privateAttributes. If any user has a custom or built-in attribute named in this list, the SDK removes it before sending the user to LaunchDarkly.

    You can also define a set of privateAttributes on the context object. For example:

    const context = {
    kind: 'user',
    key: 'user-key-123abc',
    email: 'sandy@example.com',
    privateAttributes: ['email'],
    };

    When the SDK sends this user context back to LaunchDarkly, it removes the email attribute.

    Anonymous users in the Node.js SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    const context = {kind:'user', key:'user-key-123abc', anonymous: true};

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    PHP

    Expand PHP code sample

    In the PHP SDK, use a builder pattern to construct contexts.

    Here's an example:

    $context = LDContext::builder("context-key-123abc")
    ->set("firstName", "Sandy")
    ->set("lastName", "Smith")
    ->set("email", "sandy@example.com")
    ->set("groups", ["Google", "Microsoft"])
    ->build();

    The first argument to LDContextBuilder is the context's key. The key should uniquely identify each context. You can use a primary key or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example, the hash is "context-key-123abc".

    Interpreting custom attribute types

    Most of the built-in attributes, like names and email addresses, expect string values. Custom attributes values can be booleans, numbers, strings, or arrays. If you enter a custom value on the Contexts list that looks like a number or a boolean, the SDK interprets it that way. The PHP SDK is strongly-typed, so be aware of this distinction.

    Private attributes in the PHP SDK


    You can optionally configure the PHP SDK to treat some or all attributes as private attributes. Private attributes can be used for targeting purposes, but are removed from the data sent back to LaunchDarkly.

    In the PHP SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • In the LaunchDarkly config, you can set all_attributes_private to true. If you enable this, the SDK removes all attributes except the key and kind from a context before sending the context to LaunchDarkly.
    • In the LaunchDarkly config object, you can define a list of private_attribute_names. If any context has a custom or built-in attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    You can also mark attributes as private when building the context object by calling the equivalent "private" LDContextBuilder method.

    For example:

    $context = LDContext::builder('context-key-123abc')
    ->set('email', 'sandy@example.com')
    ->private('email')
    ->build();

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous contexts in the PHP SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    $context = LDContext::builder("aa0ceb")->anonymous(true)->build();

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    Python

    Expand Python code sample

    In version 8.0 and higher of the Python SDK, the Context class has a create method for creating a simple context, with a context kind of "user" and with only a key. It has a builder method for building a context with other properties.

    In the Python SDK, users are dictionaries.

    Here's an example:

    context = Context.builder("context-key-123abc") \
    .set("firstName", "Sandy") \
    .set("lastName", "Smith") \
    .set("email", "sandy@example.com") \
    .set("groups", ["Google", "Microsoft"]) \
    .build()

    The argument to Context.builder is the context's key. The key should uniquely identify each context. You can use a primary key, an email address, or a hash, as long as the same context always has the same key. We recommend using a hash if possible. In this example the hash is "context-key-123abc".

    Interpreting custom attribute types

    The optional name and kind attributes expect string values. If the "kind" attribute is not specified, it is assumed to be "user." Other attribute values can be booleans, numbers, strings, arrays, or objects.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private context attributes in the Python SDK


    You can optionally configure the Python SDK to treat some or all attributes as private context attributes. Private context attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.

    In the Python SDK there are two ways to define private attributes for the LaunchDarkly client:

    • In the LaunchDarkly config, you can set all_attributes_private to true. If you enable this, the SDK removes all context attributes for all contexts before sending the context to LaunchDarkly, except the key.
    • In the LaunchDarkly config object, you can define a list of attributes in private_attributes. If any context has a custom or built-in attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    You can also mark attributes as private when building the context object by calling the private builder method. For example:

    context = Context.builder("context-key-123abc") \
    .set("email", "sandy@example.com") \
    .private("email") \
    .build()

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous users in the Python SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    context = Context.builder("context-key-123abc").anonymous(True).build()

    You still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this. Anonymous users still count toward your plan's MAU limit, so make sure you capture and reuse your anonymous user's key between requests.

    Ruby

    Expand Ruby code sample

    In the Ruby SDK, contexts are instances of LaunchDarkly::LDContext. Legacy users can continue to be provided as simple hashes.

    Here's an example:

    context = LaunchDarkly::LDContext.create({
    key: "user-key-123abc",
    kind: "user",
    firstName: "Sandy",
    lastName: "Smith",
    email: "sandy@example.com",
    groups: ["Google", "Microsoft"]
    }

    The key property is the context's key. The key should uniquely identify each context. You can use a primary key, an email address, or a hash string, as long as the same context always has the same key. We recommend using a hash string if possible. In this example the hash string is "user-key-123abc".

    Context attribute keys must be symbols

    All context attribute keys, for both built-in and custom attributes, must be symbols and not strings.

    Interpreting custom attribute types

    The optional name and kind attributes expect string values. If the "kind" attribute is not specified, it is assumed to be "user" and the hash is assumed to be in the legacy user format. Other attribute values can be booleans, numbers, strings, arrays, or objects. If you enter a custom value on the Contexts list that looks like a number or a boolean, the SDK interprets it that way.

    If an attribute is a JSON object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private context attributes in the Ruby SDK


    You can optionally configure the Ruby SDK to treat some or all context attributes as private context attributes. Private context attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.

    In the Ruby SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • In the LaunchDarkly config, you can set all_attributes_private to true. If you enable this, the SDK removes all context attributes for all contexts before sending the context to LaunchDarkly, except the key.
    • In the LaunchDarkly config object, you can define a list of private_attributes. If any context has a custom or built-in attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    You can also define a set of privateAttributes on the context object. For example:

    context = LaunchDarkly::LDContext.create({
    key: "user-key-123abc",
    kind: "user",
    firstName: "Sandy",
    lastName: "Smith",
    email: "sandy@example.com",
    groups: ["Google", "Microsoft"],
    _meta: {
    privateAttributes: ['email']
    }
    })

    When the SDK sends this context back to LaunchDarkly, it removes the email attribute.

    Anonymous contexts in the Ruby SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    context = { key: "context-key-123abc", anonymous: true }

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.

    Rust

    Expand Rust code sample

    The Rust SDK defines a Context struct and a ContextBuilder.

    Here's an example:

    // Context with only a key
    let context = ContextBuilder::new("context-key-123abc").build()?;
    // Context with a key plus other attributes
    let custom = hashmap! {
    "groups".into() => vec!["Google", "Microsoft"].into(),
    };
    let context = ContextBuilder::new("context-key-123abc")
    .set_value("first_name", "Sandy".into())
    .set_value("last_name", "Smith".into())
    .set_value("email", "sandy@example.com".into())
    .set_value("Google", "groups".into())
    .set_value("Microsoft", "groups".into())
    .build();

    The most common attribute is the context's key. In the example, the string "context-key-123abc" is the context key. The context key is the only mandatory context attribute. The combination of the key and kind should also uniquely identify each context. You can set the kind, or, if you do not set it, LaunchDarkly assumes that the context kind is "user". You can use a primary key, a hash string, or some other value, as long as the same context always has the same key. We recommend using a hash string if possible.

    To learn more about the available attributes, read Context and ContextBuilder.

    Interpreting custom attribute types

    The optional name and kind attributes, which you can set with .name() and .kind(), expect string values. Other attributes values can be any JSON type, including booleans, numbers, strings, arrays, or objects. These types are all represented by the AttributeValue type. The Rust SDK is strongly-typed, so be aware of this distinction.

    If an attribute is an object, then in your flag or segment targeting, you can use / as a delimiter to refer to specific object fields. For example, if you have an "address" attribute that includes several fields, then you could use /address/city in your targeting. To learn more, read Targeting with flags.

    Private attributes in the Rust SDK


    You can optionally configure the Rust SDK to treat some or all attributes as Private attributes. You can use private attributes for targeting purposes, but the SDK removes them from the user data it sends back to LaunchDarkly.

    In the Rust SDK there are two ways to define private attributes for the entire LaunchDarkly client:

    • In the LaunchDarkly config, you can set all_attributes_private to true. If you enable this, the SDK removes all attributes for all contexts before sending the context to LaunchDarkly, except the key and kind.
    • In the LaunchDarkly config object, you can define a list of private_attribute_names. If any contexts has an attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.

    You can also define a set of privateAttributeNames on the context object. For example:

    let context = ContextBuilder::new("context-key-123abc")
    .set_value("email", "youremail@example.com".into())
    .add_private_attribute(Reference::new("email"))
    .build()?;

    When the SDK sends this user back to LaunchDarkly, it removes the email attribute.

    Anonymous contexts in the Rust SDK


    If your application has both anonymous and logged-in states, you can distinguish logged-in end users from anonymous end users in the SDK.

    Here's how:

    // Anonymous context with only a key
    let context = ContextBuilder::new("context-key-123abc").anonymous(true).build();
    // Anonymous context with a key plus other attributes
    let context = ContextBuilder::new("context-key-123abc").
    anonymous(true).
    set_value("country", "US".into()).
    build();

    You still need to generate a unique key for anonymous contexts. Session IDs or UUIDs work best for this.