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/pages-functions/gotchas.md
1# Gotchas & Debugging23## Error Diagnosis45| Symptom | Likely Cause | Solution |6|---------|--------------|----------|7| **Function not invoking** | Wrong `/functions` location, wrong extension, or `_routes.json` excludes path | Check `pages_build_output_dir`, use `.js`/`.ts`, verify `_routes.json` |8| **`ctx.env.BINDING` undefined** | Binding not configured or name mismatch | Add to `wrangler.jsonc`, verify exact name (case-sensitive), redeploy |9| **TypeScript errors on `ctx.env`** | Missing type definition | Run `wrangler types` or define `interface Env {}` |10| **Middleware not running** | Wrong filename/location or missing `ctx.next()` | Name exactly `_middleware.js`, export `onRequest`, call `ctx.next()` |11| **Secrets missing in production** | `.dev.vars` not deployed | `.dev.vars` is local only - set production secrets via dashboard or `wrangler secret put` |12| **Type mismatch on binding** | Wrong interface type | See [api.md](./api.md) bindings table for correct types |13| **"KV key not found" but exists** | Key in wrong namespace or env | Verify namespace binding, check preview vs production env |14| **Function times out** | Synchronous wait or missing `await` | All I/O must be async/await, use `ctx.waitUntil()` for background tasks |1516## Common Errors1718### TypeScript type errors1920**Problem:** `ctx.env.MY_BINDING` shows type error21**Cause:** No type definition for `Env`22**Solution:** Run `npx wrangler types` or manually define:23```typescript24interface Env { MY_BINDING: KVNamespace; }25export const onRequest: PagesFunction<Env> = async (ctx) => { /* ... */ };26```2728### Secrets not available in production2930**Problem:** `ctx.env.SECRET_KEY` is undefined in production31**Cause:** `.dev.vars` is local-only, not deployed32**Solution:** Set production secrets:33```bash34echo "value" | npx wrangler pages secret put SECRET_KEY --project-name=my-app35```3637## Debugging3839```typescript40// Console logging41export async function onRequest(ctx) {42console.log('Request:', ctx.request.method, ctx.request.url);43const res = await ctx.next();44console.log('Status:', res.status);45return res;46}47```4849```bash50# Stream real-time logs51npx wrangler pages deployment tail52npx wrangler pages deployment tail --status error53```5455```jsonc56// Source maps (wrangler.jsonc)57{ "upload_source_maps": true }58```5960## Limits6162| Resource | Free | Paid |63|----------|------|------|64| CPU time | 10ms | 30s (default), 5min (max) |65| Memory | 128 MB | 128 MB |66| Script size | 10 MB compressed | 10 MB compressed |67| Env vars | 5 KB per var, 64 max | 5 KB per var, 64 max |68| Requests | 100k/day | Unlimited ($0.50/million) |6970## Best Practices7172**Performance:** Minimize deps (cold start), use KV for cache/D1 for relational/R2 for large files, set `Cache-Control` headers, batch DB ops, handle errors gracefully7374**Security:** Never commit secrets (use `.dev.vars` + gitignore), validate input, sanitize before DB, implement auth middleware, set CORS headers, rate limit per-IP7576## Migration7778**Workers → Pages Functions:**79- `export default { fetch(req, env) {} }` → `export function onRequest(ctx) { const { request, env } = ctx; }`80- Use `_worker.js` for complex routing: `env.ASSETS.fetch(request)` for static files8182**Other platforms → Pages:**83- File-based routing: `/functions/api/users.js` → `/api/users`84- Dynamic routes: `[param]` not `:param`85- Replace Node.js deps with Workers APIs or add `nodejs_compat` flag8687## Resources8889- [Official Docs](https://developers.cloudflare.com/pages/functions/)90- [Workers APIs](https://developers.cloudflare.com/workers/runtime-apis/)91- [Examples](https://github.com/cloudflare/pages-example-projects)92- [Discord](https://discord.gg/cloudflaredev)9394**See also:** [configuration.md](./configuration.md) for TypeScript setup | [patterns.md](./patterns.md) for middleware/auth | [api.md](./api.md) for bindings95