AI Automation
Secure API Key Management for Cloudflare Workers AI in Small Companies
TL;DR: Keep Cloudflare Workers AI API keys out of source code, store them as encrypted Workers Secrets (or in a vault), rotate them at least every 90 days, automate injection via wrangler, and log every access for audit. Follow the checklist below before you push any worker to production.
Why API Key Security Matters for Cloudflare Workers AI
Cloudflare Workers AI lets you call powerful LLM models from edge functions. The API token you use grants unrestricted access to those models and any attached billing account. If the token leaks, an attacker can consume credits, exfiltrate data, or embed malicious prompts that affect downstream users. Small teams often store keys in plain text files or embed them in GitHub repos—an easy target for accidental exposure.
Store Secrets Outside the Codebase
Cloudflare provides two first‑class mechanisms for secret management:
- Workers Secrets – encrypted values stored by Cloudflare and injected at runtime as environment variables. Use the
wrangler secretcommand to add, update, or delete them. - KV Namespace (encrypted) – for larger payloads, you can store encrypted blobs in Workers KV and decrypt them inside the worker.
Both methods keep the secret out of your Git history and prevent accidental commits.
Example: Adding a Workers Secret
wrangler secret put CLOUDLAYER_API_KEY
# you will be prompted for the value; it is stored encrypted on Cloudflare
In your worker code, access it via process.env.CLOUDLAYER_API_KEY (Node) or env.CLOUDLAYER_API_KEY (standard Workers runtime).
Rotate Keys Regularly and Automate the Process
Rotation limits the window of exposure. Cloudflare does not rotate tokens automatically, so you need a manual or scripted cadence.
- Generate a new API token in the Cloudflare dashboard with the same scopes.
- Update the Workers Secret using
wrangler secret put(the old value is overwritten). - Trigger a deployment so the new token is loaded by all edge instances.
- Revoke the previous token after the new one is confirmed active.
Automate steps 1‑3 with a CI/CD job that calls the Cloudflare API to create a token, stores it in a temporary secret store (e.g., HashiCorp Vault), runs wrangler secret put, and then pushes the worker.
Integrate Secret Management into Your CI/CD Pipeline
Most small teams use GitHub Actions or GitLab CI. Below is a minimal GitHub Actions snippet that pulls a secret from GitHub Secrets (which should be encrypted) and pushes it to Cloudflare Workers Secrets.
name: Deploy Worker
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Wrangler
run: npm i -g @cloudflare/wrangler
- name: Set Cloudflare API Token
env:
CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
run: echo "$CF_API_TOKEN" | wrangler secret put CLOUDLAYER_API_KEY
- name: Publish Worker
run: wrangler publish
Notice that the actual model‑access token never appears in the repo; it is injected at the last step.
Audit Access and Monitor Usage
Even with proper storage, you should know who is calling the AI model and when. Cloudflare provides request logs and analytics. Combine them with a lightweight log wrapper inside your worker:
async function fetchModel(prompt) {
const start = Date.now();
const resp = await fetch('https://api.cloudflare.com/client/v4/accounts/.../ai/run', {
method: 'POST',
headers: { 'Authorization': `Bearer ${CLOUDLAYER_API_KEY}` },
body: JSON.stringify({ prompt })
});
const duration = Date.now() - start;
console.log(JSON.stringify({
event: 'ai_call',
promptLength: prompt.length,
status: resp.status,
durationMs: duration,
timestamp: new Date().toISOString()
}));
return resp.json();
}
These logs are automatically sent to Cloudflare's logpush service or can be piped to a third‑party SIEM for further analysis.
Pre‑Launch Checklist
| Item | Verification |
|---|---|
| API key stored as Workers Secret | Run wrangler secret list and confirm presence |
| No hard‑coded keys in repo | Search for regex AKIA|cloudflare|api_key in Git history |
| Rotation schedule documented | Calendar entry or CI job with 90‑day cadence |
| Access logs enabled | Logpush configured to external bucket or SIEM |
| Least‑privilege token scopes | Token only has AI Run permission, no extra account admin rights |
Run through this list before you click “Publish”. It reduces the chance of accidental exposure and keeps you compliant with frameworks like the NIST AI RMF.
Reference Security Standards
Both the NIST AI Risk Management Framework and the OWASP Top 10 for LLM Applications recommend secret management, rotation, and audit logging as core controls. Aligning your Cloudflare Workers AI deployment with these guidelines helps you demonstrate due diligence to partners and regulators.
Conclusion
Secure API key handling for Cloudflare Workers AI is straightforward: keep keys out of code, use Workers Secrets, rotate them on a schedule, and log every call. By embedding these steps into your CI/CD pipeline and checking the pre‑launch checklist, a small team can reap the benefits of edge‑based AI without exposing critical credentials.
FAQ
- Can I store multiple API keys for different models? Yes. Create separate Workers Secrets (e.g.,
CLAUDE_API_KEY,GPT4_API_KEY) and reference the appropriate one in each worker. - What if I need to share a key with a third‑party service? Generate a scoped token with the minimum required permissions and store it in that service’s secret manager, never in plain text.
- Do Workers Secrets encrypt data at rest? Cloudflare encrypts all secret values on their servers and never returns the raw value via the API.
- How do I revoke a compromised key? Delete the secret with
wrangler secret delete, revoke the token in the Cloudflare dashboard, and issue a new one as soon as possible. - Is there a limit to the size of a Workers Secret? Secrets are limited to 4 KB each, which is ample for API tokens but not for large certificates.
Want this kind of automation built for your workflow?
AISecAll designs, builds, deploys, and maintains focused AI automations for small companies and independent entrepreneurs.