# Prompt para Construir um Proxy de API do Cloudflare Worker

> Prompt copiável de IA para construir um Cloudflare Worker que faz proxy e limita taxa de chamadas de API externas, adiciona cabeçalhos de autenticação e armazena respostas em cache.

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Cloudflare, TypeScript  
**Difficulty:** medium  
**Updated:** 2026-06-08

---

Use este prompt para criar um Cloudflare Worker que atua como intermediário para uma API externa, injeta cabeçalhos de autenticação, limita taxa por IP usando Workers KV e armazena respostas em cache — para que os clientes nunca vejam sua chave de API upstream.

## Prompt Principal

```txt title="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 Implementação

- Cloudflare Workers recebem um `Request` e retornam um `Response` — evite padrões no estilo `express`.
- `caches.default` é o cache de borda do Cloudflare; funciona apenas em produção. Use `MINIFLARE_CACHE` para testes de desenvolvimento local ou simule o cache.
- `CF-Connecting-IP` é injetado pelo Cloudflare — não é falsificável da internet pública, mas teste localmente com um IP fallback fixo.
- Segredos do Wrangler são definidos com `wrangler secret put UPSTREAM_API_KEY` — nunca os armazene em `wrangler.toml` ou arquivos `.env` commitados.

## Alterações de Arquivo Esperadas

```txt
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)
```

## Critérios de Aceitação

- `wrangler dev` inicia sem erros e faz proxy de um `GET /` para a URL upstream.
- Um IP que envia 61 requisições em um minuto recebe um `429` na 61ª requisição.
- Uma requisição de uma origem não permitida recebe um `403`.
- O cabeçalho `Authorization` não aparece na resposta ou em qualquer cabeçalho visível ao cliente.
- `wrangler deploy` é bem-sucedido e o Worker está ativo em `workers.dev`.

## Comandos de Teste

```bash
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
```

## Erros Comuns de IA

- Usar `process.env` em vez do parâmetro `env` passado para o manipulador `fetch` do Worker.
- Esquecer de lidar com requisições preflight `OPTIONS`, quebrando o CORS para chamadas POST/PUT.
- Armazenar `UPSTREAM_API_KEY` em `wrangler.toml` como uma variável simples em vez de um segredo.
- Usar `node:buffer` ou outros built-ins do Node.js, que não estão disponíveis no runtime do Workers.

## Prompt de Correção

```txt title="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.
```