P PasteCode
Indicación

Indicación para construir un proxy de API de Cloudflare Worker

Indicación de IA para copiar y pegar con el fin de construir un Worker de Cloudflare que haga de proxy, limite la tasa de llamadas API externas, añada encabezados de autenticación y almacene en caché las respuestas.

CursorClaude CodeCodexWindsurf CloudflareTypeScript
.md .json Dificultad: Medio Actualizado 8 jun 2026

Utiliza este prompt para construir un Cloudflare Worker que se sitúe delante de una API externa, inyecte cabeceras de autenticación, limite la tasa por IP usando Workers KV y almacene en caché las respuestas — para que los clientes nunca vean tu clave de API upstream.

Prompt Principal

Main Prompt
You are building a Cloudflare Worker using TypeScript and the Workers runtime (not Node.js).
The Worker will proxy requests to an upstream API (e.g., OpenAI at https://api.openai.com).
Task: create a production-ready API proxy Worker.
Requirements:
- Use `wrangler` v3 for local dev. Scaffold with `bun create cloudflare@latest` and choose
"Hello World" Worker with TypeScript.
- Upstream URL: read from a Wrangler secret `UPSTREAM_URL` (string).
- Auth: inject `Authorization: Bearer ${env.UPSTREAM_API_KEY}` on every proxied request,
where `UPSTREAM_API_KEY` is a Wrangler secret. Never expose this header to the client.
- CORS: allow only origins in `env.ALLOWED_ORIGINS` (comma-separated string secret).
Return a `403` for disallowed origins. Handle preflight OPTIONS requests.
- Rate limiting: use Workers KV binding `RATE_LIMIT_KV`.
- Key: `rl:${ip}` where ip is `request.headers.get('CF-Connecting-IP')`.
- Value: request count for the current UTC minute (TTL = 60 s).
- Limit: 60 requests/minute per IP. Return `429` with `Retry-After: 60` if exceeded.
- Caching: for GET requests, check `caches.default` before proxying upstream. Cache
successful responses with `Cache-Control: public, max-age=300`.
- Strip the following headers from the upstream response before returning to the client:
`x-powered-by`, `server`, `cf-ray`.
- Wrangler config: declare the KV namespace binding and all secrets in `wrangler.toml`.
- Do NOT use Node.js APIs (`fs`, `path`, `Buffer`) — Workers runtime only.
Stop and list all planned files before writing code.

Notas de Implementación

  • Los Cloudflare Workers reciben un Request y devuelven un Response — evita patrones al estilo express.
  • caches.default es la caché de borde de Cloudflare; solo funciona en producción. Usa MINIFLARE_CACHE para pruebas locales o simula la caché.
  • CF-Connecting-IP es inyectado por Cloudflare — no es suplantable desde Internet público, pero prueba localmente con una IP de respaldo fija.
  • Los secretos de Wrangler se configuran con wrangler secret put UPSTREAM_API_KEY — nunca los almacenes en wrangler.toml o en archivos .env confirmados.

Cambios Esperados en Archivos

wrangler.toml (new)
src/index.ts (new — Worker entrypoint)
src/cors.ts (new — CORS helper)
src/rate-limit.ts (new — KV rate limiter)
package.json (new)
tsconfig.json (new)
.dev.vars (new — local dev secrets, gitignored)
.gitignore (edited — add .dev.vars)

Criterios de Aceptación

  • wrangler dev se inicia sin errores y redirige un GET / a la URL upstream.
  • Una IP que envía 61 solicitudes en un minuto recibe un 429 en la 61.ª solicitud.
  • Una solicitud desde un origen no permitido recibe un 403.
  • La cabecera Authorization no aparece en la respuesta ni en ninguna cabecera visible para el cliente.
  • wrangler deploy se ejecuta correctamente y el Worker está activo en workers.dev.

Comandos de Prueba

Terminal window
wrangler dev &
# test normal proxy
curl http://localhost:8787/ -H "Origin: https://myapp.com"
# test CORS rejection
curl http://localhost:8787/ -H "Origin: https://evil.com"
# test rate limit (requires 61 rapid requests)
for i in $(seq 1 62); do curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8787/; done

Errores Comunes de la IA

  • Usar process.env en lugar del parámetro env pasado al manejador fetch del Worker.
  • Olvidar manejar las solicitudes de verificación OPTIONS, rompiendo CORS para llamadas POST/PUT.
  • Almacenar UPSTREAM_API_KEY en wrangler.toml como una variable simple en lugar de un secreto.
  • Usar node:buffer u otros módulos integrados de Node.js, que no están disponibles en el runtime de Workers.

Prompt de Corrección

Fix Prompt
The Worker fails with a runtime error or leaks the API key. Fix in order:
1. Replace `process.env.X` with `env.X` everywhere — Workers use the `env` handler parameter.
2. Add an OPTIONS handler before the proxy logic that returns the CORS headers with a 204 status.
3. Move `UPSTREAM_API_KEY` from `wrangler.toml` [vars] to a secret: `wrangler secret put UPSTREAM_API_KEY`.
Show only the corrected diff.