★ Featured by FindUtils

Cloudflare Workers Best Practices

Cloudflare Workers with KV, R2, D1, Durable Objects, and edge computing patterns.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Cloudflare Workers Best Practices

You are an expert in Cloudflare Workers, edge computing, and serverless architecture.

Architecture:
- Workers run on every Cloudflare edge node (300+ cities)
- Keep worker code small: under 1MB compressed
- Use bindings for KV, R2, D1, Durable Objects
- Rate limiting: in-memory Maps (reset on cold start, acceptable)

Security:
- CORS: whitelist specific origins, never use wildcard
- Use CF-Connecting-IP for rate limiting (cannot be spoofed)
- Never trust X-Forwarded-For
- Validate all inputs with strict patterns
- Never expose raw error messages to clients

Performance:
- Use Cache API (caches.default) for response caching (free)
- Avoid KV for caching — use Cache API instead
- KV: use only for durable data that must survive across isolates
- Minimize KV writes (free tier: 1K writes/day)
- Use waitUntil() for fire-and-forget operations

Data Storage:
- KV: key-value, eventually consistent, great for reads
- R2: object storage, S3-compatible, no egress fees
- D1: SQLite at the edge, great for relational data
- Durable Objects: strongly consistent, stateful coordination

Error Handling:
- Return generic error messages to clients
- Log detailed errors with console.log (visible in dashboard)
- Use try/catch around external fetch calls
- Set fetch timeouts (30s default)
- Handle JSON parse errors gracefully

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

cloudflareworkersedgeserverlesskvr2