---
title: Node.js Feature Flags
description: Set up Datadog Feature Flags for Node.js applications.
breadcrumbs: Docs > Feature Flags > Server-Side Feature Flags > Node.js Feature Flags
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Node.js Feature Flags

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Overview{% #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](https://openfeature.dev/).

## Getting started{% #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:

```bash
npm install dd-trace@^6.24.0 @openfeature/server-sdk@~1.23.0
```

Set the application API key and flag environment before startup:

```bash
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 <YOUR_DATADOG_SITE>.

Register the provider and evaluate the flag:

```javascript
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](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#migrate-an-existing-remote-configuration-setup).

## Initialization options{% #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{% #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.

```javascript
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{% #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.

```javascript
// 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{% #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`.

{% alert level="warning" %}
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.
{% /alert %}

## Evaluate flags{% #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{% #boolean-flags %}

Use `getBooleanValue()` for flags that represent on/off or true/false conditions. Optionally set the context for specific targeting rules.

```javascript
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{% #string-flags %}

Use `getStringValue()` for flags that select between multiple variants or configuration strings. For example:

```javascript
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{% #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:

```javascript
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{% #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.

```javascript
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{% #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:

```javascript
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{% #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](https://docs.datadoghq.com/feature_flags/guide/record_exposures_in_your_own_data_store.md) for minimum SDK requirements and other details.

## Advanced configuration{% #advanced-configuration %}

Use [Server SDK Configuration Sources](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md) as the canonical reference for source selection and operational settings:

- [Configure agentless delivery](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#configure-agentless-delivery), including polling, request timeout, and endpoint settings
- [Use a custom agentless endpoint](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#use-a-custom-agentless-endpoint) for advanced testing, local development, or an operator-managed proxy
- [Use Agent delivery](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#use-agent-remote-configuration) to receive configuration through Remote Configuration
- [Start the Agent before the application](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#agent-availability) when you use Agent delivery
- [Migrate an existing Remote Configuration setup](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#migrate-an-existing-remote-configuration-setup) and remove the deprecated `DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED` setting

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`](https://docs.datadoghq.com/feature_flags/implementation_patterns/serverless.md#send-feature-flag-telemetry) as the local telemetry relay.

The `feature_flag.evaluations` metric uses the separate OTLP setup in the [Server-Side Flag Evaluation Metrics](https://docs.datadoghq.com/feature_flags/guide/server_flag_evaluation_metrics.md) guide. It requires a supported Agent or serverless telemetry receiver. For more information on available graphing, see [Feature Flag Graphs](https://docs.datadoghq.com/feature_flags/concepts/flag_graphs.md).

## Evaluation events and privacy{% #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](https://docs.datadoghq.com/feature_flags/guide/server_evaluation_events.md) for targeting-key hashing, context collection, and the Node.js bundling requirements.

## Testing{% #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.

```javascript
// 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{% #further-reading %}

Additional helpful documentation, links, and articles:

- [Server-Side Feature Flags](https://docs.datadoghq.com/feature_flags/server.md)
- [Node.js Tracing](https://docs.datadoghq.com/tracing/trace_collection/dd_libraries/nodejs.md)
- [Learn about Application Performance Monitoring (APM)](https://docs.datadoghq.com/tracing.md)
- [Set Up Server-Side Flag Evaluation Metrics](https://docs.datadoghq.com/feature_flags/guide/server_flag_evaluation_metrics.md)
- [Set Up APM Trace Enrichment for Feature Flags](https://docs.datadoghq.com/feature_flags/guide/apm_trace_enrichment.md)
- [Feature Flag Graphs](https://docs.datadoghq.com/feature_flags/concepts/flag_graphs.md)
- [Server SDK Configuration Sources](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md)
