Edge computing patterns with Cloudflare Workers for Google Antigravity IDE
# Cloudflare Workers Development for Google Antigravity
Master edge computing with Cloudflare Workers in Google Antigravity IDE. This comprehensive guide covers worker creation, KV storage, Durable Objects, D1 database integration, and deployment patterns for building globally distributed applications that run at the edge.
## Configuration
Configure your Antigravity environment for Workers:
```typescript
// .antigravity/cloudflare.ts
export const cloudflareConfig = {
platform: "workers",
features: {
kvNamespaces: true,
durableObjects: true,
d1Database: true,
r2Storage: true
},
deployment: {
minify: true,
compatibility: "2024-01-01"
}
};
```
## Worker Setup with Hono
Create edge APIs using Hono:
```typescript
// src/index.ts
import { Hono } from "hono";
import { cors } from "hono/cors";
import { cache } from "hono/cache";
type Env = {
KV: KVNamespace;
DB: D1Database;
BUCKET: R2Bucket;
};
const app = new Hono<{ Bindings: Env }>();
app.use("*", cors());
app.use("/api/*", cache({ cacheName: "api-cache", cacheControl: "max-age=60" }));
app.get("/", (c) => {
return c.json({ message: "Hello from the edge!" });
});
app.get("/api/users", async (c) => {
const { results } = await c.env.DB
.prepare("SELECT * FROM users ORDER BY created_at DESC")
.all();
return c.json(results);
});
app.post("/api/users", async (c) => {
const { name, email } = await c.req.json();
const result = await c.env.DB
.prepare("INSERT INTO users (name, email) VALUES (?, ?) RETURNING *")
.bind(name, email)
.first();
return c.json(result, 201);
});
app.get("/api/cache/:key", async (c) => {
const key = c.req.param("key");
const value = await c.env.KV.get(key, "json");
if (!value) {
return c.json({ error: "Not found" }, 404);
}
return c.json(value);
});
app.put("/api/cache/:key", async (c) => {
const key = c.req.param("key");
const value = await c.req.json();
await c.env.KV.put(key, JSON.stringify(value), {
expirationTtl: 3600
});
return c.json({ success: true });
});
export default app;
```
## D1 Database Patterns
Work with Cloudflare D1 SQL database:
```typescript
// db/schema.sql
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
// db/migrations.ts
export async function migrate(db: D1Database) {
await db.batch([
db.prepare(`
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
`),
db.prepare("CREATE INDEX IF NOT EXISTS idx_posts_user ON posts(user_id)")
]);
}
// Usage in worker
async function getUserPosts(db: D1Database, userId: number) {
const { results } = await db
.prepare(`
SELECT p.*, u.name as author_name
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.user_id = ?
ORDER BY p.created_at DESC
`)
.bind(userId)
.all();
return results;
}
```
## KV Storage Patterns
Use KV for edge caching:
```typescript
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
async function getCached<T>(
kv: KVNamespace,
key: string,
fetcher: () => Promise<T>,
ttl = 3600
): Promise<T> {
const cached = await kv.get<CacheEntry<T>>(key, "json");
if (cached) {
const age = Date.now() - cached.timestamp;
if (age < cached.ttl * 1000) {
return cached.data;
}
}
const data = await fetcher();
await kv.put(key, JSON.stringify({
data,
timestamp: Date.now(),
ttl
}), { expirationTtl: ttl });
return data;
}
async function invalidateCache(kv: KVNamespace, pattern: string) {
const list = await kv.list({ prefix: pattern });
await Promise.all(
list.keys.map(key => kv.delete(key.name))
);
}
```
## Durable Objects
Create stateful edge applications:
```typescript
export class Counter {
state: DurableObjectState;
count: number = 0;
constructor(state: DurableObjectState) {
this.state = state;
this.state.blockConcurrencyWhile(async () => {
this.count = (await this.state.storage.get("count")) || 0;
});
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/increment") {
this.count++;
await this.state.storage.put("count", this.count);
return new Response(JSON.stringify({ count: this.count }));
}
if (url.pathname === "/decrement") {
this.count--;
await this.state.storage.put("count", this.count);
return new Response(JSON.stringify({ count: this.count }));
}
return new Response(JSON.stringify({ count: this.count }));
}
}
// Using the Durable Object
app.get("/counter/:id", async (c) => {
const id = c.env.COUNTER.idFromName(c.req.param("id"));
const stub = c.env.COUNTER.get(id);
return stub.fetch(c.req.raw);
});
```
## Best Practices
Follow these guidelines for Cloudflare Workers:
1. **Keep workers small** - Under 1MB compressed
2. **Use D1 for structured data** - Serverless SQL
3. **Cache aggressively** - KV for read-heavy data
4. **Durable Objects for state** - Coordinate across requests
5. **Batch D1 queries** - Reduce round trips
6. **Use Wrangler** - Local development and deployment
Google Antigravity IDE provides intelligent Workers scaffolding and edge optimization suggestions.This 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.