Skip to main content

Complete reference for the Flaggr TypeScript client SDK

Last updated November 21, 2026

Client SDK

Reference for the @flaggr/sdk client: creating it, evaluating flags, context, change events, server-rendered bootstrap and cleanup. For installation, script tags, telemetry and every configuration option, see TypeScript SDK; for React, see React Hooks.

Initialization

import { createFlaggr } from '@flaggr/sdk'
 
const client = createFlaggr({
  serviceId: 'my-service',
  apiKey: 'fgr_your_api_token',
  environment: 'production',
})

createFlaggr returns the client at once; there's nothing to await. By default it evaluates remotely through the data plane (https://api.flaggr.dev), with one request per flag whenever the cached value (10 seconds by default) has expired. With updateMode: 'stream' it receives the service's flag configurations instead and evaluates locally (see Update modes).

Global client

flag() evaluates with a global client that's created on first use:

import { configure, flag } from '@flaggr/sdk'
 
configure({ serviceId: 'my-service', apiKey: 'fgr_your_api_token', environment: 'production' })
 
if (await flag('dark-mode')) {
  enableDarkMode()
}
const variant = await flag('checkout-variant', 'classic', { targetingKey: 'user-123' })

Without a default, flag() evaluates a boolean flag with the default false. Without configure(), the global client reads FLAGGR_SERVICE_ID, FLAGGR_API_KEY, FLAGGR_ENVIRONMENT and FLAGGR_API_URL (or the same names with a NEXT_PUBLIC_ prefix) from process.env, and flag() rejects when there's no service ID. Calling configure() again replaces the global client; resetGlobalClient() destroys it and forgets the configuration.

Evaluating Flags

const enabled = await client.getBooleanValue('dark-mode', false)
const variant = await client.getStringValue('banner-variant', 'default')
const maxItems = await client.getNumberValue('cart-limit', 10)
const theme = await client.getObjectValue<{ primary: string; radius: number }>('theme-config', {
  primary: '#3b82f6',
  radius: 8,
})

Evaluation methods never throw. When the flag doesn't exist, the request fails or the token is refused, they return your default value. (A flag with an entry in the defaults option gets that entry instead of your default.)

evaluate returns the value with the reason, the variant and any error message:

const detail = await client.evaluate('checkout-v2', false)
// { value: true, reason: 'TARGETING_MATCH', variant: 'enabled' }

evaluateSync and getBooleanValueSync answer without a request, from a streamed or bootstrapped configuration or the cache, and return your default when neither has the flag.

The FlaggrClient class, which createFlaggr returns and @flaggr/sdk exports for advanced use, also has evaluateBatch. It evaluates many flags with at most one request per 100 remote-only flags:

import { FlaggrClient } from '@flaggr/sdk'
 
const client = new FlaggrClient({ serviceId: 'my-service', apiKey: 'fgr_your_api_token', environment: 'production' })
const results = await client.evaluateBatch([
  { flagKey: 'dark-mode', defaultValue: false },
  { flagKey: 'cart-limit', defaultValue: 10 },
])
results.get('dark-mode')?.value

Evaluation Context

Pass user attributes for targeted evaluation, either for every evaluation of the client or for one call. A per-call context is merged over the client's:

client.setContext({
  targetingKey: 'user-123',
  email: 'alice@example.com',
  plan: 'enterprise',
  region: 'au',
})
 
const beta = await client.getBooleanValue('beta-features', false, { region: 'us' })

Context attributes are matched against the targeting rules defined in the dashboard. Always include targetingKey (usually the user ID): percentage rollouts and variant assignment hash it. setContext clears the cached values. Flags you watch with onFlagChange that the client can evaluate locally are evaluated again for the new context at once, and their listeners get the new values.

Event Subscriptions

onFlagChange

Listen for updates to one flag. The listener gets an event with the flag key and the new (and, when known, old) value:

const unsubscribe = client.onFlagChange('my-flag', (event) => {
  console.log('Flag changed:', event.flagKey, event.oldValue, '→', event.newValue)
})
 
// Clean up
unsubscribe()

Changes arrive through stream pushes (updateMode: 'stream') and batch refreshes (updateMode: 'batch'). In the default poll mode, a change shows up the next time you evaluate the flag after its cached value expires.

onConnectionStateChange

Monitor the connection to Flaggr:

import { ConnectionState } from '@flaggr/sdk'
 
const unsubscribe = client.onConnectionStateChange((state) => {
  if (state === ConnectionState.ERROR) {
    console.warn('Flaggr stream is down; the client is reconnecting')
  }
})

client.getConnectionState() returns the current state.

Bootstrap (SSR)

To evaluate on first render without a request, give the client flag configurations up front with the bootstrap option. On the server, fetch the service's configuration from the data plane:

// Server side: the token stays on the server
const res = await fetch(
  'https://api.flaggr.dev/api/flags/export?serviceId=web-app&environment=production',
  { headers: { Authorization: `Bearer ${process.env.FLAGGR_TOKEN}` } },
)
const configuration = await res.json() // { flags: { [key]: flag }, serviceId, environment, generatedAt }

Pass configuration to the page (for example as a prop), and create the browser client with it:

const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: 'fgr_your_read_only_token',
  environment: 'production',
  bootstrap: configuration,
})
 
const enabled = client.getBooleanValueSync('checkout-v2', false) // evaluated locally

The configuration holds every flag of the service with its targeting rules, and everything in it is visible to anyone who can read the page. Flags whose rules use operators the data plane doesn't support (such as exists or cohorts) are still evaluated remotely. With remoteConfig: true, the client fetches the same kind of bootstrap from the control plane's GET /api/sdk-config itself (see Remote Configuration).

window.__FLAGGR_BOOTSTRAP__ isn't read by the client for evaluation. Flaggr browser analytics reads it, and from 0.5.0 the client starts its published values from it.

Outcomes

Record a conversion or other outcome for a flag:

await client.trackOutcome({ flagKey: 'checkout-v2', eventName: 'purchase', eventValue: 49.99, userId: 'user-123' })

The event carries the variant this client last evaluated for that flag and targeting key: the event's targetingKey when you pass one, else its userId or the client's own targetingKey. When the client hasn't evaluated the flag for that key, the variant is unknown. Pass variant when you know which one the user saw, for example on a server that evaluated the flag elsewhere. The client keeps the variants of the last 10,000 flag and targeting key pairs it evaluated.

Outcomes are stored by the control plane, and only when the request carries the SDK key (401 otherwise). From 0.5.0, trackOutcome posts to the Flaggr app's /api/events/outcomes: on https://flaggr.dev when apiUrl is the default https://api.flaggr.dev, else on your apiUrl. It sends the apiKey in the Authorization header, in browsers and on servers alike. The request is a keepalive fetch, so in a browser it can finish after the page closes. With the default apiUrl, a page with a Content Security Policy needs https://flaggr.dev in connect-src. From a page on another origin the browser sends a CORS preflight first, which https://flaggr.dev answers.

0.4.0 posts to <apiUrl>/api/events/outcomes (https://api.flaggr.dev passes it on to the control plane) and keeps one variant per flag, the last it evaluated. In a browser it sends the event with navigator.sendBeacon, which can't carry the key, so nothing is stored; on a server, which has no sendBeacon, it sends the key. With 0.4.0, record browser outcomes, and those of a server that evaluates the flag for many users, from your server: post them to https://flaggr.dev/api/events/outcomes with the variant the user saw and the SDK key in the Authorization header (up to 50 events and 128 KiB per request). See Conversion Rates by Variant for the request.

Cleanup

client.destroy()

destroy() closes the stream, stops batch refreshes, and drops the client's cache, configurations and listeners. Call it when you're done with a client in stream or batch mode, including on servers (Node 18 or later). clearPersistedConfig() drops the settings and flag snapshots that remoteConfig keeps in localStorage, for example after rotating a key.

OpenFeature Integration

@flaggr/sdk isn't an OpenFeature provider. To evaluate Flaggr flags through the OpenFeature SDKs, use an OpenFeature OFREP provider pointed at Flaggr, such as @openfeature/ofrep-provider for Node.js:

import { OpenFeature } from '@openfeature/server-sdk'
import { OFREPProvider } from '@openfeature/ofrep-provider'
 
await OpenFeature.setProviderAndWait(new OFREPProvider({
  baseUrl: 'https://api.flaggr.dev/api',
  headers: [
    ['Authorization', `Bearer ${process.env.FLAGGR_TOKEN}`],
    ['X-Service-Id', 'my-service'],
    ['X-Environment', 'production'],
  ],
}))
 
const value = await OpenFeature.getClient().getBooleanValue('my-flag', false, { targetingKey: 'user-123' })

See OFREP for the settings and the Python and Go equivalents.