Edge computing with Cloudflare Workers for Google Antigravity projects including KV storage, D1 database, and R2 object storage.
# 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 deploymentThis cloudflare 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 cloudflare 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 cloudflare projects, consider mentioning your framework version, coding style, and any specific libraries you're using.