@flagvault/sdk v1.1.0
FlagVault JavaScript/TypeScript SDK
A lightweight JavaScript/TypeScript SDK that allows developers to integrate FlagVault's feature flag service into their applications. Feature flags let you enable/disable features remotely without deploying new code.
Table of Contents
- Installation
- Quick Start
- Project Overview
- Error Handling
- Configuration
- API Reference
- Use Cases
- Project Structure
- Development
- Requirements
Installation
npm install @flagvault/sdk
# or
yarn add @flagvault/sdkQuick Start
import FlagVaultSDK, { FlagVaultAuthenticationError, FlagVaultNetworkError } from '@flagvault/sdk';
// Initialize the SDK with your API key
// Environment is automatically detected from the key prefix:
// - 'live_' prefix = production environment
// - 'test_' prefix = test environment
const sdk = new FlagVaultSDK({
apiKey: 'live_your-api-key-here', // Use 'test_' for test environment
// Optional: custom timeout
// timeout: 10000
});
// Check if a feature flag is enabled
async function checkFeature() {
try {
const isEnabled = await sdk.isEnabled('my-feature-flag');
if (isEnabled) {
// Feature is enabled, run feature code
console.log('Feature is enabled!');
} else {
// Feature is disabled, run fallback code
console.log('Feature is disabled.');
}
} catch (error) {
if (error instanceof FlagVaultAuthenticationError) {
console.error('Invalid API credentials');
} else if (error instanceof FlagVaultNetworkError) {
console.error('Network connection failed');
} else {
console.error('Unexpected error:', error);
}
}
}
checkFeature();Project Overview
What It Is
FlagVault JavaScript/TypeScript SDK provides a simple, reliable way to integrate feature flags into your applications. Feature flags (also known as feature toggles) allow you to:
- Enable/disable features without deploying new code
- Perform A/B testing and gradual rollouts
- Create kill switches for problematic features
- Manage environment-specific features
Core Functionality
The SDK centers around one main class and method:
// Initialize once
const sdk = new FlagVaultSDK({ apiKey: 'live_your-api-key-here' });
// Use throughout your application
if (await sdk.isEnabled('new-checkout-flow')) {
showNewCheckout();
} else {
showOldCheckout();
}How It Works
- Initialize: Create SDK instance with API key from your FlagVault dashboard
- Environment Detection: Environment automatically determined from key prefix (live/test)
- Check Flag: Call
isEnabled('flag-key')anywhere in your code - HTTP Request: SDK makes secure GET request to FlagVault API
- Parse Response: Returns boolean from API response
- Handle Errors: Specific exceptions for different failure scenarios
Error Handling
The SDK provides specific exception types for different error scenarios:
import FlagVaultSDK, {
FlagVaultError,
FlagVaultAuthenticationError,
FlagVaultNetworkError,
FlagVaultAPIError,
} from '@flagvault/sdk';
try {
const isEnabled = await sdk.isEnabled('my-feature-flag');
} catch (error) {
if (error instanceof FlagVaultAuthenticationError) {
// Handle authentication errors (401, 403)
console.error('Check your API credentials');
} else if (error instanceof FlagVaultNetworkError) {
// Handle network errors (timeouts, connection issues)
console.error('Network connection problem');
} else if (error instanceof FlagVaultAPIError) {
// Handle API errors (500, malformed responses, etc.)
console.error('API error occurred');
} else {
// Handle invalid input (empty flag_key, etc.)
console.error('Invalid input provided');
}
}Exception Types
FlagVaultAuthenticationError: Invalid API credentials (401/403 responses)FlagVaultNetworkError: Connection timeouts, network failuresFlagVaultAPIError: Server errors, malformed responsesError: Invalid input parameters (empty flag keys, etc.)FlagVaultError: Base exception class for all SDK errors
Configuration
SDK Parameters
apiKey(required): Your FlagVault API key with environment prefixlive_prefix for production environmenttest_prefix for test environment
timeout(optional): Request timeout in milliseconds. Defaults to 10000
Environment Management
The SDK automatically detects the environment from your API key prefix:
// Production environment
const prodSdk = new FlagVaultSDK({
apiKey: 'live_abc123...' // Automatically uses production environment
});
// Test environment
const testSdk = new FlagVaultSDK({
apiKey: 'test_xyz789...' // Automatically uses test environment
});Getting API Credentials
- Sign up at FlagVault
- Create a new organization
- Go to Settings > API Credentials
- You'll see separate API keys for production and test environments
API Reference
new FlagVaultSDK(config)
Creates a new FlagVault SDK instance.
Parameters:
config.apiKey(string): Your FlagVault API key with environment prefix (live/test)config.timeout(number, optional): Request timeout in milliseconds
Throws:
Error: If apiKey is empty
isEnabled(flagKey: string): Promise<boolean>
Checks if a feature flag is enabled.
Parameters:
flagKey(string): The key/name of the feature flag
Returns:
Promise<boolean>: True if the flag is enabled, False otherwise
Throws:
Error: If flagKey is empty or nullFlagVaultAuthenticationError: If API credentials are invalidFlagVaultNetworkError: If network request failsFlagVaultAPIError: If API returns an error
Use Cases
1. A/B Testing
if (await sdk.isEnabled('new-ui-design')) {
renderNewDesign();
} else {
renderCurrentDesign();
}2. Gradual Rollouts
if (await sdk.isEnabled('premium-feature')) {
showPremiumFeatures();
} else {
showBasicFeatures();
}3. Kill Switches
if (await sdk.isEnabled('external-api-integration')) {
await callExternalAPI();
} else {
useCachedData(); // Fallback if external service has issues
}4. Environment-Specific Features
if (await sdk.isEnabled('debug-mode')) {
enableVerboseLogging();
showDebugInfo();
}Project Structure
sdk-js/
├── src/
│ └── index.ts # Main SDK implementation
├── tests/
│ ├── index.test.ts # Test suite
│ └── jest.setup.ts # Test configuration
├── dist/ # Compiled JavaScript
├── LICENSE # MIT license
├── README.md # This file
├── package.json # Package configuration
├── tsconfig.json # TypeScript configuration
└── jest.config.ts # Jest configurationKey Features
- 🚀 Simple: One method, clear API
- 🛡️ Reliable: Comprehensive error handling with custom exceptions
- 🔧 TypeScript: Full type safety and IDE support
- ✅ Well-Tested: Comprehensive test coverage
- ⚡ Production-Ready: Configurable timeouts, proper error types
- 📦 Lightweight: Zero dependencies (uses native fetch)
Testing Strategy
The SDK includes comprehensive tests covering:
- ✅ Initialization (valid/invalid credentials)
- ✅ Successful flag checks (enabled/disabled responses)
- ✅ Error scenarios (authentication, network, API errors)
- ✅ Edge cases (invalid JSON, missing fields, special characters)
- ✅ Timeout and connection handling
Requirements
- Node.js 16+ or modern browsers with fetch support
- TypeScript 4.0+ (for TypeScript projects)
Development
Setting up for development
# Clone the repository
git clone https://github.com/flagvault/sdk-js.git
cd sdk-js
# Install dependencies
npm installRunning tests
npm test
# With coverage
npm run test:coverageCode Quality
# Linting
npm run lint
# Type checking
npm run type-check
# Build
npm run buildBuilding the package
npm run buildLicense
MIT
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Support
Made with ❤️ by the FlagVault team