P PasteCode
提示词

构建 Cloudflare Worker API 代理的提示

复制粘贴 AI 提示,构建一个 Cloudflare Worker,用于代理外部 API 调用并限速、添加认证头以及缓存响应。

CursorClaude CodeCodexWindsurf CloudflareTypeScript
.md .json 难度: 中等 更新于 2026年6月8日

使用此提示构建一个 Cloudflare Worker,它位于外部 API 之前,注入认证标头,通过 Workers KV 按 IP 进行速率限制,并缓存响应——这样客户端就永远看不到你的上游 API 密钥。

主要提示

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.

实现说明

  • Cloudflare Workers 接收 Request 并返回 Response——避免使用 express 风格的模式。
  • caches.default 是 Cloudflare 边缘缓存;仅在生产环境中有效。在本地开发测试中使用 MINIFLARE_CACHE 或模拟缓存。
  • CF-Connecting-IP 由 Cloudflare 注入——从公共互联网无法伪造,但在本地测试时使用硬编码的回退 IP。
  • Wrangler 密钥通过 wrangler secret put UPSTREAM_API_KEY 设置——切勿将它们存储在 wrangler.toml 或已提交的 .env 文件中。

预期文件变更

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)

验收标准

  • wrangler dev 启动无错误,并将 GET / 代理到上游 URL。
  • 一分钟内发送 61 次请求的 IP 在第 61 次请求时收到 429
  • 来自未允许来源的请求收到 403
  • Authorization 标头不出现在响应或任何客户端可见的标头中。
  • wrangler deploy 成功,Worker 在 workers.dev 上运行。

测试命令

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

常见 AI 错误

  • 使用 process.env 而不是传递给 Worker fetch 处理程序的 env 参数。
  • 忘记处理 OPTIONS 预检请求,导致 POST/PUT 调用的 CORS 失效。
  • UPSTREAM_API_KEY 作为普通变量存储在 wrangler.toml 中,而不是作为密钥。
  • 使用 node:buffer 或其他 Node.js 内置模块,这些在 Workers 运行时中不可用。

修复提示

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.