Prompt to Build a Cloudflare Worker API Proxy
Copy-paste AI prompt to build a Cloudflare Worker that proxies and rate-limits external API calls, adds auth headers, and caches responses.
CursorClaude CodeCodexWindsurf CloudflareTypeScript
Use this prompt to build a Cloudflare Worker that sits in front of an external API, injects auth headers, rate-limits by IP using Workers KV, and caches responses — so clients never see your upstream API key.
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.Implementation Notes
- Cloudflare Workers receive a
Requestand return aResponse— avoidexpress-style patterns. caches.defaultis the Cloudflare edge cache; it only works in production. UseMINIFLARE_CACHEfor local dev testing or mock the cache.CF-Connecting-IPis injected by Cloudflare — it is not spoofable from the public internet, but test locally with a hardcoded fallback IP.- Wrangler secrets are set with
wrangler secret put UPSTREAM_API_KEY— never store them inwrangler.tomlor committed.envfiles.
Expected File Changes
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)Acceptance Criteria
wrangler devstarts without errors and proxies aGET /to the upstream URL.- An IP sending 61 requests in one minute receives a
429on the 61st request. - A request from a non-allowed origin receives a
403. - The
Authorizationheader does not appear in the response or in any client-visible header. wrangler deploysucceeds and the Worker is live onworkers.dev.
Test Commands
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/; doneCommon AI Mistakes
- Using
process.envinstead of theenvparameter passed to the Workerfetchhandler. - Forgetting to handle
OPTIONSpreflight requests, breaking CORS for POST/PUT calls. - Storing
UPSTREAM_API_KEYinwrangler.tomlas a plain variable instead of a secret. - Using
node:bufferor other Node.js built-ins, which are not available in the Workers runtime.
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.