You ask Claude Code to add a DNS record or deploy a Worker, and it tells you it needs a Cloudflare API token. The easy thing is to copy the token from the dashboard and paste it into the chat. The agent starts working at once, which is why nearly everyone does it.
The trouble is that the chat does not go away. The conversation with your agent is saved on disk, it is sent in full to the model provider with every message, and it ends up with whoever you send a log to when you need help. The token sits in all of those places along with everything else.
Below is how we set this up for ourselves: our agent deploys and edits zones every day and has never seen the token. Cloudflare’s and Claude Code’s documentation was checked on 19 November 2026.
The short version has four steps:
- Create a token that can do only what the agent needs.
- Keep it in a file and let a small script hand it to your tools.
- Add a hook that stops the agent from opening that file.
- Put your own tokens in through the clipboard, not the chat.
Why not the chat
Pasting the token into a message is the obvious way to expose it, and not the only one. If you
ask the agent to “check what is in .env”, it reads the file, and the whole file lands in the
conversation the same way. If you have two agent windows open on two projects and one sends the
other a key in a message, the key stays in the history of both.
There is a less obvious case too. In Claude Code you can type a command after !, and it feels
like your own terminal. The documentation
says plainly that this mode “adds the command and its output to the conversation context”. Type
a token into such a command and it goes into the conversation, along with whatever the command
prints.
Step 1. A token that can do very little
Start with what the token can do, before you think about where to keep it. The Global API Key is the wrong choice for an agent: Cloudflare’s own page says it “has the exact same permissions as the user”, so it can do anything you can. The one job where you may still need it is adding zones in bulk, covered in the zone limit guide. For everything else an agent does, use an ordinary API token with limits.
Cloudflare’s token builder has four settings worth using. The first two are on that page, the other two on the page about restricting tokens.
| Setting | What Cloudflare says | What to choose for an agent |
|---|---|---|
| Permissions | “Choose the permissions to grant within the policy.” | Only what the task needs, read where read is enough |
| Resources | “specific accounts or zones” | Only the zones the agent works on |
| Client IP address filtering | “Once an Is in rule is applied, the token can only be used from the defined IP addresses.” |
Your office or server addresses, in CIDR |
| TTL | “By default, tokens do not expire and are long lived.” | An end date that matches the job |
Check one permission separately. Once you have a token, the API lets you make more: “you can create additional API tokens”. The permission behind that is API Tokens Write, and the permission list describes it as “Grants write access to user’s API tokens”. If a token with it leaks, whoever has it can make new tokens, and revoking the old one no longer helps. An agent never needs it.
Cloudflare shows a token once (“The token secret is only shown once”), and new tokens start
with cfut_, which Cloudflare calls a “scannable format” so that secret scanners can find a token
in a repository. No scanner reads your conversation with an agent, though. Once a token is in
there, all you can do is revoke it and create a new one.
Step 2. Let a script pass the token on, not the agent
Put the token in a file that git ignores. Ours is .dev.vars; many projects use .env. Then
you need a small script that reads the file and starts the program you want, wrangler for
example, with the token in its environment variables. The agent calls the script, wrangler gets
the token, and only the result reaches the conversation. This blog deploys exactly this way. The
smallest version of the script:
// with-token.mjs: node with-token.mjs <node script> [args...]
// Runs a Node script with the Cloudflare token from .dev.vars in its environment.
// Nothing from the file is printed; the token never appears on a command line.
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
const KEYS = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID'];
const env = { ...process.env };
for (const line of fs.readFileSync('.dev.vars', 'utf8').split(/\r?\n/)) {
const eq = line.indexOf('=');
const key = line.slice(0, eq).trim();
const value = line.slice(eq + 1).trim().replace(/^(['"])(.*)\1$/, '$2'); // KEY="value" too
if (eq > 0 && KEYS.includes(key)) env[key] = value;
}
const missing = KEYS.filter((k) => !env[k]);
if (missing.length) {
console.error(`.dev.vars has no ${missing.join(', ')}`);
process.exit(2);
}
const r = spawnSync(process.execPath, process.argv.slice(2), { stdio: 'inherit', env });
process.exit(r.status ?? 1);
To check it, ask the agent to run
node with-token.mjs node_modules/wrangler/bin/wrangler.js whoami. Wrangler answers that it is
“logged in with an Account API Token”, taken “from the CLOUDFLARE_API_TOKEN environment variable”,
and the token itself is nowhere in the answer. The script takes only the two variables it needs
from the file and starts the program directly, without a shell, so the token does not end up in
your command history either.
So that the agent remembers the script, add one line to the project’s CLAUDE.md or AGENTS.md:
run wrangler through node with-token.mjs, and never open the token file.
Step 3. Stop the agent from opening the token file
A line in the instructions is a request. An agent can forget it, especially in a long session,
and one day run cat .env to “check the settings”. That is what a hook is for: Claude Code runs
a PreToolUse hook before every action the agent takes, and the hook can refuse the action. Codex has hooks too,
but it runs one it did not ship only after you trust it in /hooks.
Our hook looks at which file the agent wants and which command it is about to run, and refuses
when it finds a secret file there: .env and .env.* (but not .env.example), .dev.vars,
anything inside a .secrets folder, *.pem, id_rsa. It is in the open
secret-handoff repository, and the README has the
settings for Claude Code and Codex ready to copy.
Two things are easy to get wrong when you install it.
- The hook has to cover every tool that can read a file. In Claude Code’s settings that is
the matcher, a list of tool names. On Windows the agent runs commands through
PowerShell, notBash, so with onlyBashin the listcat .envis blocked andGet-Content .envgoes through. Another tool people forget isGrep: it prints the lines it finds, so it reads files too. Our list isRead|Edit|Write|Grep|Bash|PowerShell. - Make sure it really blocks. On Windows Claude Code may start hooks through PowerShell, and
PowerShell turns exit code 2 into 1. Claude Code treats 1 as a hook error and lets the action
go ahead. We thought we were covered until we asked the agent to read
.envand watched it do so.
That is the only test that counts: by hand, with a real agent. Ask it to read a file from
.secrets and to show you .env. Both requests should end in a refusal. This is how we caught
our own mistake. The hook looked only at the file name at the end of a path, so a whole .secrets
folder was blocked while cat .secrets/token.txt went through, because token.txt is a harmless
name. That version was running on this blog while we wrote this guide.
If you write your own hook, try it on a few more cases that the review of ours turned up:
- an allowed command, a line break, and a second command such as
cat .env; - a path that only looks like the trusted script’s path, such as
evil.agents/skills/…/handoff.sh; - a
Grepsearch withglob: .env.
Step 4. Put your own token in without pasting it anywhere
That leaves the question of how a token from the Cloudflare dashboard gets into the file. Opening
the file and pasting it in by hand is fine. If you are working in the agent’s window anyway,
there is a simpler way: copy the token and run this command from the same repository in the
agent’s prompt (on macOS and Linux, python3 instead of py -3):
! py -3 $HOME/.agents/skills/secret-handoff/handoff.py put cloudflare-token-blog --clipboard
Only that line reaches the conversation, and all it holds is the name cloudflare-token-blog. The
script takes the token from the clipboard, saves it in a locked folder in your home directory and
clears the clipboard if it still holds the same token. The reply shows the name and the length,
not the value. It also warns you that a copy may remain in your clipboard history: Win+V on
Windows, the clipboard history on macOS, a clipboard manager on Linux. Clear that yourself. Then
tell the agent where the token belongs, and it moves it into the project’s file with take,
again without seeing it.
The same tool helps when a key is needed in another project. Say an agent in one window has just issued an API key, and the agent in the next project is the one that will use it. Sending the key in a message would put it back in a conversation. Instead, the first agent puts the key into the same locked folder and the second takes it out:
handoff.sh put <name> --from <file> [--line N | --key VAR] [--remove-source]
handoff.sh take <name> --into <secret file> [--key VAR]
handoff.sh drop <name>
handoff.sh list
The message between the projects carries only the key’s name and what it is for. take writes
the key only into a file the hook protects, and with --remove-source the sender keeps no copy.
A key nobody will collect is removed unread with drop. The hook allows a single call of this
script and does not let a second command ride along with it. For the hook to recognise the
script, clone the repository to the place the README names:
git clone https://github.com/investblog/secret-handoff ~/.agents/skills/secret-handoff
What this does not protect against
All of this is a seatbelt against an agent’s mistake. It will not stop an agent that is set on
reaching the key. The hook sees the text of a command, so it misses a path put together on the
fly (.sec''rets, a wildcard, a variable). It cannot help once the token itself is in the text of
a request; for that you need a second check, a commit hook that scans for secrets. The hook needs
Python: if it cannot find Python, it lets everything through rather than lock the agent out
completely. In Codex the hook reads the whole text of a patch, so it also refuses an edit to a
document that merely mentions .env; make that edit with another tool.
And about !: the command line always goes into the conversation. The clipboard keeps the value
out of it, but your command history and clipboard history are yours to clean.
If you build an API for agents yourself
So far this was about who sees a key. If you are building a service that agents will call, such as an MCP server on Workers, you can also make a leaked key worth little. In the open source clx it works like this: a key can only be issued from an account a person has signed in to, so a key cannot issue another key. Each key has its own permissions and, if you want, a list of allowed Cloudflare accounts and IP addresses. The server stores only a hash and shows the key once. And the script that issues a key revokes it by itself if the server’s answer was lost or the key could not be saved, so no working key is left lying around unaccounted for.
When you need clx or 301.st
If the Cloudflare account is yours and you run one agent, a narrow token, the script and the hook are enough. All of it is free.
clx counts visits, short link clicks and QR scans on your own sites, with a Worker and a D1 database it installs into your Cloudflare account. Its API keys work the way described above, so you can hand them to an agent without worry.
301.st does the same with the Cloudflare token itself. You create a temporary token that is allowed to create tokens. 301.st uses it once to make its own working token, with a fixed set of permissions that does not include creating tokens and with an end date five years out. Then it deletes the temporary token and stores the working one encrypted. If Cloudflare refuses the delete, 301.st logs it and the temporary token stays in your dashboard for you to remove. From then on 301.st runs redirects, traffic rules and zones for your whole portfolio with that working token.