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
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
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
Requesty devuelven unResponse— evita patrones al estiloexpress. caches.defaultes la caché de borde de Cloudflare; solo funciona en producción. UsaMINIFLARE_CACHEpara pruebas locales o simula la caché.CF-Connecting-IPes 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 enwrangler.tomlo en archivos.envconfirmados.
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 devse inicia sin errores y redirige unGET /a la URL upstream.- Una IP que envía 61 solicitudes en un minuto recibe un
429en la 61.ª solicitud. - Una solicitud desde un origen no permitido recibe un
403. - La cabecera
Authorizationno aparece en la respuesta ni en ninguna cabecera visible para el cliente. wrangler deployse ejecuta correctamente y el Worker está activo enworkers.dev.
Comandos de Prueba
wrangler dev &# test normal proxycurl http://localhost:8787/ -H "Origin: https://myapp.com"# test CORS rejectioncurl 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/; doneErrores Comunes de la IA
- Usar
process.enven lugar del parámetroenvpasado al manejadorfetchdel Worker. - Olvidar manejar las solicitudes de verificación
OPTIONS, rompiendo CORS para llamadas POST/PUT. - Almacenar
UPSTREAM_API_KEYenwrangler.tomlcomo una variable simple en lugar de un secreto. - Usar
node:bufferu otros módulos integrados de Node.js, que no están disponibles en el runtime de Workers.
Prompt de Corrección
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.