Claude Code .env: keep secrets away from the agent
Stop Claude Code reading .env files and secrets: Read deny rules, the sandbox, PreToolUse hooks, env var scrubbing, and per command injection with op run.
To stop Claude Code reading .env, add Read(./.env) and Read(./.env.*) to permissions.deny in settings.json.
That blocks the file tools and shell commands Claude Code can parse, like cat .env. It does not stop a script
that opens the file itself, so turn on the sandbox for shell commands. The safest fix is no real secret in the repo
at all: inject values into one command at a time.
This guide is about secrets files and environment variables in your project. For giving an agent passwords and website logins, see Give AI agents passwords securely.
Why agents read .env files
An agent debugging a failing database connection looks for the config. In most projects that is .env. Claude
Code runs a built-in set of read-only commands such as cat, grep and head without asking
(permissions), so one cat .env is enough.
What the agent reads goes to the model and into the transcript. Claude Code writes transcripts as plaintext to
~/.claude/projects/<project>/<session>.jsonl, not encrypted, kept 30 days by default
(application data). The docs say it plainly:
if a tool reads a .env file or a command prints a credential, that value is written there.
Deny rules in settings.json
Put the rules in .claude/settings.json and commit it, so every teammate gets them. Deny rules apply right away,
without the workspace trust step that allow rules wait for
(settings).
{
"permissions": {
"deny": [
"Read(.env)",
"Read(.env.*)",
"Read(!.env.example)",
"Read(secrets/**)",
"Read(~/.aws/**)",
"Read(~/.ssh/**)"
]
}
}How the paths work (Read and Edit rules):
- Rules use gitignore syntax. A bare name like
Read(.env)matches at any depth under the current directory. ~/starts at your home directory,//at the filesystem root. A single leading/anchors at the settings file's location, not the root.- A
!rule carves paths out of the rules listed before it in the same file, so.env.examplestays readable. - Rules are checked deny, then ask, then allow. The first match wins.
A Read deny rule also blocks Edit and Write on that path, and Claude Code makes a best effort to apply it to Grep,
Glob and @file mentions. In Bash it covers redirects and file commands it recognizes, such as cat, head,
tail, sed and tee.
The limits, from the same page: a deny rule does not apply to grep -r pattern . run from the folder that holds the
file, or to a Python or Node script that opens files itself. Permission rules are enforced by Claude Code. A line in
CLAUDE.md saying "never read .env" is guidance the model may or may not follow.
There is no .claudeignore
Claude Code has no .claudeignore file. The permissions docs say that if your project has one, it has no effect,
and that you should move its entries into Read deny rules. A .gitignore entry does not block reads either; the
deny rules only borrow its pattern syntax.
The sandbox for shell commands
Deny rules match command text. The sandbox enforces at the operating
system level for Bash, on macOS, Linux and WSL2. Turn it on with /sandbox or sandbox.enabled.
By default the sandbox still lets commands read most of the machine, including ~/.ssh and ~/.aws/credentials.
So deny what matters:
{
"sandbox": {
"enabled": true,
"failIfUnavailable": true,
"allowUnsandboxedCommands": false,
"filesystem": {
"denyRead": ["~/**/.env"]
},
"credentials": {
"files": [
{ "path": "~/.aws/credentials", "mode": "deny" },
{ "path": "~/.ssh", "mode": "deny" }
],
"envVars": [
{ "name": "GITHUB_TOKEN", "mode": "deny" }
]
}
}
}A denied env var is unset before each sandboxed command runs. allowUnsandboxedCommands: false stops Claude Code
from retrying a failed command outside the sandbox. Network goes through a proxy that checks each host against your
allowed domains, which start empty.
The sandbox covers shell commands only. The Read tool, MCP servers and hooks run outside it, and a denyRead entry
does not stop the Read tool. Use deny rules and the sandbox together.
Block reads with a PreToolUse hook
A PreToolUse hook runs your own script before a tool call. It gets the call
as JSON on stdin: tool_input.file_path for Read, tool_input.command for Bash. Exit code 2 blocks the call and
stderr becomes the reason.
#!/bin/bash
# .claude/hooks/block-env.sh
input=$(cat)
target=$(jq -r '.tool_input.file_path // .tool_input.command // empty' <<<"$input")
if grep -qE '(^|[/ ])\.env' <<<"$target"; then
echo "Blocked: .env files are off limits" >&2
exit 2
fi
exit 0{
"hooks": {
"PreToolUse": [
{
"matcher": "Read|Bash",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-env.sh" }
]
}
]
}
}This catches python -c one liners that name the file, which deny rules miss. It is still text matching: a command
that builds the path at runtime gets through. Treat it as a tripwire, not a wall.
Environment variables leak too
Bash commands inherit Claude Code's environment. If you export STRIPE_KEY before you start claude, one env or
printenv puts it in the transcript.
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1strips credentials from the environment of Bash commands, hooks and stdio MCP servers. It spots them by name or value and leaves GitHub tokens and proxy settings in place (env vars).sandbox.credentials.envVarswithdenyunsets named variables for sandboxed commands.- The
envkey insettings.jsonsets variables for every session and its subprocesses. It is a plain file, often committed: no secrets there.
For values that already leaked, lower cleanupPeriodDays or run claude purge for the project.
Prompt injection raises the stakes
A README, an issue or a web page can carry text that tells the agent to read .env and send it somewhere.
Anthropic's security page lists the
guards: in Manual mode, network commands like curl prompt, and you can deny them outright. It also says no system
is immune. Deny rules stop the read, the sandbox network proxy stops the send. A secret that is not in the repo
cannot leak either way.
What Codex and Cursor offer
Cursor. .cursorignore blocks ignored files from Agent, Tab and
@ mentions. Cursor already ignores files in .gitignore and a default list that includes .env*. Two caveats from
the docs: the terminal and MCP tools the agent uses cannot block ignored files, and complete protection is not
guaranteed.
Codex. Commands run in a sandbox. The default workspace-write mode keeps network off unless you enable it
(approvals and security). A
permissions profile can deny reads by glob:
default_permissions = "project-edit"
[permissions.project-edit.filesystem]
":minimal" = "read"
[permissions.project-edit.filesystem.":workspace_roots"]
"." = "write"
"**/*.env" = "deny"For variables, shell_environment_policy controls what reaches subprocesses. Its ignore_default_excludes is
true by default, which keeps variables containing KEY, SECRET or TOKEN. Set it to false to drop them
(config reference).
Compared
| Control | File tool reads | Shell reads | Env var leaks | Limits |
|---|---|---|---|---|
Claude Code Read deny rules | Blocked | Recognized commands only | No | Scripts that open files |
| Claude Code sandbox | No | Blocked for denied paths | envVars deny | Bash only; macOS, Linux, WSL2 |
| PreToolUse hook | Your logic | By command text | No | Bypassable by obfuscation |
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | No | No | Scrubbed | Keeps GitHub tokens |
Cursor .cursorignore | Agent, Tab, @ | No | No | Not guaranteed |
| Codex permissions profile | Denied by glob | Denied by glob | shell_environment_policy | Needs config |
| Per command injection | Nothing to read | Nothing to read | One command only | Command can still print it |
Checked November 2026.
Inject secrets per command instead
The real fix: the repo holds references, not values. With 1Password CLI
the env file holds op:// references:
# .env: references only, safe for the agent to read
DATABASE_URL=op://dev/postgres/url
STRIPE_KEY=op://dev/stripe/secretop run --env-file=./.env -- npm run migrateop run resolves the references and sets the values only for that process. Secrets printed to stdout or stderr are
concealed by default; --no-masking turns that off (op run).
Doppler does the same with doppler run -- npm start. Keep the deny rules
anyway: a command can still print a value in a form the masking misses.
agexs cred
agexs cred does the same per command injection for Claude Code, with checks on every tool call. In a shell command the agent writes a placeholder:
psql "postgres://app:{{cred:prod-db/password}}@db.example.com/app"A hook turns it into agexs cred run, so the value reaches only that command, never the transcript or the command
line. You can run it yourself too:
agexs cred run --map PGPASSWORD=prod-db/password -- psql -h db.example.com -U app- Values in the command's output are masked.
- The hooks deny tool calls whose input carries a stored value and strip stored values from tool output, also base64, URL encoded, hex or reversed. A credential that showed up in output is locked until you change it.
- Credentials are encrypted in your browser. Only devices you confirmed get them.
- Each credential is
Auto,Ask onceorAsk every time.
If you already use 1Password and only need API keys in commands, op run is enough. agexs cred adds the leak checks
and approvals. See Agents and credentials and run agexs login, then agexs cred enroll.
FAQ
Can Claude Code read my .env file?
Yes, by default. File reads inside your working directory and cat need no approval. Add Read(.env) and
Read(.env.*) deny rules to block it.
Does Claude Code support .claudeignore?
No. Anthropic's docs say a .claudeignore file has no effect. Use permissions.deny with Read(...) rules instead.
Does a deny rule stop cat .env?
Yes. Claude Code applies Read deny rules to file commands it recognizes, like cat, head and sed. It does not
stop a script that opens the file itself. Use the sandbox for that.
How do I stop Claude Code from printing my environment variables?
Set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1, or deny named variables under sandbox.credentials.envVars. Better, do
not export secrets into the shell you start claude from.
Is a deny rule enough for production secrets?
No. It cuts the common path, not every path. Keep production values out of the repo and inject them per command
with op run, doppler run or agexs cred run.
Last updated on
MCP memory servers compared: agexs brain, Mem0, Zep and more
Compare MCP memory servers for Claude Code, Codex and Cursor. Hosting, team sharing, how memories reach the agent, rules, pricing and license.
Give AI agents passwords securely, without sharing them
How to give Claude Code and other AI agents passwords and API keys without pasting them into chat. Env vars, op run, password manager agent modes and agexs cred.