Flagdeck
Pricing
Docs
Get Started

Docs

Docs


SDKs

  • JavaScript
    • Getting Started
    • Value Types
    • Evaluation Context
    • Configuration
    • Real Time Updates
    • Error Handling
    • Middleware
    • Offline Mode
    • API Reference
  • React

API Reference

  • Authentication
  • Flags
  • Environments
  • Projects

"use client"

API Reference

This page provides a comprehensive reference of the Flagdeck JavaScript SDK API.

Flagdeck Class

The main entry point to the SDK is the Flagdeck class.

Constructor

constructor(config: FlagdeckConfig)

Creates a new instance of the Flagdeck client.

Parameters:

Example:

import { Flagdeck } from '@flagdeck/js';

const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  enableCache: true,
  debug: false
});

isEnabled

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 flag
  • context (optional): EvaluationContext - Context for targeting and personalization
  • defaultValue (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

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 flag
  • context (optional): EvaluationContext - Context for targeting and personalization
  • defaultValue (optional): T - Value to use if evaluation fails

Type 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

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 evaluate
  • context (optional): EvaluationContext - Context for targeting and personalization
  • defaultValue (optional): T - Default value to use for any flag that fails to evaluate

Returns: 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

evaluateFlag(
  flagKey: string,
  context?: Partial<EvaluationContext>
): Promise<EvaluationResult>

Evaluates a flag with full evaluation details.

Parameters:

  • flagKey: string - The unique identifier of the flag
  • context (optional): EvaluationContext - Context for targeting and personalization

Returns: 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

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 evaluate
  • context (optional): EvaluationContext - Context for targeting and personalization

Returns: 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

use(middleware: EvaluationMiddleware): Flagdeck

Adds an evaluation middleware to the client.

Parameters:

Returns: The Flagdeck instance for chaining

Example:

flagdeck.use({
  name: 'LoggingMiddleware',
  beforeEvaluation: (flagKey, context) => {
    console.log(`Evaluating flag: ${flagKey}`);
  }
});

clearCache

clearCache(): void

Clears the evaluation cache.

Example:

// Clear cache after user logs out
function handleLogout() {
  flagdeck.clearCache();
  // ...other logout logic
}

saveForOffline

saveForOffline(
  flagKey: string,
  result: EvaluationResult
): Promise<void>

Saves a flag evaluation result for offline use.

Parameters:

  • flagKey: string - The unique identifier of the flag
  • result: EvaluationResult - The evaluation result to save

Example:

await flagdeck.saveForOffline('feature-a', {
  flagKey: 'feature-a',
  value: true,
  source: 'api',
  timestamp: Date.now()
});

saveMultipleForOffline

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 EvaluationResult

Example:

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

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

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

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);
  };
}, []);

Type Definitions

FlagdeckConfig

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:

PropertyTypeDefaultDescription
apiKeystringrequiredYour Flagdeck API key
enableCachebooleantrueEnable in-memory caching
cacheTimeoutnumber30000Cache timeout in milliseconds
timeoutnumber5000Network request timeout in milliseconds
retryConfigRetryConfigSee belowNetwork retry configuration
debugbooleanfalseEnable debug logging
enableOfflineModebooleanfalseEnable offline storage
enableAnalyticsbooleantrueEnable usage analytics
onErrorfunctionundefinedGlobal error handler
defaultFlagValueanyfalseDefault value when evaluation fails
sdkPlatformstringauto-detectedPlatform type ('web', 'server', 'mobile')

RetryConfig

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
}

EvaluationContext

interface EvaluationContext {
  userId?: string;
  sessionId?: string;
  attributes?: Record<string, any>;
}

Properties:

  • userId: (optional) Unique identifier for the user
  • sessionId: (optional) Identifier for the current session
  • attributes: (optional) Additional attributes for targeting

EvaluationResult

interface 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 flag
  • value: The evaluated value of the flag
  • source: Where the value came from
  • reason: (optional) Human-readable explanation
  • timestamp: When the evaluation occurred (epoch milliseconds)
  • error: (optional) Error information if evaluation failed

BulkEvaluationResponse

interface 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 results
  • metadata: Information about the bulk evaluation request

EvaluationMiddleware

interface 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 middleware
  • beforeEvaluation: (optional) Function called before flag evaluation
  • afterEvaluation: (optional) Function called after flag evaluation
  • onError: (optional) Function called when an error occurs

Error Codes

The SDK provides these error codes:

CodeDescription
NETWORK_ERRORFailed to connect to the Flagdeck API
AUTHENTICATION_ERRORInvalid API key or authentication issue
EVALUATION_ERRORError during flag evaluation logic
TIMEOUT_ERRORRequest timeout occurred
CONFIGURATION_ERRORInvalid SDK configuration
INVALID_FLAG_KEYInvalid or missing flag key
OFFLINE_ERRORError with offline storage
UNKNOWN_ERRORUnidentified error

Advanced Types

SdkPlatform

type SdkPlatform = 'web' | 'server' | 'mobile';

ApiResponse

interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: {
    code: string;
    message: string;
  };
}

BulkEvaluationRequest

interface BulkEvaluationRequest {
  flags: string[];
  context?: Partial<EvaluationContext>;
}

Constants

Default Configuration

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
};

Environment Detection

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.

Get Started
Flagdeck

Modern feature flag management platform to help you deploy with confidence.

Product

FeaturesPricingDocumentation

© 2025 Flagdeck. All rights reserved.