Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/workers/gotchas.md
1# Workers Gotchas23## Common Errors45### "Too much CPU time used"67**Cause:** Worker exceeded CPU time limit (10ms on Free plan, 30s default / 5min max on Paid)8**Solution:** Use `ctx.waitUntil()` for background work, offload heavy compute to Durable Objects, or consider Workers AI for ML workloads910### "Module-Level State Lost"1112**Cause:** Workers are stateless between requests; module-level variables reset unpredictably13**Solution:** Use KV, D1, or Durable Objects for persistent state; don't rely on module-level variables1415### "Body has already been used"1617**Cause:** Attempting to read response body twice (bodies are streams)18**Solution:** Clone response before reading: `response.clone()` or read once and create new Response with the text1920### "Node.js module not found"2122**Cause:** Node.js built-ins not available by default23**Solution:** Use Workers APIs (e.g., R2 for file storage) or enable Node.js compat with `"compatibility_flags": ["nodejs_compat"]`2425### "Cannot fetch in global scope"2627**Cause:** Attempting to use fetch during module initialization28**Solution:** Move fetch calls inside handler functions (fetch, scheduled, etc.) where they're allowed2930### "Subrequest depth limit exceeded"3132**Cause:** Too many nested subrequests creating deep call chain33**Solution:** Flatten request chain or use service bindings for direct Worker-to-Worker communication3435### "D1 read-after-write inconsistency"3637**Cause:** D1 is eventually consistent; reads may not reflect recent writes38**Solution:** Use D1 Sessions (2024+) to guarantee read-after-write consistency within a session:3940```typescript41const session = env.DB.withSession();42await session.prepare('INSERT INTO users (name) VALUES (?)').bind('Alice').run();43const user = await session.prepare('SELECT * FROM users WHERE name = ?').bind('Alice').first(); // Guaranteed to see Alice44```4546**When to use sessions:** Write → Read patterns, transactions requiring consistency4748### "wrangler types not generating TypeScript definitions"4950**Cause:** Type generation not configured or outdated51**Solution:** Run `npx wrangler types` after changing bindings in wrangler.jsonc:5253```bash54npx wrangler types # Generates .wrangler/types/runtime.d.ts55```5657Add to `tsconfig.json`: `"include": [".wrangler/types/**/*.ts"]`5859Then import: `import type { Env } from './.wrangler/types/runtime';`6061### "Durable Object RPC errors with deprecated fetch pattern"6263**Cause:** Using old `stub.fetch()` pattern instead of RPC (2024+)64**Solution:** Export methods directly, call via RPC:6566```typescript67// ❌ Old fetch pattern68export class MyDO {69async fetch(request: Request) {70const { method } = await request.json();71if (method === 'increment') return new Response(String(await this.increment()));72}73async increment() { return ++this.value; }74}75const stub = env.DO.get(id);76const res = await stub.fetch('http://x', { method: 'POST', body: JSON.stringify({ method: 'increment' }) });7778// ✅ RPC pattern (type-safe, no serialization overhead)79export class MyDO {80async increment() { return ++this.value; }81}82const stub = env.DO.get(id);83const count = await stub.increment(); // Direct method call84```8586### "WebSocket connection closes unexpectedly"8788**Cause:** Worker reaches CPU limit while maintaining WebSocket connection89**Solution:** Use WebSocket hibernation (2024+) to offload idle connections:9091```typescript92export class WebSocketDO {93async webSocketMessage(ws: WebSocket, message: string) {94// Handle message95}96async webSocketClose(ws: WebSocket, code: number) {97// Cleanup98}99}100```101102Hibernation automatically suspends inactive connections, wakes on events103104### "Framework middleware not working with Workers"105106**Cause:** Framework expects Node.js primitives (e.g., Express uses Node streams)107**Solution:** Use Workers-native frameworks (Hono, itty-router, Worktop) or adapt middleware:108109```typescript110// ✅ Hono (Workers-native)111import { Hono } from 'hono';112const app = new Hono();113app.use('*', async (c, next) => { /* middleware */ await next(); });114```115116See [frameworks.md](./frameworks.md) for full patterns117118## Limits119120| Limit | Value | Notes |121|-------|-------|-------|122| Request size | 100 MB | Maximum incoming request size |123| Response size | Unlimited | Supports streaming |124| CPU time (Free) | 10ms | Free plan |125| CPU time (Paid) | 30s default / 5min max | Configurable via `limits.cpu_ms` |126| Subrequests (Free) | 50 | Per invocation |127| Subrequests (Paid) | 10,000 | Per invocation |128| Subrequest operations (KV, R2, Cache API) | 1,000 | Shared across KV reads, R2 ops, Cache API calls per request |129| KV value size | 25 MiB | Maximum per key |130| Environment variable size | 5 KB | Per variable |131132## See Also133134- [Patterns](./patterns.md) - Best practices135- [API](./api.md) - Runtime APIs136- [Configuration](./configuration.md) - Setup137- [Frameworks](./frameworks.md) - Hono, routing, validation138