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
Cloudflare Workers Edge API

Cloudflare Workers Edge API

Edge computing with Cloudflare Workers for Google Antigravity projects including KV storage, D1 database, and R2 object storage.

cloudflareworkersedgeserverlessd1
by Antigravity Team
⭐0Stars
.antigravity
# Cloudflare Workers Edge API for Google Antigravity

Build performant edge applications with Cloudflare Workers in your Google Antigravity IDE projects. This comprehensive guide covers Workers, KV storage, D1 database, and R2 object storage optimized for Gemini 3 agentic development.

## Worker Configuration

Set up Cloudflare Workers with Wrangler:

```typescript
// wrangler.toml configuration
name = "antigravity-api"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[vars]
ENVIRONMENT = "production"

[[kv_namespaces]]
binding = "CACHE"
id = "your-kv-namespace-id"

[[d1_databases]]
binding = "DB"
database_name = "antigravity"
database_id = "your-d1-database-id"

[[r2_buckets]]
binding = "STORAGE"
bucket_name = "antigravity-assets"
```

## Worker Entry Point

Create the main worker with routing using Hono:

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

type Bindings = {
  CACHE: KVNamespace;
  DB: D1Database;
  STORAGE: R2Bucket;
  ENVIRONMENT: string;
};

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

// Middleware
app.use('*', cors({
  origin: ['https://antigravityai.directory', 'http://localhost:3000'],
  credentials: true,
}));

// Cache GET requests
app.get('/api/prompts/*', cache({
  cacheName: 'prompts-cache',
  cacheControl: 'public, max-age=60',
}));

// List prompts with pagination
app.get('/api/prompts', async (c) => {
  const { page = '1', limit = '20', search } = c.req.query();
  const offset = (Number(page) - 1) * Number(limit);

  let query = 'SELECT * FROM prompts WHERE is_approved = 1';
  const params: unknown[] = [];

  if (search) {
    query += ' AND (title LIKE ? OR description LIKE ?)';
    params.push(`%${search}%`, `%${search}%`);
  }

  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(Number(limit), offset);

  const { results } = await c.env.DB.prepare(query).bind(...params).all();
  
  const { results: countResults } = await c.env.DB.prepare(
    'SELECT COUNT(*) as total FROM prompts WHERE is_approved = 1'
  ).all();
  
  const total = (countResults[0] as { total: number }).total;

  return c.json({
    prompts: results,
    pagination: {
      page: Number(page),
      limit: Number(limit),
      total,
      totalPages: Math.ceil(total / Number(limit)),
    },
  });
});

// Get single prompt with caching
app.get('/api/prompts/:slug', async (c) => {
  const slug = c.req.param('slug');
  
  // Check cache first
  const cached = await c.env.CACHE.get(`prompt:${slug}`);
  if (cached) {
    return c.json(JSON.parse(cached));
  }

  const { results } = await c.env.DB.prepare(
    'SELECT * FROM prompts WHERE slug = ? AND is_approved = 1'
  ).bind(slug).all();

  if (results.length === 0) {
    return c.json({ error: 'Prompt not found' }, 404);
  }

  const prompt = results[0];

  // Cache for 5 minutes
  await c.env.CACHE.put(`prompt:${slug}`, JSON.stringify(prompt), {
    expirationTtl: 300,
  });

  // Increment view count asynchronously
  c.executionCtx.waitUntil(
    c.env.DB.prepare(
      'UPDATE prompts SET view_count = view_count + 1 WHERE slug = ?'
    ).bind(slug).run()
  );

  return c.json(prompt);
});

// File upload to R2
app.post('/api/uploads', async (c) => {
  const formData = await c.req.formData();
  const file = formData.get('file') as File;

  if (!file) {
    return c.json({ error: 'No file provided' }, 400);
  }

  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    return c.json({ error: 'Invalid file type' }, 400);
  }

  if (file.size > 10 * 1024 * 1024) {
    return c.json({ error: 'File too large' }, 400);
  }

  const key = `uploads/${crypto.randomUUID()}-${file.name}`;
  const buffer = await file.arrayBuffer();

  await c.env.STORAGE.put(key, buffer, {
    httpMetadata: { contentType: file.type },
  });

  return c.json({
    key,
    url: `https://assets.antigravityai.directory/${key}`,
  });
});

// Health check
app.get('/health', (c) => c.json({ status: 'ok' }));

// 404 handler
app.notFound((c) => c.json({ error: 'Not found' }, 404));

// Error handler
app.onError((err, c) => {
  console.error('Worker error:', err);
  return c.json({ error: 'Internal server error' }, 500);
});

export default app;
```

## KV Caching Utilities

Create reusable caching patterns:

```typescript
// src/lib/cache.ts
type CacheOptions = {
  ttl?: number;
  tags?: string[];
};

export class KVCache {
  constructor(private kv: KVNamespace) {}

  async get<T>(key: string): Promise<T | null> {
    const value = await this.kv.get(key);
    if (!value) return null;
    return JSON.parse(value);
  }

  async set<T>(key: string, value: T, options: CacheOptions = {}): Promise<void> {
    const { ttl = 3600 } = options;
    await this.kv.put(key, JSON.stringify(value), { expirationTtl: ttl });
  }

  async invalidate(key: string): Promise<void> {
    await this.kv.delete(key);
  }

  async getOrSet<T>(
    key: string,
    fn: () => Promise<T>,
    options: CacheOptions = {}
  ): Promise<T> {
    const cached = await this.get<T>(key);
    if (cached !== null) return cached;

    const value = await fn();
    await this.set(key, value, options);
    return value;
  }
}
```

## Best Practices

1. **Use Hono** for routing and middleware
2. **Leverage D1** for relational data at the edge
3. **Cache with KV** for frequently accessed data
4. **Store files in R2** for cost-effective object storage
5. **Use waitUntil** for async operations after response
6. **Implement proper error handling** with typed errors
7. **Use Wrangler** for local development and deployment

When to Use This Prompt

This cloudflare prompt is ideal for developers working on:

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

Related Prompts

💬 Comments

Loading comments...