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): voidInitializes the default client. Must be called before any getFlag call.
| Parameter | Type | Required | Description |
|---|---|---|---|
apiKey | string | Yes | Your environment API key |
baseUrl | string | No | API 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.
| Parameter | Type | Description |
|---|---|---|
key | string | The flag key (e.g. new-checkout-flow) |
context | EvaluationContext | User/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'| Field | Type | Description |
|---|---|---|
value | T | The resolved flag value |
reason | EvaluationReason | Why this value was chosen |
ruleId | string (optional) | The ID of the matching rule, if reason is rule_match |
Reason codes
| Reason | Description |
|---|---|
default | Flag is enabled, no targeting rules matched, returned the flag's default value |
rule_match | A targeting rule matched — ruleId will be set |
disabled | Flag is disabled in this environment — returned the default value |
not_found | Flag 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.