Implement feature flags in Google Antigravity for gradual rollouts and A/B testing.
# Feature Flags for Google Antigravity
Implement feature flags for gradual rollouts and A/B testing.
## Database Schema
```sql
CREATE TABLE public.feature_flags (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
enabled BOOLEAN DEFAULT false,
percentage INT DEFAULT 100 CHECK (percentage >= 0 AND percentage <= 100),
conditions JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE public.feature_flag_overrides (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
flag_id UUID REFERENCES public.feature_flags(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
enabled BOOLEAN NOT NULL,
UNIQUE(flag_id, user_id)
);
```
## Feature Flag Service
```typescript
// lib/feature-flags.ts
import { createClient } from "@/lib/supabase/server";
const cache = new Map<string, { flag: any; expiresAt: number }>();
export async function getFlag(key: string) {
const cached = cache.get(key);
if (cached && Date.now() < cached.expiresAt) return cached.flag;
const supabase = createClient();
const { data } = await supabase.from("feature_flags").select("*").eq("key", key).single();
if (data) cache.set(key, { flag: data, expiresAt: Date.now() + 60000 });
return data;
}
export async function isEnabled(key: string, userId?: string): Promise<boolean> {
const flag = await getFlag(key);
if (!flag || !flag.enabled) return false;
if (userId) {
const supabase = createClient();
const { data: override } = await supabase.from("feature_flag_overrides").select("enabled").eq("flag_id", flag.id).eq("user_id", userId).single();
if (override) return override.enabled;
}
if (flag.percentage < 100) {
const hash = hashString(userId || "anon");
if ((hash % 100) >= flag.percentage) return false;
}
return true;
}
function hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); hash = hash & hash; }
return Math.abs(hash);
}
```
## React Hook
```typescript
// hooks/useFeatureFlag.ts
"use client";
import { useState, useEffect } from "react";
export function useFeatureFlag(key: string, defaultValue = false): boolean {
const [enabled, setEnabled] = useState(defaultValue);
useEffect(() => {
fetch(`/api/feature-flags/${key}`).then((r) => r.json()).then(({ enabled }) => setEnabled(enabled)).catch(() => {});
}, [key]);
return enabled;
}
```
## Component Wrapper
```typescript
// components/FeatureFlag.tsx
"use client";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
export function FeatureFlag({ flag, children, fallback = null }: { flag: string; children: React.ReactNode; fallback?: React.ReactNode }) {
const enabled = useFeatureFlag(flag);
return enabled ? <>{children}</> : <>{fallback}</>;
}
```
## API Route
```typescript
// app/api/feature-flags/[key]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { isEnabled } from "@/lib/feature-flags";
import { createClient } from "@/lib/supabase/server";
export async function GET(request: NextRequest, { params }: { params: { key: string } }) {
const supabase = createClient();
const { data: { user } } = await supabase.auth.getUser();
const enabled = await isEnabled(params.key, user?.id);
return NextResponse.json({ enabled });
}
```
## Admin UI
```typescript
// components/admin/FeatureFlagAdmin.tsx
"use client";
import { useState, useEffect } from "react";
import { createClient } from "@/lib/supabase/client";
export function FeatureFlagAdmin() {
const [flags, setFlags] = useState<any[]>([]);
const supabase = createClient();
useEffect(() => {
supabase.from("feature_flags").select("*").then(({ data }) => setFlags(data || []));
}, [supabase]);
const toggle = async (id: string, enabled: boolean) => {
await supabase.from("feature_flags").update({ enabled }).eq("id", id);
setFlags(flags.map((f) => (f.id === id ? { ...f, enabled } : f)));
};
return (
<div>
<h2>Feature Flags</h2>
{flags.map((f) => (
<div key={f.id}>
<span>{f.name}</span>
<input type="checkbox" checked={f.enabled} onChange={(e) => toggle(f.id, e.target.checked)} />
<span>{f.percentage}%</span>
</div>
))}
</div>
);
}
```
## Best Practices
1. **Cache Flags**: Reduce database queries
2. **Default Safe**: Default to disabled
3. **Consistent Hashing**: Use for percentage rollouts
4. **Kill Switch**: Have instant disable capability
5. **Cleanup**: Remove old flags after rolloutThis 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.