Edge computing with Cloudflare Workers including KV storage, Durable Objects, and D1 database
# Cloudflare Workers Development for Google Antigravity
Build edge applications with Cloudflare Workers using Google Antigravity's Gemini 3 engine. This guide covers Workers, KV storage, Durable Objects, and D1 database patterns.
## Worker Setup
```typescript
// src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { HTTPException } from 'hono/http-exception';
type Bindings = {
KV: KVNamespace;
DB: D1Database;
RATE_LIMITER: DurableObjectNamespace;
API_KEY: string;
};
const app = new Hono<{ Bindings: Bindings }>();
// Middleware
app.use('*', logger());
app.use('/api/*', cors());
// Rate limiting middleware
app.use('/api/*', async (c, next) => {
const ip = c.req.header('CF-Connecting-IP') || 'unknown';
const id = c.env.RATE_LIMITER.idFromName(ip);
const limiter = c.env.RATE_LIMITER.get(id);
const response = await limiter.fetch(new Request('http://limiter/check'));
const { allowed } = await response.json();
if (!allowed) {
throw new HTTPException(429, { message: 'Too many requests' });
}
await next();
});
// Health check
app.get('/health', (c) => {
return c.json({ status: 'healthy', region: c.req.cf?.colo });
});
// KV operations
app.get('/api/cache/:key', async (c) => {
const key = c.req.param('key');
const value = await c.env.KV.get(key, 'json');
if (!value) {
throw new HTTPException(404, { message: 'Not found' });
}
return c.json(value);
});
app.put('/api/cache/:key', async (c) => {
const key = c.req.param('key');
const body = await c.req.json();
await c.env.KV.put(key, JSON.stringify(body), {
expirationTtl: 3600, // 1 hour
});
return c.json({ success: true });
});
// D1 database operations
app.get('/api/users', async (c) => {
const { results } = await c.env.DB.prepare(
'SELECT * FROM users ORDER BY created_at DESC LIMIT 100'
).all();
return c.json({ users: results });
});
app.get('/api/users/:id', async (c) => {
const id = c.req.param('id');
const user = await c.env.DB.prepare(
'SELECT * FROM users WHERE id = ?'
).bind(id).first();
if (!user) {
throw new HTTPException(404, { message: 'User not found' });
}
return c.json({ user });
});
app.post('/api/users', async (c) => {
const { email, name } = await c.req.json();
const id = crypto.randomUUID();
await c.env.DB.prepare(
'INSERT INTO users (id, email, name) VALUES (?, ?, ?)'
).bind(id, email, name).run();
return c.json({ id }, 201);
});
// Error handling
app.onError((err, c) => {
if (err instanceof HTTPException) {
return c.json({ error: err.message }, err.status);
}
console.error(err);
return c.json({ error: 'Internal server error' }, 500);
});
export default app;
```
## Durable Objects for State
```typescript
// src/rate-limiter.ts
export class RateLimiter {
private state: DurableObjectState;
private requests: number[] = [];
private readonly windowMs = 60000; // 1 minute
private readonly maxRequests = 100;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === '/check') {
return this.checkLimit();
}
if (url.pathname === '/reset') {
this.requests = [];
return new Response(JSON.stringify({ reset: true }));
}
return new Response('Not found', { status: 404 });
}
private async checkLimit(): Promise<Response> {
const now = Date.now();
// Remove expired requests
this.requests = this.requests.filter(
(timestamp) => now - timestamp < this.windowMs
);
if (this.requests.length >= this.maxRequests) {
return new Response(
JSON.stringify({
allowed: false,
remaining: 0,
resetAt: this.requests[0] + this.windowMs,
}),
{
headers: { 'Content-Type': 'application/json' },
}
);
}
this.requests.push(now);
return new Response(
JSON.stringify({
allowed: true,
remaining: this.maxRequests - this.requests.length,
}),
{
headers: { 'Content-Type': 'application/json' },
}
);
}
}
// Counter Durable Object
export class Counter {
private state: DurableObjectState;
private value: number = 0;
constructor(state: DurableObjectState) {
this.state = state;
this.state.blockConcurrencyWhile(async () => {
const stored = await this.state.storage.get<number>('value');
this.value = stored ?? 0;
});
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
switch (url.pathname) {
case '/increment':
this.value++;
await this.state.storage.put('value', this.value);
return new Response(JSON.stringify({ value: this.value }));
case '/decrement':
this.value--;
await this.state.storage.put('value', this.value);
return new Response(JSON.stringify({ value: this.value }));
case '/get':
return new Response(JSON.stringify({ value: this.value }));
default:
return new Response('Not found', { status: 404 });
}
}
}
```
## KV Caching Patterns
```typescript
// src/cache.ts
type Bindings = {
KV: KVNamespace;
};
export class CacheService {
private kv: KVNamespace;
private defaultTtl = 3600;
constructor(kv: KVNamespace) {
this.kv = kv;
}
async get<T>(key: string): Promise<T | null> {
return this.kv.get(key, 'json');
}
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
await this.kv.put(key, JSON.stringify(value), {
expirationTtl: ttl || this.defaultTtl,
});
}
async getOrSet<T>(
key: string,
fetcher: () => Promise<T>,
ttl?: number
): Promise<T> {
const cached = await this.get<T>(key);
if (cached !== null) {
return cached;
}
const fresh = await fetcher();
await this.set(key, fresh, ttl);
return fresh;
}
async delete(key: string): Promise<void> {
await this.kv.delete(key);
}
async deleteByPrefix(prefix: string): Promise<void> {
const list = await this.kv.list({ prefix });
for (const key of list.keys) {
await this.kv.delete(key.name);
}
}
// Cache-aside pattern with stale-while-revalidate
async getWithSWR<T>(
key: string,
fetcher: () => Promise<T>,
options: {
ttl?: number;
staleWhileRevalidate?: number;
} = {}
): Promise<T> {
const { ttl = 3600, staleWhileRevalidate = 60 } = options;
const metaKey = `${key}:meta`;
const [cached, meta] = await Promise.all([
this.get<T>(key),
this.get<{ timestamp: number }>(metaKey),
]);
const now = Date.now();
const isStale = meta && now - meta.timestamp > ttl * 1000;
if (cached !== null && !isStale) {
return cached;
}
if (cached !== null && isStale) {
// Return stale data and revalidate in background
this.revalidate(key, metaKey, fetcher, ttl);
return cached;
}
const fresh = await fetcher();
await Promise.all([
this.set(key, fresh, ttl + staleWhileRevalidate),
this.set(metaKey, { timestamp: now }, ttl + staleWhileRevalidate),
]);
return fresh;
}
private async revalidate<T>(
key: string,
metaKey: string,
fetcher: () => Promise<T>,
ttl: number
): Promise<void> {
try {
const fresh = await fetcher();
await Promise.all([
this.set(key, fresh, ttl),
this.set(metaKey, { timestamp: Date.now() }, ttl),
]);
} catch (error) {
console.error('Revalidation failed:', error);
}
}
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Cloudflare Workers patterns: Use KV for caching and configuration. Implement Durable Objects for stateful operations. Leverage D1 for relational data. Add proper error handling and logging. Use Hono for ergonomic routing.This Cloudflare Workers 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 workers 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 Workers projects, consider mentioning your framework version, coding style, and any specific libraries you're using.