Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

705 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Datadog OpenFeature JavaScript Clients

This repository hosts Browser and React Native clients, as well as the NodeJS flag evaluator, for Datadog's OpenFeature implementation.

Documentation

Please see the full documentation site: Getting Started with Feature Flags

Installation

npm install @datadog/openfeature-browser

Quick Start

The main entry point is DatadogProvider, which is a provider for the OpenFeature Web SDK.

import { DatadogProvider } from '@datadog/openfeature-browser'
import { OpenFeature } from '@openfeature/web-sdk'

// Initialize the provider
const provider = new DatadogProvider({
  applicationId: 'your-datadog-application-id',
  clientToken: 'your-datadog-client-token',
  enableExposureLogging: true,
  enableFlagEvaluationTracking: true,
  site: 'datadoghq.com',
})

// Set the provider
await OpenFeature.setProviderAndWait(provider)

// Get a client and evaluate flags
const client = OpenFeature.getClient()
const flagValue = await client.getBooleanValue('my-flag', false)

Configuration

const provider = new DatadogProvider({
  // Required
  clientToken: 'pub_...', // Your Datadog client token
  site: 'datadoghq.com', // Datadog site (datadoghq.com, datadoghq.eu, etc.)
  env: 'production', // Environment

  // Optional Datadog configuration
  service: 'my-service', // Service name
  version: '1.0.0', // Application version
  applicationId: 'app-id', // Your application ID for RUM attribution

  // Enable exposure logging
  enableExposureLogging: true,

  // Enable flag evaluation tracking
  enableFlagEvaluationTracking: true,

  // Optional Fetch-compatible implementation for flag configuration requests
  flagConfigurationFetch: globalThis.fetch,
})

The custom Fetch implementation applies only to flag configuration requests. Exposure and flag-evaluation intake requests use their existing transports. It receives the provider-generated RequestInit, including Datadog authentication and any configured custom headers, and may route or transform the request as needed.

Request Timeouts and Retries for npm Consumers

The npm package provides Fetch-compatible wrappers for adding a timeout and retries. The CDN bundle does not expose these helpers. The wrappers preserve the provider's cancellation signal and can be composed:

import { DatadogProvider, withRetry, withTimeout } from '@datadog/openfeature-browser'

const customFetch = withRetry(withTimeout(globalThis.fetch, 5_000), 1)

const provider = new DatadogProvider({
  clientToken: 'pub_...',
  env: 'production',
  flagConfigurationFetch: customFetch,
})

Here, each attempt has a five-second timeout and 1 allows one retry after the initial request. The timeout includes response-body download. The wrapper buffers the response body and is intended for flag configuration responses. A timeout of 0 disables the timer. Valid timeout values end at 2_147_483_647. Retry counts range from 0 to 10. withRetry uses randomized exponential backoff for Fetch TypeError failures, timeout failures, HTTP 408, and HTTP 5xx responses. On HTTP 503, a valid Retry-After value up to 30 seconds is treated as a minimum delay before jittered backoff is added; responses that request a longer delay are not retried. It does not retry HTTP 429. Browsers report network, CORS, and CSP failures as TypeError, so the wrapper cannot separate those causes. For timeout only, pass withTimeout(globalThis.fetch, 5_000) directly as flagConfigurationFetch.

Local debug logging

Set debugMode: true in the provider options to print feature-flag diagnostics to console.log. It defaults to false and does not require an OpenFeature logger or a global Datadog verbosity setting.

const provider = new DatadogProvider({
  clientToken: 'pub_...',
  env: 'production',
  applicationId: 'app-id',
  debugMode: true,
})

Filter the developer console for [Datadog Feature Flags]. Each record includes an event name, timestamp, SDK version, provider instance ID and sequence. Context changes have request/revision IDs; evaluations have evaluation IDs; uploads have batch IDs. The initial debug.enabled record confirms the option took effect before validation.

Logs include complete raw contexts, normalized targeting attributes, flag values, defaults, configuration responses, assignment metadata and event payloads. Transport credential values and custom-header values are omitted from configuration diagnostics. Context attributes remain intact even if their names resemble credential fields. Full configurations are logged at fetch, installation and cache boundaries. Per-evaluation records reference their configuration ID/revision and retain raw context, defaults, results and the evaluated assignment without repeating unrelated flags. Values are snapshotted at logging time. Large records are emitted as debug.chunk records: group by providerInstanceId and sequence, order by chunk, concatenate data, then parse the resulting JSON. Accessors are marked without invoking them, and cycles/undefined/non-finite numbers/BigInts use explicit type markers.

Useful events:

Event What it explains
init.*, tracking.configured Validation, effective settings and enabled channels
context.* Original context, RUM enrichment and attributes actually sent
fetch.* HTTP status/body, timeout, retry attempts, cancellation and unknown transport failures
configuration.*, cache.*, provider.* Decode/install versus rejection, memory/initial/IndexedDB fallback and state changes
evaluation.completed, evaluation.trace, evaluation.returned Value/default origin, variant metadata, local-rule trace and OpenFeature hook result
exposure.*, tracking.policy, rum.* Eligibility, duplicates, opt-outs and handoff to RUM
evaluation.aggregated, batch.*, upload.* Aggregation, admission, flush, intake acceptance, retry and drop
shutdown.* Close/cancellation and retained state

intake_accepted means an HTTP success response; it does not prove downstream processing. browser_queued means sendBeacon accepted the send, without server acknowledgement. Browser network/CORS/CSP/content-blocker failures can be indistinguishable and are reported as an unknown transport failure. Precomputed assignments expose the server's returned metadata, not a reconstructed server rule trace. The provider emits configuration/state events; it cannot observe whether React rendered or an Angular subscription updated the UI. Listener-failure diagnostics cover handlers registered on the provider emitter; OpenFeature client listeners use OpenFeature's own error logging.

DatadogCoreProvider also accepts { debugMode: true }. For application-managed tracking, pass debugMode: true to each createDatadogExposureLoggingHook, createDatadogEvaluationLoggingHook, or createDatadogRumTrackingHook controller whose output you want. Standalone fetchPrecomputedConfiguration and fetchRulesConfiguration accept the same option. DatadogDevtools inherits a Datadog provider's setting, with an optional second options argument to override it. Core-only mode still leaves configuration fetching and tracking ownership with the application.

Debug logging itself does not enqueue remote events or change retry/targeting policy. Application console interceptors can still observe console output. Pending requests and persistence operations may finish after close and log their completion; shutdown.completed does not claim a guaranteed network drain.

Usage Examples

Flag Evaluation

const client = OpenFeature.getClient()

// Boolean flags
const showFeature = await client.getBooleanValue('show-new-feature', false)

// String flags
const theme = await client.getStringValue('app-theme', 'light')

// Number flags
const timeout = await client.getNumberValue('request-timeout', 5000)

// Object flags
const config = await client.getObjectValue('feature-config', {})

Using Evaluation Context

Context must be set globally before flag evaluation and affects all subsequent evaluations:

// Set global context (async operation)
await OpenFeature.setContext({
  targetingKey: 'user-123',
  userId: 'user-123',
  userEmail: 'user@example.com',
})

// Now evaluate flags with the context
const result = await client.getBooleanDetails('premium-feature', false)
console.log(result.value) // Flag value
console.log(result.reason) // Evaluation reason

Contributing

Setup

This project uses @lavamoat/allow-scripts to protect against supply-chain attacks by blocking all dependency lifecycle scripts by default. Only explicitly allowlisted packages can run postinstall scripts.

To install dependencies:

yarn setup

Do not use bare yarn install for local development — it will skip the postinstall scripts that some dependencies need (e.g. nx, unrs-resolver).

Adding new packages

When you add a dependency that includes lifecycle scripts (preinstall/install/postinstall):

  1. Inspect the dependency's install scripts to verify they are safe.
  2. Run yarn allow-scripts auto to update the allowlist in package.json.
  3. Review the generated lavamoat.allowScripts entries — set trusted packages to true and leave untrusted ones as false.
  4. Run yarn setup to re-install with the updated allowlist.

End-user license agreement

https://www.datadoghq.com/legal/eula

About

No description, website, or topics provided.

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages