Cloudflare Workers Skill
Expert knowledge in Cloudflare Workers, edge computing, KV storage, Durable Objects, R2, and serverless deployment patterns.
1. Worker Basics
1.1 Worker Syntax & Structure
Workers use the fetch event handler pattern to intercept and handle HTTP requests at the edge.
✅ Good: Standard fetch event handler
typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello from the edge!', {
status: 200,
headers: { 'Content-Type': 'text/plain' },
});
},
};
✅ Good: Module worker with typed environment
typescript
interface Env {
MY_KV: KVNamespace;
MY_SECRET: string;
MY_DURABLE_OBJECT: DurableObjectNamespace;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === '/api/data') {
const data = await env.MY_KV.get('key');
return new Response(data, { status: 200 });
}
return new Response('Not found', { status: 404 });
},
};
❌ Bad: Using global state (resets between requests)
typescript
// Global state is NOT persistent across requests!
let requestCount = 0; // ❌ This resets unpredictably
export default {
async fetch(request: Request): Promise<Response> {
requestCount++; // ❌ Unreliable counter
return new Response(`Count: ${requestCount}`);
},
};
❌ Bad: Blocking synchronous operations
typescript
export default {
async fetch(request: Request): Promise<Response> {
// ❌ Don't use synchronous blocking operations
const data = someHeavyComputationSync(); // Wastes CPU time
return new Response(data);
},
};
1.2 Request & Response Objects
Workers use standard Web APIs (Request/Response) for HTTP handling.
✅ Good: Parsing request data
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const method = request.method;
if (method === 'POST') {
const contentType = request.headers.get('Content-Type');
if (contentType?.includes('application/json')) {
const body = await request.json();
return Response.json({ received: body }, { status: 200 });
}
if (contentType?.includes('application/x-www-form-urlencoded')) {
const formData = await request.formData();
return Response.json({ fields: Object.fromEntries(formData) });
}
}
return new Response('Method not allowed', { status: 405 });
},
};
✅ Good: Setting response headers and status
typescript
export default {
async fetch(request: Request): Promise<Response> {
const data = { message: 'Success', timestamp: Date.now() };
return new Response(JSON.stringify(data), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=300',
'X-Custom-Header': 'edge-response',
},
});
},
};
1.3 Routing Patterns
✅ Good: Path-based routing
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
if (path === '/') {
return new Response('Home page');
}
if (path.startsWith('/api/')) {
return handleAPI(request, env);
}
if (path.startsWith('/static/')) {
return handleStatic(request, env);
}
return new Response('Not found', { status: 404 });
},
};
async function handleAPI(request: Request, env: Env): Promise<Response> {
return Response.json({ api: 'v1', status: 'ok' });
}
async function handleStatic(request: Request, env: Env): Promise<Response> {
// Serve static assets from R2 or KV
return new Response('Static content', { status: 200 });
}
✅ Good: Using URL patterns with regex
typescript
const routes = [
{ pattern: /^\/api\/users\/(\d+)$/, handler: getUserById },
{ pattern: /^\/api\/posts\/([a-z0-9-]+)$/, handler: getPostBySlug },
{ pattern: /^\/health$/, handler: healthCheck },
];
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
for (const route of routes) {
const match = url.pathname.match(route.pattern);
if (match) {
return route.handler(request, env, match);
}
}
return new Response('Not found', { status: 404 });
},
};
async function getUserById(
request: Request,
env: Env,
match: RegExpMatchArray
): Promise<Response> {
const userId = match[1];
return Response.json({ userId, name: 'John Doe' });
}
async function getPostBySlug(
request: Request,
env: Env,
match: RegExpMatchArray
): Promise<Response> {
const slug = match[1];
const post = await env.POSTS_KV.get(slug);
return new Response(post || 'Not found', { status: post ? 200 : 404 });
}
async function healthCheck(): Promise<Response> {
return Response.json({ status: 'healthy', timestamp: Date.now() });
}
1.4 Local Development
Use Wrangler for local development with hot reloading.
✅ Good: Local development workflow
bash
# Install Wrangler globally
npm install -g wrangler
# Create new Worker project
wrangler init my-worker
# Start local development server (port 8787 by default)
wrangler dev
# Start with remote resources (KV, Durable Objects)
wrangler dev --remote
# Start on custom port
wrangler dev --port 3000
# Start with live reload
wrangler dev --live-reload
✅ Good: Testing locally with curl
bash
# Test GET request
curl http://localhost:8787/
# Test POST with JSON
curl -X POST http://localhost:8787/api/data \
-H "Content-Type: application/json" \
-d '{"key":"value"}'
# Test with headers
curl http://localhost:8787/api/users/123 \
-H "Authorization: Bearer token"
1.5 Deployment
✅ Good: Deploy to production
bash
# Deploy Worker
wrangler deploy
# Deploy to specific environment
wrangler deploy --env production
# Deploy with verbose logging
wrangler deploy --verbose
# Tail logs after deployment
wrangler tail
✅ Good: wrangler.toml configuration
toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-11-01"
# Routes (alternative to dashboard configuration)
routes = [
{ pattern = "example.com/*", zone_name = "example.com" }
]
# Environment variables
[vars]
ENVIRONMENT = "production"
API_VERSION = "v1"
# KV bindings
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123"
# Durable Object bindings
[[durable_objects.bindings]]
name = "MY_DO"
class_name = "MyDurableObject"
script_name = "my-worker"
# R2 bindings
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
2. KV Storage (Key-Value)
Workers KV is a global, low-latency key-value store optimized for high read volumes and infrequent writes.
2.1 KV Operations
✅ Good: Basic KV operations
typescript
interface Env {
MY_KV: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const key = url.searchParams.get('key');
if (!key) {
return new Response('Key required', { status: 400 });
}
// GET: Read value
const value = await env.MY_KV.get(key);
if (value === null) {
return new Response('Not found', { status: 404 });
}
return new Response(value, { status: 200 });
},
};
✅ Good: PUT with metadata and TTL
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { key, value, ttl } = await request.json();
// Put with metadata and expiration
await env.MY_KV.put(key, value, {
expirationTtl: ttl || 3600, // 1 hour default
metadata: {
createdAt: Date.now(),
version: '1.0',
author: 'worker',
},
});
return Response.json({ success: true, key });
},
};
✅ Good: GET with metadata
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const key = 'user:123';
// Get value with metadata
const { value, metadata } = await env.MY_KV.getWithMetadata(key);
if (value === null) {
return new Response('Not found', { status: 404 });
}
return Response.json({
value,
metadata, // Custom metadata attached to the key
});
},
};
✅ Good: DELETE operation
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const key = 'session:abc123';
// Delete key
await env.MY_KV.delete(key);
return Response.json({ deleted: true, key });
},
};
2.2 KV Namespaces
KV data is organized into namespaces (isolated storage buckets).
✅ Good: Multiple namespaces for different data types
toml
# wrangler.toml
[[kv_namespaces]]
binding = "USERS"
id = "abc123"
[[kv_namespaces]]
binding = "SESSIONS"
id = "def456"
[[kv_namespaces]]
binding = "CACHE"
id = "ghi789"
typescript
interface Env {
USERS: KVNamespace;
SESSIONS: KVNamespace;
CACHE: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Different namespaces for different purposes
const user = await env.USERS.get('user:123');
const session = await env.SESSIONS.get('session:abc');
const cachedData = await env.CACHE.get('api:response:xyz');
return Response.json({ user, session, cachedData });
},
};
2.3 TTL and Expiration
✅ Good: Using TTL for automatic expiration
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sessionId = 'session:abc123';
const sessionData = JSON.stringify({ userId: 123, loggedIn: true });
// Expire after 1 hour (3600 seconds)
await env.SESSIONS.put(sessionId, sessionData, {
expirationTtl: 3600,
});
return Response.json({ message: 'Session created with 1-hour TTL' });
},
};
✅ Good: Using absolute expiration timestamp
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const cacheKey = 'cache:data';
const data = JSON.stringify({ result: 'cached' });
// Expire at specific Unix timestamp (24 hours from now)
const expirationTime = Math.floor(Date.now() / 1000) + 86400;
await env.CACHE.put(cacheKey, data, {
expiration: expirationTime,
});
return Response.json({ message: 'Cached until tomorrow' });
},
};
❌ Bad: Not using TTL for temporary data
typescript
// ❌ Storing temporary data without expiration
await env.SESSIONS.put('session:temp', 'data'); // Never expires, wastes storage
2.4 Bulk Operations
✅ Good: Listing keys with pagination
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const allKeys: string[] = [];
let cursor: string | undefined;
// Paginate through all keys
do {
const result = await env.MY_KV.list({ cursor, limit: 1000 });
allKeys.push(...result.keys.map((k) => k.name));
cursor = result.cursor;
} while (cursor);
return Response.json({ keys: allKeys, total: allKeys.length });
},
};
✅ Good: Listing keys with prefix filter
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// List all user keys (e.g., "user:123", "user:456")
const result = await env.USERS.list({ prefix: 'user:' });
const userKeys = result.keys.map((k) => k.name);
return Response.json({ users: userKeys });
},
};