How to Implement Feature Flags with Claude Code
Learn how to implement feature flags using Claude Code. Includes practical code examples and step-by-step guidance.
フィーチャーフラグとは
フィーチャーフラグ(Feature Flags)は、コードをデプロイした後でも機能のオン・オフを切り替えられる仕組みです。段階的なリリースやA/Bテストに不可欠な技術であり、Claude Codeを使えば堅牢な実装を素早く構築できます。
基本的なフィーチャーフラグシステム
> TypeScriptでフィーチャーフラグの管理システムを作って。
> ユーザー属性に基づく条件付きフラグにも対応して。
type FlagValue = boolean | string | number;
interface FlagRule {
conditions: Record<string, any>;
value: FlagValue;
}
interface FeatureFlag {
key: string;
defaultValue: FlagValue;
description: string;
rules: FlagRule[];
enabled: boolean;
}
class FeatureFlagManager {
private flags: Map<string, FeatureFlag> = new Map();
register(flag: FeatureFlag) {
this.flags.set(flag.key, flag);
}
evaluate(key: string, context: Record<string, any> = {}): FlagValue {
const flag = this.flags.get(key);
if (!flag || !flag.enabled) return flag?.defaultValue ?? false;
for (const rule of flag.rules) {
if (this.matchConditions(rule.conditions, context)) {
return rule.value;
}
}
return flag.defaultValue;
}
private matchConditions(conditions: Record<string, any>, context: Record<string, any>): boolean {
return Object.entries(conditions).every(([key, value]) => {
if (Array.isArray(value)) return value.includes(context[key]);
return context[key] === value;
});
}
isEnabled(key: string, context?: Record<string, any>): boolean {
return Boolean(this.evaluate(key, context));
}
}
React用フックの実装
> Reactコンポーネントでフィーチャーフラグを使うためのカスタムフックを作って。
import { createContext, useContext, ReactNode } from 'react';
const FlagContext = createContext<FeatureFlagManager | null>(null);
export function FlagProvider({ manager, children }: { manager: FeatureFlagManager; children: ReactNode }) {
return <FlagContext.Provider value={manager}>{children}</FlagContext.Provider>;
}
export function useFeatureFlag(key: string, context?: Record<string, any>): boolean {
const manager = useContext(FlagContext);
if (!manager) throw new Error('FlagProviderが必要です');
return manager.isEnabled(key, context);
}
// Usage example
function NewDashboard() {
const showNewUI = useFeatureFlag('new-dashboard', { userId: currentUser.id });
if (showNewUI) {
return <ModernDashboard />;
}
return <LegacyDashboard />;
}
パーセンテージロールアウト
特定の割合のユーザーにだけ機能を公開する段階的リリースも実装できます。
function percentageRollout(userId: string, percentage: number): boolean {
const hash = Array.from(userId).reduce((acc, char) => {
return ((acc << 5) - acc + char.charCodeAt(0)) | 0;
}, 0);
return Math.abs(hash % 100) < percentage;
}
// フラグ登録時にパーセンテージを設定
flagManager.register({
key: 'new-checkout',
defaultValue: false,
description: '新しいチェックアウトフロー',
enabled: true,
rules: [{
conditions: { rolloutPercentage: 20 },
value: true,
}],
});
フラグの管理画面
運用を楽にするため、フラグの状態をAPIで管理する仕組みも構築できます。
import express from 'express';
const router = express.Router();
router.get('/api/flags', (req, res) => {
const flags = Array.from(flagManager.getAllFlags()).map(([key, flag]) => ({
key,
enabled: flag.enabled,
description: flag.description,
}));
res.json(flags);
});
router.patch('/api/flags/:key', (req, res) => {
const { enabled } = req.body;
flagManager.setEnabled(req.params.key, enabled);
res.json({ success: true });
});
Summary
フィーチャーフラグを導入することで、安全な段階的リリースとリスクの低減が可能になります。Claude Codeなら条件分岐ロジックやReactフック、管理APIまで一貫して生成できます。A/Bテストとの組み合わせはA/Bテスト実装ガイドを、状態管理の設計は状態管理の記事を参照してください。
フィーチャーフラグの設計パターンについてはMartin Fowler - Feature Togglesが詳しいです。
Related Posts
10 Tips to Triple Your Productivity with Claude Code
Learn about 10 tips to triple your productivity using Claude Code. Practical tips and code examples included.
Canvas/WebGL Optimization with Claude Code
Learn about canvas/webgl optimization using Claude Code. Practical tips and code examples included.
Markdown Implementation with Claude Code
Learn about markdown implementation using Claude Code. Practical tips and code examples included.