"use client"
This page provides a comprehensive reference of the Flagdeck JavaScript SDK API.
The main entry point to the SDK is the Flagdeck
class.
constructor(config: FlagdeckConfig)
Creates a new instance of the Flagdeck client.
Parameters:
config
: FlagdeckConfig - Configuration object for the SDKExample:
import { Flagdeck } from '@flagdeck/js';
const flagdeck = new Flagdeck({
apiKey: 'your-api-key',
enableCache: true,
debug: false
});
isEnabled(
flagKey: string,
context?: Partial<EvaluationContext>,
defaultValue?: boolean
): Promise<boolean>
Checks if a feature flag is enabled.
Parameters:
flagKey
: string - The unique identifier of the flagcontext
(optional): EvaluationContext - Context for targeting and personalizationdefaultValue
(optional): boolean - Value to use if evaluation fails (defaults to false)Returns: Promise resolving to a boolean indicating if the flag is enabled
Example:
const isEnabled = await flagdeck.isEnabled('new-feature', {
userId: 'user-123',
attributes: { country: 'US' }
});
if (isEnabled) {
// Feature is enabled
}
getValue<T = any>(
flagKey: string,
context?: Partial<EvaluationContext>,
defaultValue?: T
): Promise<T>
Gets the value of a flag with the specified type.
Parameters:
flagKey
: string - The unique identifier of the flagcontext
(optional): EvaluationContext - Context for targeting and personalizationdefaultValue
(optional): T - Value to use if evaluation failsType Parameters:
T
: The expected type of the flag value (boolean, string, number, object, etc.)Returns: Promise resolving to the flag value of type T
Example:
// String value
const variant = await flagdeck.getValue('experiment', context, 'control');
// Number value
const limit = await flagdeck.getValue('rate-limit', context, 100);
// Object value with TypeScript
interface ApiConfig {
url: string;
timeout: number;
}
const config = await flagdeck.getValue<ApiConfig>('api-config', context, {
url: 'https://api.default.com',
timeout: 5000
});
getValues<T = any>(
flagKeys: string[],
context?: Partial<EvaluationContext>,
defaultValue?: T
): Promise<Record<string, T>>
Gets multiple flag values in a single request.
Parameters:
flagKeys
: string[] - Array of flag keys to evaluatecontext
(optional): EvaluationContext - Context for targeting and personalizationdefaultValue
(optional): T - Default value to use for any flag that fails to evaluateReturns: Promise resolving to an object mapping flag keys to their values
Example:
const values = await flagdeck.getValues([
'feature-a',
'feature-b',
'limit'
], context);
console.log(values['feature-a']); // boolean
console.log(values['limit']); // number
evaluateFlag(
flagKey: string,
context?: Partial<EvaluationContext>
): Promise<EvaluationResult>
Evaluates a flag with full evaluation details.
Parameters:
flagKey
: string - The unique identifier of the flagcontext
(optional): EvaluationContext - Context for targeting and personalizationReturns: Promise resolving to an EvaluationResult object
Example:
const result = await flagdeck.evaluateFlag('new-feature', context);
console.log(`Value: ${result.value}`);
console.log(`Source: ${result.source}`);
console.log(`Reason: ${result.reason}`);
evaluateBulk(
flagKeys: string[],
context?: Partial<EvaluationContext>
): Promise<BulkEvaluationResponse>
Evaluates multiple flags with full details in a single request.
Parameters:
flagKeys
: string[] - Array of flag keys to evaluatecontext
(optional): EvaluationContext - Context for targeting and personalizationReturns: Promise resolving to a BulkEvaluationResponse object
Example:
const response = await flagdeck.evaluateBulk([
'feature-a',
'feature-b'
], context);
console.log(response.results['feature-a'].value);
console.log(response.metadata.totalFlags);
use(middleware: EvaluationMiddleware): Flagdeck
Adds an evaluation middleware to the client.
Parameters:
middleware
: EvaluationMiddleware - Middleware object to addReturns: The Flagdeck instance for chaining
Example:
flagdeck.use({
name: 'LoggingMiddleware',
beforeEvaluation: (flagKey, context) => {
console.log(`Evaluating flag: ${flagKey}`);
}
});
clearCache(): void
Clears the evaluation cache.
Example:
// Clear cache after user logs out
function handleLogout() {
flagdeck.clearCache();
// ...other logout logic
}
saveForOffline(
flagKey: string,
result: EvaluationResult
): Promise<void>
Saves a flag evaluation result for offline use.
Parameters:
flagKey
: string - The unique identifier of the flagresult
: EvaluationResult - The evaluation result to saveExample:
await flagdeck.saveForOffline('feature-a', {
flagKey: 'feature-a',
value: true,
source: 'api',
timestamp: Date.now()
});
saveMultipleForOffline(
flags: Record<string, EvaluationResult>
): Promise<void>
Saves multiple flag evaluation results for offline use.
Parameters:
flags
: Record<string, EvaluationResult>
- Object mapping flag keys to EvaluationResultExample:
await flagdeck.saveMultipleForOffline({
'feature-a': {
flagKey: 'feature-a',
value: true,
source: 'api',
timestamp: Date.now()
},
'feature-b': {
flagKey: 'feature-b',
value: 'variant-1',
source: 'api',
timestamp: Date.now()
}
});
clearOfflineStorage(): Promise<void>
Clears all stored offline flag values.
Example:
// Clear offline storage when user logs out
async function handleLogout() {
await flagdeck.clearOfflineStorage();
// ...other logout logic
}
flushAnalytics(): Promise<void>
Manually flushes any pending analytics events.
Example:
// Flush analytics before the app closes
async function handleAppClose() {
await flagdeck.flushAnalytics();
// ...other cleanup
}
destroy(): Promise<void>
Cleans up resources when the client is no longer needed.
Example:
// Clean up when component unmounts
useEffect(() => {
return () => {
flagdeck.destroy().catch(console.error);
};
}, []);
interface FlagdeckConfig {
// Required
apiKey: string;
// Optional
enableCache?: boolean;
cacheTimeout?: number;
timeout?: number;
retryConfig?: RetryConfig;
debug?: boolean;
enableOfflineMode?: boolean;
enableAnalytics?: boolean;
onError?: (error: Error, flagKey?: string) => void;
defaultFlagValue?: any;
sdkPlatform?: SdkPlatform;
}
Properties:
Property | Type | Default | Description |
---|---|---|---|
apiKey | string | required | Your Flagdeck API key |
enableCache | boolean | true | Enable in-memory caching |
cacheTimeout | number | 30000 | Cache timeout in milliseconds |
timeout | number | 5000 | Network request timeout in milliseconds |
retryConfig | RetryConfig | See below | Network retry configuration |
debug | boolean | false | Enable debug logging |
enableOfflineMode | boolean | false | Enable offline storage |
enableAnalytics | boolean | true | Enable usage analytics |
onError | function | undefined | Global error handler |
defaultFlagValue | any | false | Default value when evaluation fails |
sdkPlatform | string | auto-detected | Platform type ('web', 'server', 'mobile') |
interface RetryConfig {
attempts: number;
delay: number;
maxDelay: number;
}
Default:
{
attempts: 3, // Maximum number of retry attempts
delay: 1000, // Initial delay in milliseconds
maxDelay: 5000 // Maximum delay between retries
}
interface EvaluationContext {
userId?: string;
sessionId?: string;
attributes?: Record<string, any>;
}
Properties:
userId
: (optional) Unique identifier for the usersessionId
: (optional) Identifier for the current sessionattributes
: (optional) Additional attributes for targetinginterface EvaluationResult {
flagKey: string;
value: any;
source: 'api' | 'cache' | 'offline' | 'error';
reason?: string;
timestamp: number;
error?: {
code: string;
message: string;
};
}
Properties:
flagKey
: The identifier of the flagvalue
: The evaluated value of the flagsource
: Where the value came fromreason
: (optional) Human-readable explanationtimestamp
: When the evaluation occurred (epoch milliseconds)error
: (optional) Error information if evaluation failedinterface BulkEvaluationResponse {
results: Record<string, EvaluationResult>;
metadata: {
totalFlags: number;
successCount: number;
errorCount: number;
timeTaken: number;
cacheHits: number;
error?: {
code: string;
message: string;
};
};
}
Properties:
results
: Object mapping flag keys to their evaluation resultsmetadata
: Information about the bulk evaluation requestinterface EvaluationMiddleware {
name: string;
beforeEvaluation?: (
flagKey: string,
context?: Partial<EvaluationContext>
) => void | Partial<EvaluationContext> | Promise<void | Partial<EvaluationContext>>;
afterEvaluation?: (
flagKey: string,
result: EvaluationResult,
context?: Partial<EvaluationContext>
) => EvaluationResult | Promise<EvaluationResult>;
onError?: (
error: Error,
flagKey?: string
) => void | Promise<void>;
}
Properties:
name
: Identifier for the middlewarebeforeEvaluation
: (optional) Function called before flag evaluationafterEvaluation
: (optional) Function called after flag evaluationonError
: (optional) Function called when an error occursThe SDK provides these error codes:
Code | Description |
---|---|
NETWORK_ERROR | Failed to connect to the Flagdeck API |
AUTHENTICATION_ERROR | Invalid API key or authentication issue |
EVALUATION_ERROR | Error during flag evaluation logic |
TIMEOUT_ERROR | Request timeout occurred |
CONFIGURATION_ERROR | Invalid SDK configuration |
INVALID_FLAG_KEY | Invalid or missing flag key |
OFFLINE_ERROR | Error with offline storage |
UNKNOWN_ERROR | Unidentified error |
type SdkPlatform = 'web' | 'server' | 'mobile';
interface ApiResponse<T> {
success: boolean;
data: T;
error?: {
code: string;
message: string;
};
}
interface BulkEvaluationRequest {
flags: string[];
context?: Partial<EvaluationContext>;
}
const DEFAULT_CONFIG = {
enableCache: true,
cacheTimeout: 30000, // 30 seconds
timeout: 5000, // 5 seconds
retryConfig: {
attempts: 3,
delay: 1000,
maxDelay: 5000
},
debug: false,
enableOfflineMode: false,
enableAnalytics: true
};
The SDK automatically detects the environment:
// Environment is automatically detected as:
// - 'web' for browsers
// - 'server' for Node.js
// - 'mobile' for React Native
You can override this with the sdkPlatform
option if needed.
Start using Flagdeck today
Simple feature flag management for modern development teams.
Product
© 2025 Flagdeck. All rights reserved.