This product is not supported for your selected Datadog site. ().
Overview
This page describes how to instrument your browser JavaScript application with the Datadog Feature Flags SDK. Datadog feature flags provide a unified way to remotely control feature availability in your app, experiment safely, and deliver new experiences with confidence.
The Datadog Feature Flags SDK for JavaScript is built on OpenFeature, an open standard for feature flag management. This guide explains how to install the SDK, configure the Datadog provider, and evaluate flags in your application.
Installation
Install the Datadog OpenFeature provider and the OpenFeature Web SDK using your preferred package manager:
Use DatadogProvider for most applications. It fetches precomputed assignments, retrieves updated assignments when the evaluation context changes, and manages built-in telemetry. The setup and examples on this page use this provider.
DatadogCoreProvider is an advanced, OpenFeature-compatible alternative for application-controlled configuration delivery and refreshes. It also supports local rules evaluation across context changes without fetching new assignments. It does not fetch configuration or install tracking hooks. See Advanced: application-managed configuration.
DatadogProvider supports custom Fetch behavior and initial precomputed fallback data; these use cases alone do not require the advanced provider.
Initialize the provider
Create a DatadogProvider instance with your Datadog credentials. For live Browser Feature Flags configuration, applicationId, clientToken, site, and env are required. To create a client token, see Client tokens.
Browser Feature Flags are not supported for the selected Datadog site ().
import{DatadogProvider,withTimeout}from'@datadog/openfeature-browser';import{OpenFeature}from'@openfeature/web-sdk';constprovider=newDatadogProvider({// Required
// applicationId is a unique identifier to distinguish multiple frontend applications.
// This should match the app ID you provide to your RUM SDK.
applicationId:'<APPLICATION_ID>',// Required
clientToken:'<CLIENT_TOKEN>',site:'',env:'<ENV_NAME>',flagConfigurationFetch:withTimeout(globalThis.fetch,5_000),});
Set the evaluation context
Define who or what the flag evaluation applies to using an evaluation context. The evaluation context includes user or session information used to determine which flag variations should be returned. Reference these attributes in your targeting rules to control who sees each variant.
Datadog Feature Flags requires evaluation context attributes to be flat primitive values: strings, numbers, and Booleans. Do not pass nested objects or arrays; they are not supported and can cause exposure data to be dropped.
The targetingKey is used as the randomization subject for percentage-based targeting. When a flag targets a percentage of subjects (for example, 50%), the targetingKey determines which "bucket" a user falls into. Users with the same targetingKey always receive the same variant for a given flag.
Most applications run several asynchronous tasks at startup, such as fetching data from another service or loading configuration. This example shows only feature flag initialization. As a best practice, start all of your startup promises together and await them as a group (for example, with Promise.all) right before the results are needed, rather than awaiting each one sequentially. This keeps total startup time close to the slowest task instead of the sum of all of them.
Evaluate flags
After the provider is initialized, you can evaluate flags anywhere in your application. Flag evaluation is local and instantaneous—the SDK uses locally cached data, so no network requests occur when evaluating flags.
Get a client
Retrieve the OpenFeature client to evaluate flags:
constclient=OpenFeature.getClient();
Boolean flags
Use getBooleanValue(key, defaultValue) for flags that represent on/off or true/false conditions:
When you need more than just the flag value, use the detail methods. These return both the evaluated value and metadata explaining the evaluation:
constdetails=client.getBooleanDetails('checkout_new',false);console.log(details.value);// Evaluated value (true or false)
console.log(details.variant);// Variant name, if applicable
console.log(details.reason);// Why this value was chosen
console.log(details.errorCode);// Error code, if evaluation failed
Complete example
Here’s a complete example showing how to set up and use Datadog Feature Flags in a JavaScript application:
import{DatadogProvider,withTimeout}from'@datadog/openfeature-browser';import{OpenFeature}from'@openfeature/web-sdk';// Initialize the Datadog provider
constprovider=newDatadogProvider({applicationId:'<APPLICATION_ID>',clientToken:'<CLIENT_TOKEN>',site:'',env:'<ENV_NAME>',flagConfigurationFetch:withTimeout(globalThis.fetch,5_000),});// Set the evaluation context
constevaluationContext={targetingKey:'user-123',user_id:'123',user_role:'admin',};awaitOpenFeature.setProviderAndWait(provider,evaluationContext);// Get the client and evaluate flags
constclient=OpenFeature.getClient();constshowNewFeature=client.getBooleanValue('new_feature',false);if(showNewFeature){console.log('New feature is enabled!');}
Update the evaluation context
To update the evaluation context after initialization (for example, when a user logs in), use OpenFeature.setContext():
The web provider also supports these optional settings:
Option
Default
Use
trackExposures
true
Send exposure events to the exposures intake. Available in version 2.3.0 and later. Replaces the deprecated enableExposureLogging option. To record exposures in your own data store, see Record Feature Flag Exposures in Your Own Data Store.
enableFlagEvaluationTracking
true
Send aggregated evaluation telemetry.
enableRumFeatureFlagTracking
true
Add flag evaluations to RUM events when Browser RUM is available. Enabling this option can increase RUM-billed event counts.
Replace default request headers with customHeaders.
flagConfigurationFetch
globalThis.fetch
Provide a Fetch-compatible implementation for flag configuration requests.
flagSelection
unset
Load only the flags that match a set of tags or key patterns. See Load a subset of flags.
Supply initial precomputed fallback data
Use initialFlagsConfiguration to supply precomputed assignments, such as configuration delivered by your application at startup. In browser SDK 2.0.0, DatadogProvider still attempts a configuration fetch during initialization. If fetching fails and the supplied configuration matches the effective evaluation context, the provider uses it and reports STALE status. If the context does not match, the provider checks its persistent cache instead; without a matching fallback, initialization fails.
For a portable precomputed configuration string, parse it and restore its associated context:
import{configurationFromString,DatadogProvider,getPrecomputedContext,}from'@datadog/openfeature-browser';import{OpenFeature}from'@openfeature/web-sdk';constconfiguration=configurationFromString('<PRECOMPUTED_CONFIGURATION_WIRE>');constcontext=getPrecomputedContext(configuration);if(context===undefined){thrownewError('Expected a precomputed configuration with an evaluation context');}constprovider=newDatadogProvider({applicationId:'<APPLICATION_ID>',clientToken:'<CLIENT_TOKEN>',site:'',env:'<ENV_NAME>',initialFlagsConfiguration:configuration,});awaitOpenFeature.setProviderAndWait(provider,context);
Supply precomputed assignments generated for the same evaluation context that the provider uses. Include any RUM user attributes that the provider adds. Subsequent context changes still attempt to fetch assignments; initial data does not become a rules-based configuration.
This option does not skip the initialization request. To initialize entirely from supplied configuration, use application-managed configuration.
Set a timeout and retries for flag configuration requests
The browser provider does not add a timeout or retries by default. In npm installations of @datadog/openfeature-browser 1.4.0 and later, use withTimeout and withRetry to limit each request attempt and retry transient failures. These helpers are not available in the CDN bundle.
The flagConfigurationFetch option applies only to flag configuration requests. It does not affect exposure, aggregated flag evaluation, or RUM telemetry requests.
import{DatadogProvider,withRetry,withTimeout}from'@datadog/openfeature-browser';constprovider=newDatadogProvider({// Other provider options...
flagConfigurationFetch:withRetry(withTimeout(globalThis.fetch,5_000),1),});
withTimeout(fetch, timeoutMs)
Sets the timeout in milliseconds for each request attempt, including the complete response-body download. Set the timeout to 0 to disable the timer. Accepted values are non-negative integers up to 2_147_483_647.
withRetry(fetch, retryCount)
Sets the number of retries after the initial request. Set the retry count to 0 to disable retries. Accepted values are integers from 0 to 10. Retries cover Fetch TypeError failures, timeout errors, HTTP 408, and HTTP 5xx responses. Caller cancellation and HTTP 429 responses are not retried. Retries use randomized exponential backoff capped at 30 seconds. For HTTP 503, a valid Retry-After value up to 30 seconds is a minimum delay before the backoff. A response that requests a longer delay is not retried. Browsers report network, CORS, and CSP failures as TypeError, so the wrapper cannot separate these causes.
In the example, withTimeout is inside withRetry. Therefore, each attempt has its own five-second timeout, and 1 allows one retry after the initial request.
Load a subset of flags
In @datadog/openfeature-browser 2.2.0 and later, use flagSelection to load only the flags your application needs instead of every flag in the environment. Loading a subset reduces the size of the flag configuration that the SDK downloads and caches, which helps when an environment contains flags for many applications.
Pass flagSelection to the provider when you create it. The selection is fixed for the provider’s lifetime. To load a different set of flags, create a new provider.
flagSelection accepts two optional lists:
tags
Flag tags to match, such as app:checkout-web. A flag matches if it has any of the listed tags. Tags match exactly and are case-sensitive.
keyPatterns
Patterns to match against the whole flag key. * matches any sequence of characters, including none, anywhere in the pattern. Every other character, including ?, [, ], {, and }, matches only itself. For example, checkout-* matches checkout-banner but not new-checkout-banner, and *-checkout-* matches new-checkout-banner.
A flag loads if it matches any listed tag or any key pattern. In the following example, the SDK loads every flag tagged app:checkout-web and every flag whose key starts with checkout-:
Team tags can change when flag ownership changes, which changes the flags your application loads. Instead of selecting by team tags, add tags to your flags specifically for selection, such as app:checkout-web.
Limits and validation
Before sending the selection, the SDK trims leading and trailing whitespace from each value, removes empty values and duplicates, and sorts each list. After this processing, the selection must meet these limits:
tags contains at most 31 values.
keyPatterns contains at most 31 values.
Each tag is at most 200 bytes (UTF-8).
Each key pattern is at most 200 bytes (UTF-8).
A selection cannot include a tag longer than 200 bytes, so keep the tags you add to flags for selection at 200 bytes or less.
If both lists are empty after this processing, the SDK sends no selection and loads the full flag configuration without logging an error.
If the flag selection is malformed or exceeds a limit, the SDK does not send it in the flag configuration request, logs an error to the browser console, and loads the full flag configuration.
Because the SDK checks these limits first, selections that fail them never reach Datadog. Datadog can still ignore a selection that passes these checks, for example when the selection is too long to send in one request. In that case, Datadog returns the full flag configuration with a DD-Flag-Selection-Ignored header that gives one of the following reasons, and the SDK logs an error to the browser console:
Reason
Meaning
too_many_values
A list contains more than 31 values, or the selection is too long to send in one request.
invalid_tag
A tag is longer than 200 bytes.
invalid_key_pattern
A key pattern is longer than 200 bytes.
malformed_selection
The selection could not be parsed.
tag_load_failed
Flag tags could not be loaded for this request. The full configuration is returned so that evaluation can continue.
The SDK logs these errors to the browser console:
Message
Cause
Datadog Browser SDK: flagSelection was not sent (<REASON>: <DETAIL>). Loading the full flag configuration.
The selection is malformed or exceeds a limit.
Datadog Browser SDK: flagSelection was ignored by the server (<REASON>). Loaded the full flag configuration.
Datadog ignored the selection. See the reasons in the previous table.
If you route flag configuration requests through a proxy, see Proxy Feature Flag SDK Traffic for the header your proxy must pass through.
Evaluate flags outside the selection
Flags outside the selection are not loaded. Evaluating one of these flags returns the default value you supply, with the error code FLAG_NOT_FOUND:
constclient=OpenFeature.getClient();// 'search-ranking' has no app:checkout-web tag and does not match checkout-*
constdetails=client.getBooleanDetails('search-ranking',false);console.log(details.value);// false (the supplied default)
console.log(details.errorCode);// 'FLAG_NOT_FOUND'
Initial configuration is not filtered
flagSelection does not filter configuration that you supply with initialFlagsConfiguration. The SDK uses that configuration as provided. For details, see the Supply initial precomputed fallback data section.
Rules-based configuration
fetchRulesConfiguration() from @datadog/openfeature-browser/rules-based accepts the same flagSelection option, with the same matching rules and limits. The request URL, including the encoded selection, must be at most 8,192 bytes. If it would be longer, the SDK does not send the selection, logs a too_many_values error to the browser console, and loads the full configuration. See Browser Rules-Based Evaluation.
The SDK sends the selection as selected_flag_tags and selected_flag_key_patterns query parameters, with one parameter for each value. If you route this request through a proxy or a custom fetch implementation, forward all of these parameters unchanged. If you cache the response, include these parameters in the cache key so that requests with different selections do not share a cached response.
Record exposures in your own data store
Use ExposureHook to record exposures in your own logs, data warehouse, or analytics pipeline. It calls your code after each flag evaluation with the same exposure decision that the provider uses for Datadog. To stop sending exposures to Datadog, set trackExposures: false. This requires @datadog/openfeature-browser 2.3.0 or later. See Record Feature Flag Exposures in Your Own Data Store.
Advanced: application-managed configuration
Use DatadogCoreProvider from @datadog/openfeature-browser/rules-based in SDK 2.0.0 and later only when your application needs to own configuration delivery or evaluate rules locally across context changes. Your application supplies and refreshes configuration with setConfiguration() and explicitly registers and manages any tracking hooks.
For setup, configuration formats, and optional tracking, see Browser Rules-Based Evaluation. Keep DatadogProvider for the managed setup described on this page.
Override flags in your browser
To browse your organization’s flags and override them locally while you develop, compose the DatadogDevtools wrapper into your provider stack and use the Feature Flags tab in the Datadog Browser SDK developer extension.
Testing
You can test against a dedicated Datadog test environment with the real DatadogProvider, or swap it for OpenFeature’s InMemoryProvider to control flag values directly in test code. This section shows the in-memory approach, which keeps tests hermetic and offline. InMemoryProvider is exported directly from @openfeature/web-sdk, so no additional dependency is required.
Unlike the server-side SDK, the Web SDK evaluates flags synchronously after initialization. Still awaitsetProviderAndWait once in beforeEach to ensure the provider is ready.
import{beforeEach,afterAll,expect,test}from'vitest';import{OpenFeature,TypedInMemoryProvider}from'@openfeature/web-sdk';constflags={new_checkout_button:{variants:{on:true,off:false},defaultVariant:'on',disabled:false,},ui_theme:{variants:{dark:'dark',light:'light'},defaultVariant:'light',disabled:false,},};beforeEach(async()=>{awaitOpenFeature.setProviderAndWait(newTypedInMemoryProvider(flags));});afterAll(async()=>{awaitOpenFeature.close();});test('new checkout button is enabled by default',()=>{constclient=OpenFeature.getClient();expect(client.getBooleanValue('new_checkout_button',false)).toBe(true);});test('missing flag returns default',()=>{constclient=OpenFeature.getClient();expect(client.getBooleanValue('does-not-exist',false)).toBe(false);});
The Web SDK flag shape requires variants, defaultVariant, and disabled. Omitting any of these fails TypeScript compilation; at runtime, evaluating an unknown flag key returns the supplied default. Prefer TypedInMemoryProvider over the deprecated InMemoryProvider for type-checked flag configurations. The same test pattern works with Jest + jsdom; swap the vitest imports for @jest/globals and add jest-environment-jsdom to your project.
Further reading
Additional helpful documentation, links, and articles: