Implement feature flag systems for gradual rollouts, A/B testing, and safe deployments with runtime configuration.
# Feature Flags for Google Antigravity
Feature flags enable controlled releases and experimentation. This guide covers feature flag implementation optimized for Google Antigravity and production deployments.
## Feature Flag Service
Build a comprehensive feature flag system:
```typescript
// lib/features/flags.ts
import { Redis } from "@upstash/redis";
interface FeatureFlag {
key: string;
enabled: boolean;
percentage?: number; // For gradual rollout
allowedUsers?: string[];
allowedGroups?: string[];
metadata?: Record<string, unknown>;
}
interface UserContext {
userId?: string;
email?: string;
groups?: string[];
attributes?: Record<string, string | number | boolean>;
}
const redis = new Redis({
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!,
});
const FLAG_PREFIX = "feature_flag:";
const flagCache = new Map<string, { flag: FeatureFlag; expiry: number }>();
const CACHE_TTL = 60000; // 1 minute
export async function getFlag(key: string): Promise<FeatureFlag | null> {
// Check memory cache first
const cached = flagCache.get(key);
if (cached && cached.expiry > Date.now()) {
return cached.flag;
}
// Fetch from Redis
const flag = await redis.get<FeatureFlag>(`${FLAG_PREFIX}${key}`);
if (flag) {
flagCache.set(key, { flag, expiry: Date.now() + CACHE_TTL });
}
return flag;
}
export async function isEnabled(
key: string,
context: UserContext = {}
): Promise<boolean> {
const flag = await getFlag(key);
if (!flag) return false;
if (!flag.enabled) return false;
// Check user allowlist
if (flag.allowedUsers?.length && context.userId) {
if (flag.allowedUsers.includes(context.userId)) {
return true;
}
}
// Check group allowlist
if (flag.allowedGroups?.length && context.groups?.length) {
const hasGroup = context.groups.some((g) => flag.allowedGroups!.includes(g));
if (hasGroup) return true;
}
// Percentage rollout
if (flag.percentage !== undefined && context.userId) {
const hash = hashString(context.userId + key);
const bucket = hash % 100;
return bucket < flag.percentage;
}
// If no conditions, use enabled status
return flag.enabled;
}
function hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return Math.abs(hash);
}
// Admin functions
export async function setFlag(flag: FeatureFlag): Promise<void> {
await redis.set(`${FLAG_PREFIX}${flag.key}`, flag);
flagCache.delete(flag.key);
}
export async function deleteFlag(key: string): Promise<void> {
await redis.del(`${FLAG_PREFIX}${key}`);
flagCache.delete(key);
}
```
## React Feature Flag Components
Create reusable feature flag components:
```typescript
// components/FeatureFlag.tsx
"use client";
import { createContext, useContext, useState, useEffect } from "react";
interface FeatureFlagContextType {
isEnabled: (key: string) => boolean;
isLoading: boolean;
}
const FeatureFlagContext = createContext<FeatureFlagContextType>({
isEnabled: () => false,
isLoading: true,
});
export function FeatureFlagProvider({
children,
userId,
}: {
children: React.ReactNode;
userId?: string;
}) {
const [flags, setFlags] = useState<Record<string, boolean>>({});
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function loadFlags() {
const response = await fetch("/api/features", {
headers: userId ? { "x-user-id": userId } : {},
});
const data = await response.json();
setFlags(data.flags);
setIsLoading(false);
}
loadFlags();
}, [userId]);
const isEnabled = (key: string) => flags[key] ?? false;
return (
<FeatureFlagContext.Provider value={{ isEnabled, isLoading }}>
{children}
</FeatureFlagContext.Provider>
);
}
export function useFeatureFlag(key: string): boolean {
const { isEnabled, isLoading } = useContext(FeatureFlagContext);
return !isLoading && isEnabled(key);
}
// Conditional render component
export function Feature({
flag,
children,
fallback = null,
}: {
flag: string;
children: React.ReactNode;
fallback?: React.ReactNode;
}) {
const isEnabled = useFeatureFlag(flag);
return <>{isEnabled ? children : fallback}</>;
}
// Usage
function Dashboard() {
return (
<div>
<Feature flag="new-dashboard" fallback={<OldDashboard />}>
<NewDashboard />
</Feature>
<Feature flag="beta-features">
<BetaFeaturesPanel />
</Feature>
</div>
);
}
```
## Server-Side Feature Flags
Implement server-side flag checking:
```typescript
// lib/features/server.ts
import { cookies } from "next/headers";
import { isEnabled } from "./flags";
export async function checkFeature(key: string): Promise<boolean> {
const cookieStore = await cookies();
const userId = cookieStore.get("userId")?.value;
return isEnabled(key, { userId });
}
// Usage in Server Component
async function ProductPage() {
const showNewPricing = await checkFeature("new-pricing-model");
return (
<div>
{showNewPricing ? (
<NewPricingTable />
) : (
<LegacyPricingTable />
)}
</div>
);
}
// API endpoint for client-side flags
// app/api/features/route.ts
export async function GET(request: Request) {
const userId = request.headers.get("x-user-id");
const flags = {
"new-dashboard": await isEnabled("new-dashboard", { userId: userId || undefined }),
"beta-features": await isEnabled("beta-features", { userId: userId || undefined }),
"dark-mode": await isEnabled("dark-mode", { userId: userId || undefined }),
};
return Response.json({ flags });
}
```
## Best Practices
When implementing feature flags in Antigravity projects, use consistent naming conventions, clean up old flags regularly, log flag evaluations for debugging, implement override mechanisms for testing, use percentage rollouts for gradual releases, cache flag values appropriately, and monitor flag usage metrics for decision making.This Feature Flags prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their feature flags implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Feature Flags projects, consider mentioning your framework version, coding style, and any specific libraries you're using.