LaunchDarkly SDK: Feature Flag Implementation
Welcome to TopperBlog! 👋
I'm a tech content creator passionate about helping developers level up their careers and master cutting-edge technologies.
🎯 What I Write About:
• AI/ML Engineering & LLMs
• Web3 & Blockchain Development
• System Design & Architecture
• Interview Preparation (FAANG)
• Freelancing & Remote Work
• Modern Tech Stacks (Next.js, React, Rust, TypeScript)
• Performance Optimization & Best Practices
💼 Mission: Sharing practical, actionable insights that accelerate your tech career and maximize your earning potential.
📚 15+ In-Depth Guides covering everything from earning $10k/month as a freelancer to cracking FAANG interviews.
🌐 Let's connect and grow together in this amazing tech journey!
#TechBlogger #SoftwareEngineering #CareerGrowth #WebDevelopment #AIEngineering
LaunchDarkly SDK: Feature Flag Implementation Guide
Overview
LaunchDarkly is a feature management platform that enables teams to control feature rollouts, A/B testing, and gradual deployments without code changes. The SDK provides real-time feature flag evaluation.
Core Concepts
Feature Flags
- Boolean Flags: Simple on/off toggles
- Multivariate Flags: Multiple variations (strings, numbers, JSON objects)
- Targeting Rules: Segment users based on attributes
- Rollout Percentages: Gradual user exposure
Key Components
- SDK Client: Initializes connection to LaunchDarkly
- User Context: Identifies and attributes users
- Flag Evaluation: Retrieves flag values for users
- Event Tracking: Sends analytics to LaunchDarkly
Implementation Steps
1. Installation
npm install launchdarkly-js-client-sdk
# or
yarn add launchdarkly-js-client-sdk
2. Initialize SDK
import * as LDClient from 'launchdarkly-js-client-sdk';
const client = LDClient.initialize('YOUR_CLIENT_SIDE_ID', {
user: {
key: 'user-123',
name: 'John Doe',
email: 'john@example.com',
custom: {
plan: 'premium',
region: 'us-west'
}
}
});
// Wait for SDK to be ready
await client.waitForInitialization();
3. Evaluate Flags
// Boolean flag
const showNewFeature = client.variation('new-feature-flag', false);
// Multivariate flag
const uiTheme = client.variation('ui-theme', 'light');
// With details
const flagDetail = client.variationDetail('feature-flag', false);
console.log(flagDetail.value);
console.log(flagDetail.reason); // Why this value was returned
4. Listen for Changes
client.on('change:feature-flag', (newValue, oldValue) => {
console.log(`Flag changed from ${oldValue} to ${newValue}`);
// Update UI reactively
});
client.on('change', () => {
console.log('Any flag changed');
});
5. Update User Context
await client.identify({
key: 'user-456',
name: 'Jane Smith',
custom: {
plan: 'enterprise'
}
});
React Integration Example
import { useFlags, useLDClient } from 'launchdarkly-react-client-sdk';
function App() {
const { newFeature, betaUI } = useFlags();
const ldClient = useLDClient();
return (
<div>
{newFeature && <NewFeatureComponent />}
{betaUI ? <BetaUI /> : <StandardUI />}
<button onClick={() => ldClient.track('user-action')}>
Track Event
</button>
</div>
);
}
Advanced Features
Targeting Rules
// In LaunchDarkly dashboard, create rules like:
// - Target specific users
// - Target by custom attributes (plan, region, etc.)
// - Percentage rollouts
// - Scheduled rollouts
A/B Testing
const variant = client.variation('ab-test-flag', 'control');
if (variant === 'treatment') {
// Show treatment version
} else {
// Show control version
}
// Track conversion
client.track('purchase', { value: 99.99 });
Custom Events
client.track('feature-used', {
featureName: 'new-dashboard',
timestamp: Date.now()
});
client.track('conversion', { revenue: 150 }, 150);
Best Practices
- Initialize Early: Set up SDK before rendering UI
- Handle Offline: Provide sensible defaults
- Segment Users: Use custom attributes for targeting
- Track Events: Monitor feature adoption
- Clean Up: Remove listeners when components unmount
- Cache Flags: Store evaluated flags for performance
- Error Handling: Implement fallbacks for SDK failures
Common Patterns
Feature Rollout
// Start with 0%, gradually increase to 100%
// LaunchDarkly handles percentage-based targeting
const isEnabled = client.variation('gradual-rollout', false);
Kill Switch
const isServiceDown = client.variation('kill-switch', false);
if (isServiceDown) {
return <MaintenancePage />;
}
Experimentation
const experiment = client.variation('experiment-flag', 'control');
trackExperimentEvent(experiment);
Troubleshooting
| Issue | Solution |
| Flags not updating | Ensure waitForInitialization() completes |
| Wrong flag values | Verify user context attributes match targeting rules |
| Events not tracked | Check network connectivity and event tracking enabled |
| Performance issues | Implement flag caching and lazy evaluation |
Resources
This implementation enables powerful feature management with minimal code changes and maximum control over deployments.