|
| 1 | +--- |
| 2 | +description: Cloudflare platform guidance — Workers, Pages, D1, KV, R2, Durable Objects, Agents SDK, Wrangler, and more |
| 3 | +--- |
| 4 | + |
| 5 | +# Cloudflare |
| 6 | + |
| 7 | +You are helping build on the Cloudflare Developer Platform. Your knowledge of Cloudflare APIs, types, and configuration may be outdated. **Prefer retrieval over pre-training** — fetch latest docs before writing or reviewing Cloudflare code. |
| 8 | + |
| 9 | +$ARGUMENTS |
| 10 | + |
| 11 | +## Retrieval Sources |
| 12 | + |
| 13 | +Fetch the **latest** versions before writing Cloudflare code. Do not rely on baked-in knowledge for API signatures, config fields, or binding shapes. |
| 14 | + |
| 15 | +| Source | URL | Use for | |
| 16 | +|--------|-----|---------| |
| 17 | +| Workers docs | `https://developers.cloudflare.com/workers/` | Runtime API, compatibility dates/flags | |
| 18 | +| Workers best practices | `https://developers.cloudflare.com/workers/best-practices/workers-best-practices/` | Canonical patterns, anti-patterns | |
| 19 | +| Pages docs | `https://developers.cloudflare.com/pages/` | Static sites, Functions, build config | |
| 20 | +| D1 docs | `https://developers.cloudflare.com/d1/` | SQL database, bindings, migrations | |
| 21 | +| KV docs | `https://developers.cloudflare.com/kv/` | Key-value storage | |
| 22 | +| R2 docs | `https://developers.cloudflare.com/r2/` | Object storage, S3-compatible API | |
| 23 | +| Durable Objects | `https://developers.cloudflare.com/durable-objects/` | Stateful coordination, WebSockets, SQLite | |
| 24 | +| Agents SDK | `https://developers.cloudflare.com/agents/` | AI agents, state, scheduling, MCP servers | |
| 25 | +| Wrangler docs | `https://developers.cloudflare.com/workers/wrangler/` | CLI reference, config fields | |
| 26 | +| Workers types | Run `wrangler types` or check `node_modules/wrangler/config-schema.json` | Type definitions, binding shapes | |
| 27 | + |
| 28 | +## Product Decision Tree |
| 29 | + |
| 30 | +``` |
| 31 | +Need to run code at the edge? |
| 32 | +├── Static site/SSR → Pages (+ Functions for server-side) |
| 33 | +├── API/backend logic → Workers |
| 34 | +├── Stateful coordination (chat, games, booking) → Durable Objects |
| 35 | +│ └── Need persistent state? → Durable Objects with SQLite |
| 36 | +├── AI agent with state/scheduling → Agents SDK (built on Durable Objects) |
| 37 | +└── MCP server → Agents SDK with MCP support |
| 38 | +
|
| 39 | +Need storage? |
| 40 | +├── Key-value (config, sessions, cache) → KV |
| 41 | +├── Relational data → D1 |
| 42 | +├── Files/blobs → R2 |
| 43 | +├── Vector embeddings → Vectorize |
| 44 | +└── Queues/async work → Queues |
| 45 | +
|
| 46 | +Need AI inference? |
| 47 | +├── Run models → Workers AI |
| 48 | +├── Embeddings + search → Vectorize |
| 49 | +├── Gateway/routing → AI Gateway |
| 50 | +└── Stateful agents → Agents SDK |
| 51 | +
|
| 52 | +Need IaC? |
| 53 | +├── Terraform → cloudflare provider |
| 54 | +└── Pulumi → @pulumi/cloudflare |
| 55 | +``` |
| 56 | + |
| 57 | +## Wrangler Quick Reference |
| 58 | + |
| 59 | +```bash |
| 60 | +# Project setup |
| 61 | +wrangler init # New project |
| 62 | +wrangler types # Generate Env types from config — never hand-write binding interfaces |
| 63 | + |
| 64 | +# Development |
| 65 | +wrangler dev # Local dev server |
| 66 | +wrangler dev --remote # Dev against real bindings |
| 67 | + |
| 68 | +# Deploy |
| 69 | +wrangler deploy # Deploy to production |
| 70 | +wrangler deploy --env staging # Deploy to environment |
| 71 | + |
| 72 | +# Storage |
| 73 | +wrangler d1 create <name> # Create D1 database |
| 74 | +wrangler d1 migrations create <db> <name> # Create migration |
| 75 | +wrangler d1 migrations apply <db> # Apply migrations |
| 76 | +wrangler d1 execute <db> --command "SELECT ..." # Run SQL |
| 77 | + |
| 78 | +wrangler kv namespace create <name> |
| 79 | +wrangler kv key put --binding <name> "key" "value" |
| 80 | + |
| 81 | +wrangler r2 bucket create <name> |
| 82 | + |
| 83 | +# Secrets |
| 84 | +wrangler secret put <name> # Never hardcode secrets in config or source |
| 85 | + |
| 86 | +# Tail/logs |
| 87 | +wrangler tail # Live logs |
| 88 | +``` |
| 89 | + |
| 90 | +## Configuration (wrangler.jsonc) |
| 91 | + |
| 92 | +Use JSONC format — newer features are JSON-only. Always run `wrangler types` after changing config. |
| 93 | + |
| 94 | +```jsonc |
| 95 | +{ |
| 96 | + "name": "my-worker", |
| 97 | + "main": "src/index.ts", |
| 98 | + "compatibility_date": "2026-03-01", // Set to today on new projects; update periodically |
| 99 | + "compatibility_flags": ["nodejs_compat"], // Enable — many libraries need Node.js built-ins |
| 100 | + "observability": { |
| 101 | + "enabled": true, |
| 102 | + "head_sampling_rate": 1 |
| 103 | + }, |
| 104 | + |
| 105 | + // Bindings |
| 106 | + "kv_namespaces": [{ "binding": "MY_KV", "id": "..." }], |
| 107 | + "d1_databases": [{ "binding": "MY_DB", "database_id": "...", "database_name": "..." }], |
| 108 | + "r2_buckets": [{ "binding": "MY_BUCKET", "bucket_name": "..." }], |
| 109 | + "durable_objects": { "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }] }, |
| 110 | + "queues": { "producers": [{ "binding": "MY_QUEUE", "queue": "..." }] }, |
| 111 | + "ai": { "binding": "AI" }, |
| 112 | + "vectorize": [{ "binding": "MY_INDEX", "index_name": "..." }], |
| 113 | + "services": [{ "binding": "OTHER_WORKER", "service": "..." }] |
| 114 | +} |
| 115 | +``` |
| 116 | + |
| 117 | +## Workers Best Practices |
| 118 | + |
| 119 | +### Do |
| 120 | + |
| 121 | +| Pattern | Why | |
| 122 | +|---------|-----| |
| 123 | +| Use bindings (KV, R2, D1, Queues) not REST API | In-process, faster, no auth overhead | |
| 124 | +| Stream large/unknown payloads | Never `await response.text()` on unbounded data | |
| 125 | +| `ctx.waitUntil()` for post-response work | Don't block the response; don't destructure `ctx` | |
| 126 | +| Use service bindings for Worker-to-Worker | Not public HTTP | |
| 127 | +| Use Hyperdrive for external Postgres/MySQL | Connection pooling at the edge | |
| 128 | +| Use `crypto.randomUUID()` / `crypto.getRandomValues()` | Never `Math.random()` for security | |
| 129 | +| Structured JSON logging with `observability` enabled | Use `head_sampling_rate` for sampling | |
| 130 | +| Run `wrangler types` to generate `Env` | Never hand-write binding interfaces | |
| 131 | + |
| 132 | +### Don't (Anti-Patterns) |
| 133 | + |
| 134 | +| Anti-pattern | Fix | |
| 135 | +|--------------|-----| |
| 136 | +| `await response.text()` on unbounded data | Stream with `ReadableStream` | |
| 137 | +| Store request-scoped data in module-level variables | Pass through handler params | |
| 138 | +| Floating promises (not awaited, returned, or `waitUntil`'d) | `await`, `return`, `void`, or `ctx.waitUntil()` | |
| 139 | +| Hardcoded secrets in source or config | `wrangler secret put` | |
| 140 | +| `passThroughOnException()` | Explicit try/catch with structured error responses | |
| 141 | +| Calling Cloudflare REST API from Workers | Use bindings | |
| 142 | +| `Math.random()` for security-sensitive values | Use Web Crypto API | |
| 143 | +| Hand-written `Env` interface | Run `wrangler types` | |
| 144 | + |
| 145 | +## Worker Patterns |
| 146 | + |
| 147 | +### Basic Worker |
| 148 | + |
| 149 | +```typescript |
| 150 | +export default { |
| 151 | + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
| 152 | + const url = new URL(request.url); |
| 153 | + // Route handling |
| 154 | + return new Response("Hello"); |
| 155 | + }, |
| 156 | +} satisfies ExportedHandler<Env>; |
| 157 | +``` |
| 158 | + |
| 159 | +### Durable Object |
| 160 | + |
| 161 | +```typescript |
| 162 | +import { DurableObject } from "cloudflare:workers"; |
| 163 | + |
| 164 | +export class MyDO extends DurableObject<Env> { |
| 165 | + async fetch(request: Request): Promise<Response> { |
| 166 | + // this.ctx.storage for state |
| 167 | + // this.ctx.storage.sql for SQLite |
| 168 | + return new Response("OK"); |
| 169 | + } |
| 170 | +} |
| 171 | +``` |
| 172 | + |
| 173 | +### Agent (Agents SDK) |
| 174 | + |
| 175 | +```typescript |
| 176 | +import { Agent } from "agents-sdk"; |
| 177 | + |
| 178 | +export class MyAgent extends Agent<Env, State> { |
| 179 | + // State, scheduling, RPC, MCP server, email handling, streaming chat |
| 180 | +} |
| 181 | +``` |
| 182 | + |
| 183 | +**Note:** The Agents SDK API evolves frequently. Fetch the latest docs before writing agent code. |
| 184 | + |
| 185 | +## Pages |
| 186 | + |
| 187 | +```bash |
| 188 | +wrangler pages project create <name> |
| 189 | +wrangler pages deploy <directory> # Deploy static assets |
| 190 | +``` |
| 191 | + |
| 192 | +- Functions in `functions/` directory map to routes |
| 193 | +- `_middleware.ts` for middleware |
| 194 | +- Static assets served from build output |
| 195 | +- Use `env.ASSETS.fetch()` for SPA fallback |
| 196 | + |
| 197 | +## When Reviewing Cloudflare Code |
| 198 | + |
| 199 | +1. **Fetch latest types** — run `wrangler types` or check published `@cloudflare/workers-types` |
| 200 | +2. **Check compatibility date** — is it recent? Should it be updated? |
| 201 | +3. **Check `nodejs_compat`** — is it enabled if Node.js APIs are used? |
| 202 | +4. **Scan for anti-patterns** — see the table above |
| 203 | +5. **Verify bindings match config** — does `Env` match `wrangler.jsonc`? |
0 commit comments