This product is not supported for your selected
Datadog site. (
).
Overview
The Datadog Node.js SDK receives flag configuration directly from Datadog by default and evaluates flags locally. No Datadog Agent is required. The provider implements OpenFeature.
Getting started
Use Node.js 22 or later and dd-trace 6.24.0 or later. Create a Boolean flag named my-flag. Enable its Server distribution channel and enable the flag in the target environment.
Install the SDKs:
npm install dd-trace@^6.24.0 @openfeature/server-sdk@~1.23.0
Set the application API key and flag environment before startup:
export DD_API_KEY='<DATADOG_API_KEY>'
export DD_ENV='<YOUR_ENVIRONMENT>'
If your organization uses a site other than datadoghq.com, set DD_SITE. For the selected site, use .
Register the provider and evaluate the flag:
import tracer from 'dd-trace';
import { OpenFeature } from '@openfeature/server-sdk';
tracer.init();
await OpenFeature.setProviderAndWait(tracer.openfeature);
const enabled = await OpenFeature.getClient().getBooleanValue(
'my-flag', false, { targetingKey: 'user-123' }
);
console.log(enabled);
Run this example as an ES module, such as app.mjs. In CommonJS, put the initialization code in an async function.
Accessing tracer.openfeature starts configuration polling. No Feature Flags enablement or source setting is required for a new setup. For an existing Agent setup, follow Migrate an existing Remote Configuration setup.
Initialization options
setProviderAndWait waits for initial configuration. If initialization fails, handle the error or let application startup fail. Evaluations return caller-provided defaults until configuration arrives.
Accepting default values before initialization
When responsiveness during startup matters more than serving real values for the first few requests, you can call setProvider without waiting for initialization. setProvider is synchronous, so the client returns default values until the selected configuration source loads in the background.
OpenFeature.setProvider(tracer.openfeature);
const client = OpenFeature.getClient();
app.get('/my-endpoint', async (req, res) => {
const flagKey = 'my-flag';
const defaultValue = false;
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown', // targetingKey is required context
companyID: req.session?.companyID
};
// Note: evaluations are synchronous, but return a Promise type
// to follow the OpenFeature provider specifications
const value = await client.getBooleanValue(flagKey, defaultValue, evaluationContext);
if (value) {
res.send('feature enabled!');
} else {
res.send('feature disabled!');
}
});
Waiting for provider initialization
When you want the server to start listening immediately while still evaluating against real configuration data, you can defer the wait to request time. Store the initialization promise, then await it in each request handler before evaluating flags. Requests that arrive before initialization completes wait for it to finish.
// Attach the catch once, at creation. This logs a failed initialization a
// single time and keeps the shared promise from rejecting on every request;
// evaluations return default values until the provider receives its first
// configuration.
const initializationPromise = OpenFeature.setProviderAndWait(tracer.openfeature)
.catch((err) => {
console.error('Datadog feature flag provider failed to initialize', err);
});
const client = OpenFeature.getClient();
app.get('/my-endpoint', async (req, res) => {
const flagKey = 'my-flag';
const defaultValue = false;
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown', // targetingKey is required context
companyID: req.session?.companyID
};
// Wait for initialization if necessary. The promise is already handled
// above, so awaiting it here never throws, even if initialization failed.
await initializationPromise;
// Note: evaluations are synchronous, but return a Promise type
// to follow the OpenFeature provider specifications
const value = await client.getBooleanValue(flagKey, defaultValue, evaluationContext);
if (value) {
res.send('feature enabled!');
} else {
res.send('feature disabled!');
}
});
Set the evaluation context
Use an evaluation context to identify the user or entity for flag targeting. Pass the context to a client method, or set a shared context with OpenFeature.setContext.
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.
Evaluate flags
After creating the OpenFeature client in Getting started, evaluate flags throughout the application. Flag evaluation uses locally cached data, so no network requests occur when evaluating flags.
Each flag is identified by a key (a unique string) and can be evaluated with a typed getter that returns a value of the expected type. If the flag doesn’t exist or cannot be evaluated, the SDK returns the provided default value.
Boolean flags
Use getBooleanValue() for flags that represent on/off or true/false conditions. Optionally set the context for specific targeting rules.
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown',
companyID: req.session?.companyID
};
const isNewCheckoutEnabled = await client.getBooleanValue(
'new-checkout-flow', // flag key
false, // default value
evaluationContext, // context
);
if (isNewCheckoutEnabled) {
showNewCheckoutFlow();
} else {
showLegacyCheckout();
}
String flags
Use getStringValue() for flags that select between multiple variants or configuration strings. For example:
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown',
companyID: req.session?.companyID
};
const searchAlgorithm = await client.getStringValue(
'search-algorithm', // flag key
'basic', // default value
evaluationContext,
);
switch (searchAlgorithm) {
case 'basic':
return basicSearch(query);
case 'fuzzy':
return fuzzySearch(query);
case 'semantic':
return semanticSearch(query);
default:
return basicSearch(query);
}
Number flags
For number flags, use getNumberValue(). This is appropriate when a feature depends on a numeric parameter such as a limit, percentage, or multiplier:
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown',
companyID: req.session?.companyID,
};
const maxItems = await client.getNumberValue(
'max-cart-items', // flag key
20, // default value
evaluationContext,
);
const priceMultiplier = await client.getNumberValue(
'pricing-multiplier', // flag key
1.3, // default value
evaluationContext,
);
Object flags
For structured JSON data, use getObjectValue(). This method returns an object, which can represent primitives, arrays, or dictionaries. Object flags are useful when multiple properties need to be provided together.
const defaultConfig = {
color: '#00A3FF',
fontSize: 14,
};
const evaluationContext = {
targetingKey: req.session?.userID ?? 'unknown',
companyID: req.session?.companyID,
};
const config = await client.getObjectValue('ui-config', defaultConfig, evaluationContext);
Flag evaluation details
When you need more than just the flag value, use the get<Type>Details functions. These methods return both the evaluated value and metadata explaining the evaluation:
getBooleanDetails() -> Promise<EvaluationDetails<boolean>>getStringDetails() -> Promise<EvaluationDetails<string>>getNumberDetails() -> Promise<EvaluationDetails<number>>getObjectDetails() -> Promise<EvaluationDetails<JsonValue>>
For example:
const details = await client.getStringDetails('paywall-layout', 'control', evaluationContext);
console.log(details.value); // Evaluated value (for example: "A", "B", or "control")
console.log(details.variant); // Variant name, if applicable
console.log(details.reason); // Description of why this value was chosen (for example: "TARGETING_MATCH")
console.log(details.errorCode); // The error that occurred during evaluation, if any
console.log(details.errorMessage); // A more detailed message of the error that occurred, if any
console.log(details.flagMetadata); // Additional information about the evaluation
Record exposures in your own data store
Use ExposureHook from dd-trace/openfeature/exposure-hook 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 DD_FEATURE_FLAGS_EXPOSURES_DATADOG_LOGGING_ENABLED=false. See Record Feature Flag Exposures in Your Own Data Store for minimum SDK requirements and other details.
Advanced configuration
Use Server SDK Configuration Sources as the canonical reference for source selection and operational settings:
With agentless delivery, Node.js uses a compatible local telemetry relay when available. It sends experiment exposure events directly when no compatible relay is available. For no-Agent serverless environments, you can use serverless-init as the local telemetry relay.
The feature_flag.evaluations metric uses the separate OTLP setup in the Server-Side Flag Evaluation Metrics guide. It requires a supported Agent or serverless telemetry receiver. For more information on available graphing, see Feature Flag Graphs.
Evaluation events and privacy
In dd-trace 6.20.0 or later on 6.x, the provider sends aggregated flag evaluation events by default. On 5.x, use version 5.131.0 or later. In agentless mode, it uses a local relay or direct fallback. Set DD_FLAGGING_EVALUATION_COUNTS_ENABLED=false to disable only these events. See Server-Side Evaluation Events and Privacy for targeting-key hashing, context collection, and the Node.js bundling requirements.
Testing
You can test against a dedicated Datadog test environment with the real tracer.openfeature provider, or swap it for OpenFeature’s TypedInMemoryProvider to control flag values directly in test code. This section shows the in-memory approach, which keeps tests hermetic and offline. TypedInMemoryProvider ships with @openfeature/server-sdk, so no additional dependency is required.
When using the in-memory provider, do not call tracer.init() or set tracer.openfeature as the provider — that is the behavior being replaced.
The OpenFeature API is a singleton per Node.js process. Reset it in afterAll with OpenFeature.close() or OpenFeature.clearProviders() to prevent state from one test file leaking into the next.
// flags.test.js
import { beforeAll, beforeEach, afterAll, expect, test } from 'vitest';
import { OpenFeature, TypedInMemoryProvider } from '@openfeature/server-sdk';
const flags = {
'new-checkout-flow': {
variants: { on: true, off: false },
defaultVariant: 'off',
disabled: false,
contextEvaluator: (ctx) => (ctx.companyID === 'beta-co' ? 'on' : 'off'),
},
};
let provider;
beforeAll(async () => {
provider = new TypedInMemoryProvider(flags);
await OpenFeature.setProviderAndWait(provider);
});
beforeEach(() => {
// Reset flag state between tests to prevent cross-test pollution.
provider.putConfiguration(flags);
});
afterAll(async () => {
await OpenFeature.close();
});
test('beta company sees new checkout', async () => {
const client = OpenFeature.getClient();
const value = await client.getBooleanValue('new-checkout-flow', false, {
targetingKey: 'user-1',
companyID: 'beta-co',
});
expect(value).toBe(true);
});
test('non-beta company falls back to default', async () => {
const client = OpenFeature.getClient();
const details = await client.getBooleanDetails('new-checkout-flow', false, {
targetingKey: 'user-2',
companyID: 'acme',
});
expect(details.value).toBe(false);
expect(details.variant).toBe('off');
});
The snippet above uses Vitest for its first-class ESM support. The same pattern works with Jest; Jest users may need --experimental-vm-modules if their project is ESM. The non-generic InMemoryProvider export is deprecated — prefer TypedInMemoryProvider.
Further reading
Additional helpful documentation, links, and articles: