Skip to main content

Standalone @flaggr/sdk package with pluggable OTEL instrumentation

Last updated November 21, 2026

TypeScript SDK (@flaggr/sdk)

The standalone Flaggr SDK for TypeScript. Includes a core client, React hooks, and pluggable OpenTelemetry instrumentation.

Installation

npm install @flaggr/sdk
Use 0.5.0 or later

@flaggr/sdk 0.3.0 and 0.4.0 import isLocallyEvaluable from @flaggr/evaluator 0.2.0, which doesn't export it, so they fail to load as ES modules (including the jsDelivr +esm build). Under CommonJS (require) they load, but can't evaluate a flag from a streamed, bootstrapped or remoteConfig configuration: evaluate and the typed getters return your default (reason ERROR), and evaluateSync and getBooleanValueSync throw a TypeError. 0.5.0 depends on @flaggr/evaluator 0.3.0 and loads. The script-tag bundle has the evaluator built in and isn't affected.

Script tag

Load the browser bundle from a CDN, with no bundler:

<script src="https://cdn.flaggr.dev/sdk.js"
        data-service-id="web-app"
        data-api-key="fgr_your_token"
        data-api-url="https://api.flaggr.dev"
        data-environment="production"
        defer></script>

The data-* attributes configure the global client, so that tag is the entire setup. Anywhere later on the page:

<script type="module">
  const enabled = await flaggr.flag('checkout-v2', false)
</script>
AttributeSets
data-service-idserviceId. Required: a tag without it configures nothing
data-api-keyapiKey
data-api-urlapiUrl
data-environmentenvironment
data-update-modeupdateMode (stream, batch or poll)
data-remote-configremoteConfig: true (see Remote Configuration)
data-telemetryAdds the flaggrTelemetry() plugin (see Browser Telemetry)
data-expose-flags="false"Keeps flag values off the page (0.5.0 and later, see Browser analytics)

Keep data-api-url in the tag while a page can load 0.4.0. Without it, 0.4.0 sends every evaluation to the relative URL undefined/api/flags/evaluate, next to the page (https://example.com/shop/undefined/api/flags/evaluate from https://example.com/shop/item), and flaggr.flag() returns your default. From 0.5.0, apiUrl defaults to https://api.flaggr.dev.

The bundle is the npm package's dist/browser.global.js, served from:

  • https://cdn.flaggr.dev/sdk.js: Flaggr's CDN. It serves the release Flaggr has pinned for it, whatever npm tags latest: a new npm release reaches it only once Flaggr adds it. latest["/sdk.js"] in https://cdn.flaggr.dev/manifest.json shows the version it serves.
  • https://cdn.jsdelivr.net/npm/@flaggr/sdk@0/dist/browser.global.js: jsDelivr, the newest 0.x release on npm.
  • https://cdn.flaggr.dev/sdk-<version>.js: a pinned copy that never changes, for Subresource Integrity. Take the file's integrity value from the manifest:
<script src="https://cdn.flaggr.dev/sdk-0.4.0.js"
        integrity="sha384-jjDxi4XRdiP9sgrAYjukEGXn7j2/Oj4cAqUz22AmTrqxhrsMQtkoGtyVkR+mm/qs"
        crossorigin="anonymous"
        data-service-id="web-app"
        data-api-key="fgr_your_token"
        data-api-url="https://api.flaggr.dev"
        defer></script>

With a Content Security Policy, allow the CDN's origin in script-src and your apiUrl origin (https://api.flaggr.dev by default) in connect-src. Inline scripts, such as the type="module" one above, also need a nonce or a hash. With the default apiUrl, 0.5.0 and later fetch remote configuration, post telemetry and post trackOutcome events to https://flaggr.dev, so with remoteConfig, flaggrTelemetry(), data-telemetry or trackOutcome also allow https://flaggr.dev in connect-src. 0.4.0 sends all three to its apiUrl.

ES modules from a CDN

<script type="module">
  import { createFlaggr } from 'https://cdn.jsdelivr.net/npm/@flaggr/sdk@0/+esm'
  const client = createFlaggr({ serviceId: 'web-app', apiKey: 'fgr_your_token' })
</script>

This needs 0.5.0 or later (see the warning above).

Quick Start

import { createFlaggr } from '@flaggr/sdk'
 
const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  environment: 'production',
})
 
const isEnabled = await client.getBooleanValue('checkout-v2', false)

Set environment explicitly. Without it, the data plane (https://api.flaggr.dev, the default apiUrl) evaluates in production, while the control plane's POST /api/flags/evaluate on https://flaggr.dev, and OFREP requests without an X-Environment header, evaluate in development.

For a one-line setup, flag() evaluates with a global client that configure() sets up, or that reads FLAGGR_SERVICE_ID, FLAGGR_API_KEY, FLAGGR_ENVIRONMENT and FLAGGR_API_URL (or their NEXT_PUBLIC_ versions) from process.env. See Client SDK.

Remote Configuration (zero-config setup)

Set remoteConfig: true and the SDK fetches service-level settings from GET /api/sdk-config — environment, update mode, cache TTL, and telemetry opt-in all come from the service's settings.sdk instead of being repeated in client code:

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  remoteConfig: true, // pulls environment/updateMode/telemetry from Flaggr
})

Explicit fields always win — remote values only fill gaps. The settings response is cached in localStorage (60s fresh window, stale-while-revalidate), and the flag bootstrap is persisted as a separate snapshot — repeat page loads evaluate instantly from disk with zero requests, revalidating in the background. When the service config sets sdk.telemetry: true, the telemetry plugin attaches itself.

/api/sdk-config is a control plane route, and the default apiUrl reaches it. With apiUrl left at https://api.flaggr.dev, 0.5.0 and later fetch it from https://flaggr.dev, while 0.4.0 fetches it from https://api.flaggr.dev, which passes the request on to the control plane. With any other apiUrl, the client fetches it from that URL. The client waits for the settings before its first remote evaluation, and without an environment in your code it uses the service's default environment from them (production unless the service sets another). If the settings can't be fetched, the client runs on the settings in your code.

Snapshot durability guarantees:

  • Bustable: client.clearPersistedConfig() drops settings + all flag snapshots for the service; schema-versioned records self-invalidate on SDK upgrades; snapshots expire after 7 days.
  • Isolated: snapshots are keyed serviceId + environment + auth-scope (anonymous vs API-key hash) — an authed session's private flags can never leak into an anonymous session.
  • Managed: writes >4MB are skipped; quota errors evict oldest flaggr:* snapshots and retry once; corrupt/stale records are detected and removed.
  • Fresh: the server returns a bootstrapVersion content hash — identical payloads skip re-apply and re-persist entirely; SSE configuration_sync, configuration_delta, and flag-update messages keep the snapshot current.

The endpoint also returns a bootstrap flag payload — the service's flag configurations for the environment — so the SDK evaluates locally with zero additional round trips after the config fetch. Authenticated requests (Authorization: Bearer) get the full flag set; unauthenticated requests get isPublic flags only (same trust boundary as POST /api/flags/evaluate).

Script tag:

<script src="https://cdn.flaggr.dev/sdk.js"
        data-service-id="web-app" data-api-key="fgr_..."
        data-api-url="https://api.flaggr.dev" data-remote-config defer></script>

Browser Telemetry (opt-in)

The flaggrTelemetry() plugin links Core Web Vitals and client errors to the flags that were active, and sends them to Flaggr's SDK telemetry ingest (POST /api/analytics/sdk-telemetry):

  1. Evaluation summaries: counts, cache hits and misses, and latency per flag and variant, aggregated locally, without a request per evaluation.
  2. Core Web Vitals: LCP, CLS, INP, TTFB and (from 0.5.0) FCP through PerformanceObserver, each tagged with the active flag variants.
  3. Error correlation: unhandled window errors, recorded with the active flag variants.
import { createFlaggr, flaggrTelemetry } from '@flaggr/sdk'
 
const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  environment: 'production',
  plugins: [
    flaggrTelemetry({
      vitals: true,           // LCP, CLS, INP, TTFB and FCP (default true)
      errors: true,           // window errors with the active flag variants (default true)
      beacon: true,           // send the last batch when the page is hidden (default true)
      flushIntervalMs: 30000, // periodic flush (default 30 s)
      // endpoint: 'https://flaggr.example.com/api/analytics/sdk-telemetry', // only for a self-hosted Flaggr (see Host below)
    }),
  ],
})

Via the script tag, add data-telemetry:

<script src="https://cdn.flaggr.dev/sdk.js"
        data-service-id="web-app" data-api-key="fgr_..."
        data-api-url="https://api.flaggr.dev" data-environment="production"
        data-telemetry defer></script>
  • Key. The ingest needs the project's SDK key: the client's apiKey, a project API token (personal access tokens are refused with 403). A key scoped to an environment or to particular flags covers no telemetry and is refused with 403 (TELEMETRY_FORBIDDEN): use a project-wide or service-scoped key. Without an apiKey the plugin sends nothing and logs a warning. Once the ingest refuses the key (401 or 403), the plugin stops sending.
  • Host. The ingest is a control plane route, and the default apiUrl reaches it. With apiUrl left at https://api.flaggr.dev, 0.5.0 and later post to https://flaggr.dev/api/analytics/sdk-telemetry, while 0.4.0 posts to https://api.flaggr.dev/api/analytics/sdk-telemetry, which passes the batch on to the control plane. With any other apiUrl, the plugin posts to <apiUrl>/api/analytics/sdk-telemetry; with a self-hosted data plane as apiUrl, set endpoint to the same path on your Flaggr app. A host that answers 404 or 405 stops the plugin, which logs a warning.
  • Delivery. Batches go every flushIntervalMs with the key as a bearer token (Authorization: Bearer). When the page is hidden, the last batch goes on a request that outlives the page: a fetch with keepalive, or navigator.sendBeacon where keepalive isn't supported. Neither can send an Authorization header without a CORS preflight, so that batch carries the key as apiKey in a text/plain JSON body. 0.4.0 sends its page-hide batch without the key, and the ingest refuses it with 401.
  • Rollout checks. Rollout RUM checks count this telemetry only when the batch comes from the domain, or a subdomain, of one of the project's Sites, judged by its Origin header, or by its Referer when it has no Origin. Register a Site for each domain your app runs on. Batches from other origins, and from servers (no Origin or Referer), are stored but marked untrusted.
  • The report. The telemetry report (GET /api/analytics/sdk-telemetry, which the console's Performance tab and the MCP server's get_sdk_analytics read) leaves the web vitals, errors and rage and dead clicks of untrusted batches out, unless a project member adds includeUntrusted=1. It counts the evaluation summaries (evaluations, cache hits and latency) of every batch, servers' included. Those summaries never count as visitors, or as events from other origins, in browser analytics.

Read the aggregated report with GET /api/analytics/sdk-telemetry (see SDK Ingest & Telemetry Analytics). AnalyticsClient, getFlaggrAnalytics(), getFlaggrDiagnostics() and an analytics option for createFlaggr belong to the Flaggr console's own client, not to @flaggr/sdk, which doesn't export them.

If you report evaluation events yourself, POST /api/evaluations needs the project's SDK key or a project API token in the Authorization header: batches without one are refused with 401, and batches that name another project's service are refused whole (403). Use POST /api/events/exposures/batch for new exposure integrations.

Error Tracking

flaggrErrors() (0.6.0 and later) reports crashes and errors to Flaggr. The console's Issues page groups them into issues. Each event carries:

  • the flag variants the client evaluated,
  • your release and environment,
  • the user and tags you set,
  • the breadcrumbs that led up to it: flag evaluations, console warnings and errors, fetch requests, and navigations in a browser.
import { createFlaggr, flaggrErrors, captureException, setUser } from '@flaggr/sdk'
 
const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_...',
  environment: 'production',
  plugins: [flaggrErrors({ release: 'web@1.4.2' })],
})
 
setUser({ id: currentUser.id })
 
try {
  await checkout()
} catch (error) {
  captureException(error, { tags: { step: 'pay' }, extra: { cartSize: 3 } })
}

Uncaught errors and unhandled promise rejections are reported on their own (autoCapture: false turns that off). captureException, captureMessage, addBreadcrumb and setUser go through the most recently created client with flaggrErrors(). The plugin has the same methods, plus setTag, setTags and flush().

Where errors go:

  • In a browser, errors go to the Flaggr app with the client's apiKey (the project's SDK key), like Browser Telemetry batches. When both plugins are installed, flaggrTelemetry() leaves window errors to flaggrErrors().
  • On a server (Node.js, Bun, Deno), errors go to POST /api/ingest/server-events. That route needs a project API token and refuses SDK keys, because SDK keys ship inside client bundles.
    • Pass the token as serverToken, or set FLAGGR_ERRORS_TOKEN. Otherwise the client's apiKey is tried.
    • After an uncaught exception, the plugin sends it, then exits the process with code 1 as Node.js would have, within shutdownTimeoutMs (default 2,000 ms). Set exitOnUncaught: false to leave that to your own handler.
OptionDefault
releaseYour app's version: issues show the releases they appear in, and a resolved issue regresses when it comes back
environmentthe client's
autoCapturetrueCatch uncaught errors and unhandled rejections
breadcrumbsallfalse, or { flags, console, fetch, navigation }
maxBreadcrumbs50
sampleRate1The share of errors sent
ignoreErrors[]Strings or regular expressions matched against the message
beforeSendChange an event, or return null to drop it
serverTokenFLAGGR_ERRORS_TOKEN, then apiKeyServer only
serverServiceIdServer only: a service id (not its slug) to file errors under
tracePropagationTargetsthe page's originBrowser only: URLs (string prefixes or patterns) whose fetch requests get a traceparent header, so your backend's traces and errors share the browser's trace id; [] turns it off
appUrlfrom apiUrlThe Flaggr app's URL, when apiUrl points somewhere other than the hosted data plane

The plugin sends at most 60 errors a minute, and reports an error object only once even if it reaches several handlers. It cuts messages and stacks to 2,000 characters and keeps URLs without their query strings. Flaggr removes tokens, email addresses and URL credentials before storing events. With the script tag, add data-errors (and data-release="web@1.4.2") to turn error tracking on; window.flaggr.captureException is then available.

Browser analytics

From 0.5.0, a client running in a browser publishes the flag values it resolves for Flaggr browser analytics (https://cdn.flaggr.dev/a.js), so every event the analytics script sends is tagged with the variants the page is using. Values are merged into window.__FLAGGR_FLAGS__, keeping keys that other code put there. Each burst of changes dispatches one flaggr:flags-changed event on window whose detail is the full map, and nothing is dispatched when no value changed. If other code replaces or deletes the map, each value of the client's that went missing is put back the next time the client evaluates any flag; a key the new map holds with another value is left as it is. When the client publishes before anything else has, it starts from the server-rendered window.__FLAGGR_BOOTSTRAP__ values, by the same rules as its own.

  • What's published. The result of every evaluation (the typed getters, evaluate, evaluateSync, batch evaluations and cache hits), and each later stream push or batch refresh for a flag the page has evaluated or watches with onFlagChange.
  • Copies. What's published is a copy of each value as it was resolved: changes your code makes to the object afterwards never reach the page, even when the value is put back. Object and array values are published by variant name when the evaluation has one. Values over 1,024 characters of JSON, and values that can't be serialized, aren't published. _flaggr_analytics is always published in full: its value sets what the analytics script collects.
  • No fallbacks. Your defaultValue or defaults entry isn't published when it's returned because an evaluation failed, the flag doesn't exist, or nothing has loaded yet. A failed evaluation leaves the value published before it.
  • Deleted flags. A flag that no longer exists is taken off the page: when an evaluation reports it missing (the data plane's FLAG_NOT_FOUND), the stream reports it deleted, or a configuration from the stream no longer has it.
  • Other users. Values evaluated for someone else aren't published: when the client has a targetingKey, a per-call context that gives another one, or clears it ({ targetingKey: undefined }). A client without a targetingKey publishes values evaluated with any per-call targetingKey, and the latest one wins. On pages that evaluate flags for other users, such as an admin's "preview as customer" list, give the client the page user's targetingKey (the context option), or set exposeFlags: false.
  • After setContext. The flags the client published for its own context, and the ones you watch with onFlagChange, are republished for the new context at once when the client can evaluate them locally. The rest are republished when the page next evaluates them: flags only the data plane can evaluate, and flags the page evaluated with a per-call context. A remote result for an evaluation called before setContext isn't published or cached.
  • Browsers only. Nothing is published on a server (including one with a DOM shim), in a worker, or anywhere else without a working DOM.

Any script on the page can read published values, and the analytics script sends them with every event. Turn publishing off for one client with exposeFlags: false, or for the whole page with data-expose-flags="false" on any script tag: it applies to every client created while that tag is on the page. With the script-tag bundle it also applies after the tag is gone, if the tag was there when the bundle loaded. A client's own exposeFlags setting overrides the attribute.

const client = createFlaggr({ serviceId: 'web-app', apiKey: 'fgr_your_token', exposeFlags: false })
<script src="https://cdn.flaggr.dev/sdk.js" data-service-id="web-app"
        data-api-key="fgr_your_token" data-api-url="https://api.flaggr.dev"
        data-expose-flags="false" defer></script>

Core Client API

Flag Evaluation Methods

// Boolean flag
const enabled: boolean = await client.getBooleanValue('my-flag', false)
 
// String flag
const variant: string = await client.getStringValue('button-color', 'blue')
 
// Number flag
const limit: number = await client.getNumberValue('rate-limit', 100)
 
// Object flag (typed). From 0.5.0 an interface works too; 0.4.0 needs a type alias.
type BannerConfig = {
  text: string
  color: string
  dismissible: boolean
}
const banner: BannerConfig = await client.getObjectValue<BannerConfig>(
  'banner-config',
  { text: '', color: 'blue', dismissible: true }
)

Evaluation with Context

Pass targeting context for per-user or per-segment evaluation:

const result = await client.getBooleanValue('checkout-v2', false, {
  targetingKey: 'user-456',
  email: 'bob@example.com',
  plan: 'enterprise',
  country: 'AU',
})

Detailed Evaluation

When you need the full evaluation result (reason, variant, metadata):

const detail = await client.evaluate<boolean>('checkout-v2', false)
 
// detail.value       → true
// detail.reason      → "TARGETING_MATCH"
// detail.variant     → "enabled"
// detail.errorMessage → undefined (present on errors)

With React

import { FlaggrProvider, useBooleanFlag } from '@flaggr/sdk/react'
 
function App() {
  return (
    <FlaggrProvider apiKey="fgr_your_token" serviceId="web-app" environment="production">
      <Checkout />
    </FlaggrProvider>
  )
}
 
function Checkout() {
  const useNewFlow = useBooleanFlag('checkout-v2', false)
  return useNewFlow ? <CheckoutV2 /> : <CheckoutClassic />
}

FlaggrProvider takes apiKey, serviceId and environment props, or a config object with any createFlaggr option; when you pass the serviceId prop, the props override the same fields in config. In the Next.js App Router, render it from a 'use client' file and use the hooks in Client Components only: see React Hooks.

Available Hooks

HookReturnsDescription
useBooleanFlag(key, default, context?)booleanBoolean flag value
useStringFlag(key, default, context?)stringString flag value
useNumberFlag(key, default, context?)numberNumber flag value
useObjectFlag<T>(key, default, context?)TTyped object flag value
useFlag(key, default?, context?)the default's typeAny flag type; the default is false when omitted
useFlaggr()FlaggrClientInstanceThe provider's client, for setContext, trackOutcome and the other client methods
useConnectionState()ConnectionStateCurrent connection state
useRefreshFlags()() => Promise<void>Re-evaluates every flag the client has cached or a hook watches, in batched requests of up to 100 flags, re-renders the hooks whose value changed, and resolves when done (0.4.0 only clears the cache)

Hook Behavior

Each hook returns the flag's value. Its first render uses the value the client can resolve without a request (a streamed or bootstrapped configuration, or the cache), else the flag's defaults entry or your default; it then re-renders with the evaluated value, and again when the flag changes through a stream push or a batch refresh. A failed evaluation resolves to the defaults entry or your default.

// ConnectionState is one of:
type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'
 
// Use in a status indicator
function ConnectionBadge() {
  const state = useConnectionState()
  return (
    <span className={state === 'connected' ? 'text-green-500' : 'text-red-500'}>
      {state}
    </span>
  )
}

Error Handling

The SDK is designed to fail safely. Evaluation methods never throw -- they return the default value and report errors via the plugin system.

// This never throws, even if the server is unreachable
const value = await client.getBooleanValue('my-flag', false)
// → false (default) when an error occurs

Evaluation Reasons and Errors

ReasonMeaningRecovery
TARGETING_MATCHA targeting rule matched, including a rule's percentage rolloutNo action needed
OVERRIDEAn override for the context's targetingKey matchedNo action needed
VARIANTVariant allocation selected this valueNo action needed
DEFAULTNo rule or variant applied, so the flag's default value was returned. Also the reason from evaluateSync before anything has loaded (your default, or the flag's defaults entry)Check the flag's rules if unexpected
DISABLEDFlag is disabledEnable the flag or update the fallback
FLAG_NOT_FOUNDNo flag with that key in the service and environment (the data plane, the default apiUrl)Check the key, serviceId and environment
NOT_FOUNDThe same, from the control plane (https://flaggr.dev)Check the key, serviceId and environment
STATICThe response carried no reasonNo action needed
ERRORNetwork or server error, a refused token, or an invalid responseCheck connectivity and errorMessage

Through the control plane, evaluations can also return EXPERIMENT, PREREQUISITE_FAILED and MUTUAL_EXCLUSION (see Evaluation Reasons). The client passes them on as received. From 0.5.0 the EvaluationResult type lists them and FLAG_NOT_FOUND; 0.4.0's type lists none of the four.

Custom Error Handling

Use the plugin system for logging and alerting on errors:

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  plugins: [{
    name: 'error-reporter',
    onEvaluateError(flagKey, error, durationMs) {
      console.error(`Flag evaluation failed: ${flagKey}`, error)
      // Send to your error tracking service
      Sentry.captureException(error, {
        tags: { flagKey, durationMs },
      })
    },
  }],
})

Streaming Reconnection

Evaluation methods fail safely by returning the provided default value and reporting errors through plugins. The SDK does not expose per-evaluation retry configuration.

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  enableStreaming: true,
})

With an apiKey, the SDK streams over fetch and sends the key in the Authorization header, never in the URL. It reconnects after network errors, server errors and dropped streams with exponential backoff (1 s doubling to 30 s). The connection state is error while it's down and connected once the stream reopens. If the stream refuses the key (401/403, for example a flag-scoped key on a service-wide stream), or the runtime can't stream a response body, the SDK stops streaming and refreshes watched flags every batchIntervalMs instead (getUpdateMode() still reports stream). Without an apiKey it uses EventSource, which works only for public demo services with apiUrl: 'https://flaggr.dev': the data plane answers 401 to a stream without a key. From 0.5.0 the client then refreshes watched flags every batchIntervalMs, as it does when a stream refuses a key (its connection state stays error), and it polls the same way where EventSource doesn't exist. 0.4.0 stays in the error state without polling. It also streams with an apiKey through EventSource, with the key in the URL, which the data plane refuses the same way (see Real-Time Updates). Server-side clients (Node 18+) with an apiKey in stream mode stream from 0.5.0, so call destroy() when you're done.

With OpenTelemetry

The SDK supports pluggable OTEL instrumentation. Install the peer dependency:

npm install @opentelemetry/api

Basic OTEL Setup

import { createFlaggr } from '@flaggr/sdk'
import { otelPlugin } from '@flaggr/sdk/otel'
 
const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  plugins: [otelPlugin()],  // Uses global OTEL providers
})

Custom Configuration

import { otelPlugin } from '@flaggr/sdk/otel'
 
plugins: [otelPlugin({
  serviceName: 'checkout-service',
  enableTracing: true,
  enableMetrics: true,
  metricPrefix: 'myapp.flags',
  additionalAttributes: {
    'deployment.environment': 'production',
    'service.version': '1.2.3',
  },
})]

Bring Your Own Providers

import { MeterProvider } from '@opentelemetry/sdk-metrics'
import { otelPlugin } from '@flaggr/sdk/otel'
 
const meterProvider = new MeterProvider({
  readers: [myMetricReader],
})
 
plugins: [otelPlugin({
  meterProvider,
  tracerProvider: myTracerProvider,
})]

Exported Metrics

MetricTypeDescription
flaggr.evaluations.totalCounterTotal flag evaluations
flaggr.evaluations.durationHistogramEvaluation latency (ms)
flaggr.evaluations.errorsCounterEvaluation errors
flaggr.cache.hitsCounterCache hits
flaggr.cache.missesCounterCache misses
flaggr.flag_changes.totalCounterFlag change events
flaggr.connections.activeUpDownCounterActive connections

Exported Spans

Each flag evaluation creates a span named flaggr.evaluate with attributes:

AttributeDescription
feature_flag.keyFlag key being evaluated
feature_flag.provider_nameAlways "flaggr"
feature_flag.valueEvaluated value
feature_flag.reasonEvaluation reason
feature_flag.variantVariant key (if applicable)

Plugin System

The SDK supports a plugin architecture for extending behavior:

import type { FlaggrPlugin } from '@flaggr/sdk'
 
const myPlugin: FlaggrPlugin = {
  name: 'my-plugin',
  onInit(client) { /* SDK initialized */ },
  onEvaluate(flagKey, context) { /* Before evaluation */ },
  onEvaluateComplete(flagKey, result, durationMs) { /* After evaluation */ },
  onEvaluateError(flagKey, error, durationMs) { /* On error */ },
  onFlagChange(event) { /* Flag value changed */ },
  onConnectionStateChange(state) { /* Connection state changed */ },
  onRequest(info) { /* After each SDK network request */ },
  onDestroy() { /* SDK destroyed */ },
}
 
const client = createFlaggr({
  serviceId: 'web-app',
  plugins: [myPlugin],
})

Plugin Lifecycle

createFlaggr()
  ├─ onInit()           Called once after client creation
  │
  ├─ evaluate('flag')
  │   ├─ onEvaluate()          Before evaluation
  │   ├─ onEvaluateComplete()  After successful evaluation
  │   └─ onEvaluateError()     On evaluation failure
  │
  ├─ onFlagChange()     When a flag value changes (stream pushes, batch refreshes)
  ├─ onConnectionStateChange()  On connection state transitions
  │
  └─ client.destroy()
      └─ onDestroy()    Cleanup (close connections, flush metrics)

Configuration

interface FlaggrConfig {
  apiUrl?: string        // Default: 'https://api.flaggr.dev'
  serviceId: string      // Your service identifier
  apiKey?: string        // API token
  environment?: string   // Target environment (set it: see Quick Start)
  context?: EvaluationContext  // Default evaluation context
  plugins?: FlaggrPlugin[]     // SDK plugins
  cacheTtl?: number      // Cache TTL in ms (default: 10000)
  updateMode?: 'stream' | 'batch' | 'poll'  // Update delivery (default: poll)
  batchIntervalMs?: number  // Batch refresh cadence (default: 2000)
  enableStreaming?: boolean  // Deprecated — use updateMode: 'stream'
  bootstrap?: Record<string, unknown>  // Flag configurations to evaluate locally from the start
  defaults?: Record<string, FlagValue>  // Fallbacks for evaluations that fail or find no flag
  remoteConfig?: boolean  // Fetch service settings from /api/sdk-config (control plane)
  exposeFlags?: boolean   // Publish resolved values for browser analytics (default: on in a browser, 0.5.0+)
}

Update Modes

The SDK's update delivery can be switched at runtime — stream applies SSE pushes instantly with zero requests, batch revalidates every flag the client has cached or watches each interval (up to 100 flags per request), and poll relies on per-flag fetches when the cache expires:

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  updateMode: 'batch',
  batchIntervalMs: 1500,
})
 
client.setUpdateMode('stream') // tears down batch, opens SSE
 
// Per-request telemetry for instrumentation
const instrumented = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  plugins: [{
    name: 'telemetry',
    onRequest: (info) => {
      // info: { url, durationMs, ok, requestBytes, responseBytes }
      metrics.record(info.durationMs)
    },
  }],
})

Local evaluation

With updateMode: 'stream', bootstrap or remoteConfig, the client evaluates flags from the configurations it holds, with @flaggr/evaluator (0.3.0 in @flaggr/sdk 0.5.0), as the data plane does. A flag that uses an operator the data plane doesn't implement, such as in_cohort, is evaluated remotely instead. 0.5.0 evaluates differently from the 0.4.0 script-tag bundle (the 0.4.0 npm package can't evaluate locally; see Installation) in three ways:

  • A targeting rule with no conditions and no condition groups matches everyone (0.4.0 matched it to nobody). A data plane from before Flaggr 0.5.0 matches it to nobody, so a client that evaluates locally against one serves such a rule where remote evaluations there don't. See Evaluation Order.
  • A context without a targetingKey is never in a rule's rollout below 100% (0.4.0 hashed it as an empty key, so such a rule included every keyless context of some flags and none of others).
  • The configurations https://api.flaggr.dev streams and exports carry unset fields as null: a rule whose rolloutPercentage is null serves everyone it matches, and a rule whose value is null serves the flag's default value. (0.4.0 skips the first and serves null for the second. It can't stream from https://api.flaggr.dev, so it meets them only in a bootstrap built from the data plane's flags, such as /api/flags/export.) An entry of targeting that isn't an object is skipped.

Offline Defaults

Provide fallback values in one place:

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_token',
  updateMode: 'stream',
  defaults: {
    'checkout-v2': false,
    'dark-mode': true,
    'rate-limit': 100,
    'banner-config': { text: 'Welcome', color: 'blue', dismissible: true },
  },
})

A defaults entry is a fallback: the client returns it instead of the method-level default wherever it would return that default. That covers an evaluation that fails (reason ERROR), a flag that isn't found (FLAG_NOT_FOUND from the data plane, NOT_FOUND from the control plane) and evaluateSync before anything has loaded (DEFAULT). A flag listed in defaults is still evaluated as usual, in every update mode: its entry never replaces a result.

0.4.0 returns a defaults entry before any remote evaluation, so it never evaluates a listed flag remotely: in poll mode, where nothing is resolved locally, a listed flag always gets its defaults value. With 0.4.0, use defaults only for flags the client evaluates locally, with updateMode: 'stream' or bootstrap.