Switchflag
SDK

getFlag

Evaluate a feature flag using the singleton client. Requires init() to be called first.

Singleton pattern

The getFlag function provides a simpler API when you don't need multiple client instances. Call init() once at startup, then use getFlag() anywhere.

import { init, getFlag } from '@switchflag/sdk'

// Call once at app startup
init('sf_production_...')

// Use anywhere
const result = await getFlag<boolean>('new-feature', {
  userId: 'user-123',
})

init

function init(apiKey: string, baseUrl?: string): void

Initializes the default client. Must be called before any getFlag call.

ParameterTypeRequiredDescription
apiKeystringYesYour environment API key
baseUrlstringNoAPI base URL override (default: https://api.switchflag.dev)

getFlag

function getFlag<T>(
  key: string,
  context: EvaluationContext,
): Promise<EvaluationResult<T>>

Evaluates a feature flag using the default client.

ParameterTypeDescription
keystringThe flag key (e.g. new-checkout-flow)
contextEvaluationContextUser/request attributes for targeting rules

Throws if init() hasn't been called:

Error: Switchflag SDK not initialized. Call init() first.

EvaluationResult

interface EvaluationResult<T> {
  readonly value: T
  readonly reason: EvaluationReason
  readonly ruleId?: string
}

type EvaluationReason = 'default' | 'rule_match' | 'disabled' | 'not_found'
FieldTypeDescription
valueTThe resolved flag value
reasonEvaluationReasonWhy this value was chosen
ruleIdstring (optional)The ID of the matching rule, if reason is rule_match

Reason codes

ReasonDescription
defaultFlag is enabled, no targeting rules matched, returned the flag's default value
rule_matchA targeting rule matched — ruleId will be set
disabledFlag is disabled in this environment — returned the default value
not_foundFlag key doesn't exist, or the API returned an error

Type parameter

The <T> generic lets you type the result value:

// Boolean flag
const { value } = await getFlag<boolean>('dark-mode', ctx)
// value: boolean

// String flag
const { value } = await getFlag<string>('theme', ctx)
// value: string

// JSON flag
const { value } = await getFlag<{ maxItems: number }>('config', ctx)
// value: { maxItems: number }

The type parameter is for your convenience — the SDK doesn't validate the runtime type matches T.