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
Edge Computing Patterns

Edge Computing Patterns

Build edge-first applications with Cloudflare Workers and Vercel Edge

edgecloudflarevercelserverless
by antigravity-team
⭐0Stars
.antigravity
# Edge Computing Patterns for Google Antigravity

Deploy compute closer to users with edge functions for optimal performance using Google Antigravity IDE.

## Cloudflare Workers Setup

```typescript
// src/index.ts
import { Hono } from "hono";
import { cors } from "hono/cors";
import { cache } from "hono/cache";
import { logger } from "hono/logger";

type Env = {
  KV: KVNamespace;
  DB: D1Database;
  R2: R2Bucket;
  AI: Ai;
};

const app = new Hono<{ Bindings: Env }>();

// Middleware
app.use("*", logger());
app.use("/api/*", cors());

// Cache static responses
app.get(
  "/api/products",
  cache({ cacheName: "products", cacheControl: "max-age=3600" }),
  async (c) => {
    const products = await c.env.DB.prepare(
      "SELECT * FROM products WHERE status = ? LIMIT 100"
    ).bind("active").all();
    
    return c.json(products.results);
  }
);

// Edge-side personalization
app.get("/api/recommendations", async (c) => {
  const userId = c.req.header("X-User-ID");
  const country = c.req.cf?.country || "US";
  
  // Check cache first
  const cacheKey = `recs:${userId}:${country}`;
  const cached = await c.env.KV.get(cacheKey, "json");
  if (cached) return c.json(cached);
  
  // Generate recommendations based on location
  const products = await c.env.DB.prepare(`
    SELECT * FROM products 
    WHERE region = ? OR region = 'global'
    ORDER BY popularity DESC
    LIMIT 10
  `).bind(country).all();
  
  // Cache for 5 minutes
  await c.env.KV.put(cacheKey, JSON.stringify(products.results), {
    expirationTtl: 300
  });
  
  return c.json(products.results);
});

// AI at the edge
app.post("/api/summarize", async (c) => {
  const { text } = await c.req.json();
  
  const response = await c.env.AI.run("@cf/meta/llama-2-7b-chat-int8", {
    messages: [
      { role: "system", content: "Summarize the following text concisely." },
      { role: "user", content: text }
    ]
  });
  
  return c.json({ summary: response.response });
});

// Image optimization with R2
app.get("/images/:key", async (c) => {
  const key = c.req.param("key");
  const width = parseInt(c.req.query("w") || "800");
  
  const object = await c.env.R2.get(key);
  if (!object) return c.notFound();
  
  // Return with caching headers
  return new Response(object.body, {
    headers: {
      "Content-Type": object.httpMetadata?.contentType || "image/jpeg",
      "Cache-Control": "public, max-age=31536000, immutable",
      "CDN-Cache-Control": "max-age=31536000"
    }
  });
});

// Geolocation-based routing
app.get("/api/nearest-store", async (c) => {
  const { latitude, longitude, country, city } = c.req.cf || {};
  
  const stores = await c.env.DB.prepare(`
    SELECT *, 
      (3959 * acos(cos(radians(?)) * cos(radians(lat)) * 
       cos(radians(lng) - radians(?)) + sin(radians(?)) * sin(radians(lat)))) AS distance
    FROM stores
    WHERE country = ?
    ORDER BY distance
    LIMIT 5
  `).bind(latitude, longitude, latitude, country).all();
  
  return c.json({
    location: { city, country, latitude, longitude },
    stores: stores.results
  });
});

export default app;
```

## Vercel Edge Middleware

```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { geolocation, ipAddress } from "@vercel/edge";

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
};

export function middleware(request: NextRequest) {
  const geo = geolocation(request);
  const ip = ipAddress(request);
  
  // Add geo headers for downstream use
  const response = NextResponse.next();
  response.headers.set("x-geo-country", geo.country || "US");
  response.headers.set("x-geo-city", geo.city || "Unknown");
  response.headers.set("x-geo-region", geo.region || "Unknown");
  
  // A/B testing at the edge
  const bucket = request.cookies.get("ab-bucket")?.value || 
    (Math.random() < 0.5 ? "control" : "variant");
  
  if (!request.cookies.has("ab-bucket")) {
    response.cookies.set("ab-bucket", bucket, {
      maxAge: 60 * 60 * 24 * 30, // 30 days
      httpOnly: true
    });
  }
  
  response.headers.set("x-ab-bucket", bucket);
  
  // Rate limiting
  const rateLimit = await checkRateLimit(ip);
  if (!rateLimit.success) {
    return new NextResponse("Too Many Requests", {
      status: 429,
      headers: {
        "Retry-After": rateLimit.retryAfter.toString(),
        "X-RateLimit-Limit": rateLimit.limit.toString(),
        "X-RateLimit-Remaining": "0"
      }
    });
  }
  
  // Bot detection
  const userAgent = request.headers.get("user-agent") || "";
  if (isBot(userAgent) && !isGoodBot(userAgent)) {
    return new NextResponse("Forbidden", { status: 403 });
  }
  
  // Redirect based on country
  const pathname = request.nextUrl.pathname;
  if (pathname === "/" && geo.country && geo.country !== "US") {
    const localizedPath = `/${geo.country.toLowerCase()}`;
    if (hasLocalizedContent(geo.country)) {
      return NextResponse.redirect(new URL(localizedPath, request.url));
    }
  }
  
  return response;
}

async function checkRateLimit(ip: string) {
  // Use Vercel KV or Upstash Redis for rate limiting
  const key = `rate:${ip}`;
  // Implementation details...
  return { success: true, limit: 100, remaining: 99, retryAfter: 0 };
}

function isBot(userAgent: string): boolean {
  return /bot|crawler|spider|crawling/i.test(userAgent);
}

function isGoodBot(userAgent: string): boolean {
  return /googlebot|bingbot|yandex/i.test(userAgent);
}

function hasLocalizedContent(country: string): boolean {
  return ["GB", "DE", "FR", "ES", "JP"].includes(country);
}
```

## Edge API Routes

```typescript
// app/api/edge/route.ts
import { NextRequest } from "next/server";

export const runtime = "edge";

export async function GET(request: NextRequest) {
  const start = Date.now();
  
  // Get user location from edge
  const country = request.geo?.country || "US";
  const city = request.geo?.city || "Unknown";
  
  // Fetch from edge-optimized data source
  const data = await fetch("https://api.example.com/data", {
    headers: { "X-Country": country },
    next: { revalidate: 60 }
  }).then(r => r.json());
  
  return Response.json({
    data,
    meta: {
      country,
      city,
      latency: Date.now() - start,
      region: process.env.VERCEL_REGION
    }
  }, {
    headers: {
      "Cache-Control": "public, s-maxage=60, stale-while-revalidate=300"
    }
  });
}
```

## Best Practices

1. **Cache aggressively** at the edge
2. **Use KV storage** for session and config data
3. **Implement geo-routing** for localization
4. **Run A/B tests** at the edge
5. **Add rate limiting** before origin
6. **Optimize images** with edge transformations
7. **Monitor edge performance** with analytics

Google Antigravity helps build edge-first architectures with intelligent caching strategies.

When to Use This Prompt

This edge prompt is ideal for developers working on:

  • edge applications requiring modern best practices and optimal performance
  • Projects that need production-ready edge code with proper error handling
  • Teams looking to standardize their edge development workflow
  • Developers wanting to learn industry-standard edge 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 edge 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 edge 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 edge 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 edge projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...