User and context configuration
Read time: 33 minutes
Last edited: Feb 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.
A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users." To learn more, read Contexts and segments.
Creating contexts and evaluating flags based on them is supported in the latest major versions of most of our SDKs. For these SDKs, the code samples on this page include the two most recent versions.
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 list. The attribute values determine which variation of a feature flag the customer receives.
Every object is required to have a key
. Keys are always transmitted to LaunchDarkly. Typically, you supply the key when you create the context. If you are using a client-side SDK and mark the context as anonymous, the SDK can generate the key for you. To learn more, read Designating anonymous contexts.
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.
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 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
Here are the configuration options for context and user entities in client-side SDKs.
- .NET (client-side)
- Android
- C/C++ (client-side)
- Electron
- Flutter
- iOS
- JavaScript
- Node.js (client-side)
- React Native
- React Web: The React SDK relies on the JavaScript SDK for context-related functionality.
- Roku
.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"
.
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 theAllAttributesPrivate
method, which takes in a boolean parameter. Iftrue
, 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 thePrivateAttributes
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 context 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 contexts. 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.
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"
.
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 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 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"
.
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 theallAttributesPrivate
value totrue
. 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 ofprivateAttributeNames
. 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 privateLDConfigSetAllAttributesPrivate(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);
If you don't use Experimentation, 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
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"
.
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 };
If you don't use Experimentation, 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"
.
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 privateAttributeNames
method, 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().privateAttributeNames(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();
If you don't use Experimentation, 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 theallContextAttributesPrivate
attribute totrue
. - When creating the LDConfig object, you can set the
privateContextAttributes
property to a list ofReference
s, 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.
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 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.
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 privateAttributes
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'}}
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 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
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"
.
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 privateAttributes
option. You can configure this option on a per-context basis by specifying which attributes should be private in your context object.
You can configure this option in both the context object and the configuration object:
const context = {kind: 'user',key: 'user-key-123abc',name: 'Sandy Smith',email: 'sandy@example.com'_meta: {privateAttributes: ['email']}};const client = ld.initialize('client-side-id-123abc', context, {privateAttributes: ['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 };
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 user is. This way LaunchDarkly counts the initialization context key only once against your MAU, instead of every time you initialize.
React Native
Expand React Native code sample
Here is a context configuration object:
// key and kind are the only required attributeslet context = {key: 'user-key-123abc',kind: 'user',firstName: 'Sandy',lastName: 'Smith',email: 'sandy@example.com',address: {street: '123 Main St',city: 'Springfield'}};
The first attribute in the object is the key
. In the example, the value is user-key-123abc
. key and kind are the only mandatory attributes. The combination of key
and kind
should also uniquely identify each context. You can use any value such as 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.
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.
Private attributes in the React Native SDK
You can optionally configure the React Native SDK to treat attributes as private context attributes. Private attributes can be used for targeting purposes, but are removed from the context data sent back to LaunchDarkly.
You can configure this option in the configuration object, to apply to all contexts, either for all attributes or some attributes. Here's how:
const config = {mobileKey: 'mobile-key-123abc',allAttributesPrivate: true};await ldClient.configure(config, context);
To learn more, read allAttributesPrivate
and privateAttributes
on LDConfig
.
You can also mark an attribute as private for a particular context. Here's how:
const context = {kind: 'user',key: 'user-key-123abc',firstName: 'Sandy',lastName: 'Smith',email: 'sandy@example.com',address: {street: '123 Main St',city: 'Springfield'},_meta: {privateAttributes: ['email', '/address/street']}};
For attributes that are objects, you can mark specific fields private, using the /
delimiter followed by the attribute name, then the /
delimiter followed by the JSON property within the value. In the example, the attribute "address": { "street": "Main St", "city": "Springfield" }
has only the /address/street
marked as private.
Anonymous contexts in the React Native SDK
You can distinguish logged out or unregistered end users from logged-in end users in the SDK. Anonymous contexts are just like regular contexts, except that they do not appear on the Contexts list in LaunchDarkly. This prevents unauthenticated end users from diluting useful data on the Contexts list.
If you omit the context key when building an anonymous context, the SDK sets the context key to a generated UUID. If you omit the context key and do not mark the context as anonymous, the SDK gives a usage error.
If you use multi-contexts, you can choose to make only some contexts anonymous.
Here's how:
// This user context is not anonymousconst userContext = {kind: 'user',key: 'user-key-123abc'}// This device context is anonymous// The key is omitted, and the SDK will automatically generate oneconst deviceContext = {kind: 'device',deviceId: '12345',anonymous: true}// The multi-context contains one anonymous context// and one non-anonymous contextconst multiContext = {kind: 'multi',user: userContext,device: deviceContext}
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 user key only once against your MAU, instead of every time you initialize.
React Web
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.
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)
- Apex
- C/C++ (server-side)
- Erlang
- Go
- Haskell
- Java
- Lua
- Node.js (server-side)
- PHP
- Python
- Ruby
- Rust
.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
.
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 configureEvents
withAllAttributesPrivate
, which takes in a boolean parameter. Iftrue
, the SDK removes all attributes for all contexts before sending the context to LaunchDarkly, except the key. - Or, you can configure
Events
withPrivateAttributes
, 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 usesetAllAttributesPrivate(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 useLDConfigSetAllAttributesPrivate
. 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 withLDConfigAddPrivateAttribute
. 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 context:
Context = ldclient_context:set(<<"name">>, <<"Sandy Smith">>,ldclient_context:set(<<"email">>, <<"sandy@example.com">>,ldclient_context:set(<<"group">>, [<<"microsoft">>, <<"google">>],ldclient_context:new(<<"user-key">>, <<"user">>)))),
The key
property is the context's key. The key is the only mandatory context attribute. The combination of key and kind should 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, 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"
.
Anonymous contexts in the Erlang 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 anonymous contexts in the Erlang SDK:
Context = ldclient_context:set(anonymous, true,ldclient_context:new(<<"user-key-123abc">>))
You must still generate a unique key for anonymous contexts. We recommend using Session IDs or UUIDs.
Private attributes in the Erlang SDK
You can configure the Erlang SDK to treat some or all context attributes as private attributes. You can use private attributes to target contexts without sending data associated with that context back to LaunchDarkly.
When you create the Options map, use the private_attributes
key to set private context attributes. When you do this, the SDK does not send the context attributes you specify to LaunchDarkly.
The context key is not optional. You cannot set either the context key or the context kind as a private attribute.
Here's how to set context attributes as private for all contexts:
ldclient:start_instance("sdk-key-123abc", your_instance, #{private_attributes => [email]})
Here's how to set context attributes as private for a specific context:
ContextWithPrivateAttributes = ldclient_context:set_private_attributes([<<"name">>, <<"/address/street">>],ldclient_context:set(<<"name">>, <<"Global Health Services">>,ldclient_context:set(<<"email">>, <<"info@globalhealthexample.com">>,ldclient_context:set(<<"address">>, #{<<"street">> => <<"123 Main Street">>,<<"city">> => <<"Springfield">>},ldclient_context:new(<<"context-key-456def">>, <<"organization">>))))),
In the example, only the name
and /address/street
attributes are private for this context.
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 attributescontext2 := 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 key. We recommend using a hash if possible.
To learn more about the available attributes, read Context
and Builder
.
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
PrivateAttributes
to a list of attribute names. If any context has an attribute named in this list, the SDK removes it before sending the context 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 contextsconfig.Events = ldcomponents.SendEvents().AllAttributesPrivate(true)// Or, make just the email and address attributes private for all contextsconfig.Events = ldcomponents.SendEvents().PrivateAttributes("name", "email")
You can also define a set of private attributes on the context object itself. In the following 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 keycontext1 := ldcontext.NewBuilder("context-key-123abc").Anonymous(true)// Anonymous context with a key plus other attributescontext2 := 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 context:
{-# LANGUAGE OverloadedStrings #-}import LaunchDarkly.Server.Contextimport Data.Function ((&))-- Context with key and kindcontext1 :: Contextcontext1 = makeContext "context-key-123abc" "user"-- Context with a key plus other attributescontext2 :: Contextcontext2 = makeContext "context-key-456def" "organization"& withAttribute "name" "Global Health Services"& withAttribute "email" "info@globalhealthexample.com"& withAttribute "address" $ Object $ fromList [("street", "123 Main St"), ("city", "Springfield")]
The argument to makeUser
is the context's key. The key is the only mandatory attribute. The combination of the key and kind should uniquely identify each context. 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 attributes in the Haskell SDK
Optionally, you can configure the Haskell 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.
When you create the Config
object, use configSetAllAttributesPrivate
to set all context attributes as private. When you do this, all context attributes, except the key and kind, are removed before the SDK sends the context to LaunchDarkly.
Here's how:
makeConfig "sdk-key" & configSetAllAttributesPrivate True
When you create the Config
object, you can list specific private attributes with configSetPrivateAttributeNames
. If any context has attributes named in this list, the SDK removes them before sending the context to LaunchDarkly.
Here's an example:
import qualified Data.Set as Simport qualified LaunchDarkly.Server.Reference as RmakeConfig sdkKey& configSetAllAttributesPrivate True& configSetPrivateAttributeNames (S.fromList $ map R.makeLiteral ["name", "email"])
You can also define private attribute names on a per-context basis.
For example:
makeContext "key" "user"& withName "Sandy"& withAttribute "email" "sandy@example.com"& withPrivateAttributes (S.fromList $ map R.makeLiteral ["name", "email"])
Anonymous contexts 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:
makeContext "user-key-123abc" "user"& withAnonymous True
You still must generate a unique key for anonymous contexts. 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.
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 theallAttributesPrivate
method, which takes in a boolean parameter. Iftrue
, 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 theprivateAttributes
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 privateAttributes
builder method. For example:
LDContext context = LDContext.builder("context-key-123abc").set("email", "sandy@example.com").privateAttributes("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"
.
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
LDOptions
, you can setallAttributesPrivate
totrue
. 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
LDOptions
object, you can define a list ofprivateAttributes
. 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',_meta: {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"
.
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 setall_attributes_private
totrue
. 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 ofprivate_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"
.
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 setall_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 inprivate_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"
.
All context attribute keys, for both built-in and custom attributes, must be symbols and not strings.
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 setall_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 keylet context = ContextBuilder::new("context-key-123abc").build()?;// Context with a key plus other attributeslet 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
.
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 object, 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_attributes
. If any contexts has an attribute named in this list, the SDK removes it before sending the context to LaunchDarkly.
You can also define private attributes 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 keylet context = ContextBuilder::new("context-key-123abc").anonymous(true).build();// Anonymous context with a key plus other attributeslet 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.