Reference

API Reference: SDK

TypeScript client API for bootstrapping FlagForge definitions and evaluating flags locally

Package and import

Install the SDK in the application that evaluates your flags:

bash
pnpm add @flagforge/sdk

The package exposes the FlagForgeClient class and its public option and evaluation types from one import path:

typescript
import {
  FlagForgeClient,
  type AttributeValue,
  type BootstrapPayload,
  type ChangeListener,
  type ClientOptions,
  type EvaluationContext,
  type EvaluationReason,
  type EvaluationResult,
  type FetchLike,
  type FlagValue,
  type JsonValue,
} from "@flagforge/sdk";

FlagForgeClient

FlagForgeClient downloads the definitions and segments for one environment from GET /v1/config. After bootstrap, flag checks use the downloaded definitions locally and synchronously; checks do not make a network request per call.

Constructor

typescript
new FlagForgeClient(options: ClientOptions): FlagForgeClient
OptionTypeDefaultDescription
clientKeystringRequiredFlagForge client API key.
baseUrlstringRequiredBase URL of the FlagForge API. A trailing slash is removed before requests are built.
environmentstringRequiredEnvironment key whose definitions are bootstrapped and evaluated.
pollIntervalMsnumber0Background refresh interval in milliseconds. 0 disables polling.
fetchFetchLikeglobalThis.fetchOptional WHATWG-compatible fetch implementation.

The constructor throws if clientKey, baseUrl, or environment is missing. It also throws when no fetch implementation is available and options.fetch was not supplied.

Initialization and lifecycle methods

typescript
init(): Promise<void>
refresh(): Promise<void>
readonly ready: boolean
close(): void
  • init() performs the first refresh(), marks the client ready, and starts background polling when pollIntervalMs is greater than zero. Call it once before reading flags.

  • refresh() requests the current environment configuration and notifies registered change listeners after replacing the client’s definitions and segments.

  • ready is false until init() has completed successfully, and true thereafter.

  • close() stops background polling and releases change listeners.

The request made by init() and refresh() is equivalent to GET /v1/config?environment=<environment> with the client key in the Authorization: Bearer <clientKey> header. A non-successful response rejects the promise with an error containing the response status and status text.

typescript
import { FlagForgeClient } from "@flagforge/sdk";

const client = new FlagForgeClient({
  clientKey: process.env.FLAGFORGE_CLIENT_KEY!,
  baseUrl: "https://flags.example.com",
  environment: "production",
  pollIntervalMs: 30_000,
});

await client.init();

const context = {
  key: user.id,
  attributes: { plan: user.plan, country: user.country },
};

if (client.isEnabled("new-checkout", context)) {
  renderNewCheckout();
}

client.close();

Flag access methods

typescript
isEnabled(key: string, context?: EvaluationContext): boolean

getString(
  key: string,
  defaultValue: string,
  context?: EvaluationContext,
): string

getNumber(
  key: string,
  defaultValue: number,
  context?: EvaluationContext,
): number

getJson<T extends JsonValue>(
  key: string,
  defaultValue: T,
  context?: EvaluationContext,
): T

variation<T extends FlagValue>(
  key: string,
  defaultValue: T,
  context?: EvaluationContext,
): T

detailedVariation(
  key: string,
  context?: EvaluationContext,
): EvaluationResult | null
MethodBehavior
isEnabledEvaluates a boolean flag.
getStringEvaluates a string flag and returns the supplied default when the lookup cannot provide a usable result.
getNumberEvaluates a number flag and returns the supplied default when the lookup cannot provide a usable result.
getJsonEvaluates a JSON flag and returns the supplied default when the lookup cannot provide a usable result.
variationReturns the raw flag value using the supplied fallback when the flag is unknown or evaluation returns an ERROR reason.
detailedVariationReturns the complete evaluation result, or null when no flag with the requested key is present.

The optional context defaults to { key: "anonymous" }. Supply a stable subject key when targeting or percentage rollouts should distinguish users.

typescript
const enabled = client.isEnabled("new-checkout", context);
const theme = client.getString("checkout-theme", "control", context);
const maxItems = client.getNumber("max-cart-items", 10, context);
const options = client.getJson(
  "checkout-options",
  { compact: false },
  context,
);

const result = client.detailedVariation("new-checkout", context);

if (result) {
  console.log(result.variationKey, result.value, result.reason);
}

Note:

Flag checks are local after bootstrap. Use refresh() or configure pollIntervalMs when the application needs updated definitions. Call close() when the client is no longer needed.

Change listeners

typescript
onChange(listener: ChangeListener): () => void

onChange registers a callback for bootstrap refresh notifications and returns an unsubscribe function. Notifications occur after refresh() has replaced the definitions, including refreshes started by background polling.

typescript
const unsubscribe = client.onChange(() => {
  redrawFeatureGatedState();
});

await client.refresh();
unsubscribe();

Public types

ClientOptions

typescript
type ClientOptions = {
  clientKey: string;
  baseUrl: string;
  environment: string;
  pollIntervalMs?: number;
  fetch?: FetchLike;
};

clientKey, baseUrl, and environment are required. pollIntervalMs defaults to 0, which disables polling. fetch defaults to globalThis.fetch.

BootstrapPayload

typescript
type BootstrapPayload = {
  environment: string;
  flags: EvaluatableFlag[];
  segments: Segment[];
};

BootstrapPayload is the payload returned by GET /v1/config and consumed by init() and refresh(). It contains the environment key, evaluatable flag definitions, and reusable segments.

ChangeListener and FetchLike

typescript
type ChangeListener = () => void;

type FetchLike = (
  input: RequestInfo | URL,
  init?: RequestInit,
) => Promise<Response>;

ChangeListener is the callback accepted by onChange. FetchLike is a WHATWG fetch-compatible transport override for runtimes that do not provide globalThis.fetch or that need custom HTTP handling.

Re-exported evaluation types

The SDK re-exports these types from @flagforge/core, so applications can use one import surface:

TypePurpose
EvaluationContextEvaluation subject: { key: string; attributes?: Record<string, AttributeValue> }.
AttributeValuePrimitive context attribute value: string, number, or boolean.
EvaluationResultDetailed result containing variationKey, value, and reason.
EvaluationReasonEvaluation reason type, including reasons such as OFF, RULE_MATCH, and FALLTHROUGH.
FlagValueFlag value union used by typed getters and variation.
JsonValueJSON-serializable value used by JSON flags and rule comparisons.

When no context is supplied, the client uses { key: "anonymous" }. The context key is also the default stable key for percentage rollout bucketing.

Core evaluation engine

Reuse the pure evaluation engine directly when your application needs to evaluate EvaluatableFlag definitions outside the SDK client.

SDK client guide

See the adoption workflow for installing the SDK, bootstrapping an environment, and choosing typed getters or polling.