Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Feature Flags for Antigravity

Feature Flags for Antigravity

Implement feature flag systems for gradual rollouts, A/B testing, and safe deployments with runtime configuration.

Feature FlagsA/B TestingDeploymentTypeScriptReact
by Antigravity Team
⭐0Stars
👁️1Views
.antigravity
# 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.

When to Use This Prompt

This Feature Flags prompt is ideal for developers working on:

  • Feature Flags applications requiring modern best practices and optimal performance
  • Projects that need production-ready Feature Flags code with proper error handling
  • Teams looking to standardize their feature flags development workflow
  • Developers wanting to learn industry-standard Feature Flags patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Feature Flags code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Feature Flags prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...