Workers can use API keys and credentials without exposing them to the frontend. Secrets are set via MCP tools and accessed in worker code through a safe API.
Setting secrets
// Personal secret — available to all your worker spaces
set_secret({ name: "OPENAI_KEY", value: "sk-..." })
// Org secret — shared across all spaces in the org
set_secret({ name: "OPENAI_KEY", value: "sk-...", scope: "org", org: "my-team" })
// Restrict where the secret can be sent
set_secret({
name: "OPENAI_KEY",
value: "sk-...",
allowed_urls: ["https://api.openai.com/"]
})
Using secrets in worker code
export default {
async fetch(request, env) {
const key = await env.secrets.get("OPENAI_KEY");
const allNames = await env.secrets.list();
// Use in API calls — safe, stays server-side
const resp = await fetch("https://api.openai.com/v1/chat/completions", {
headers: { "Authorization": "Bearer " + key },
// ...
});
}
};
Safety layers
- Isolated API — secrets are NOT on
envdirectly.JSON.stringify(env)andObject.keys(env)won't reveal them. Access only viaenv.secrets.get(name). - Fetch interception — if a secret has
allowed_urls, outboundfetch()calls are inspected. Requests containing the secret sent to non-allowed URLs are blocked (403). - Response redaction — text and JSON response bodies are scanned for secret values. Matches are replaced with
[REDACTED]before reaching the browser.
Was this page helpful?