How to stop Claude Code from reading your .env files

Claude Code can read any .env file in the folder you start it in, and it doesn't ask first. File reads inside your working directory need no approval, and neither .gitignore nor a .claudeignore file changes that. What does change it is a Read deny rule in your settings, plus the sandbox, which makes the operating system refuse the read for every shell command Claude runs, not only the commands Claude Code recognises.

I covered the short version in How to let Claude Code use an API key without seeing it. This post goes further: which patterns match which files, what the sandbox blocks by default and what it doesn't, how to keep exported keys out of commands, when a hook is worth writing, and how to test the whole setup. I checked every setting against Anthropic's documentation in October 2026. Claude Code changes often, so the links say which version a feature needs.

Can Claude Code read my .env file?

Yes. Claude Code's permissions page puts file reads and Grep in the read-only group, which needs no approval inside your working directory and any directories you add. A .env file at the root of your project, or in services/api/, is one tool call away.

Three things people expect to help don't:

  • .gitignore. It stops git from tracking the file. In Claude Code, the respectGitignore setting only keeps ignored files out of the @ file picker. The Read tool still opens them.
  • .claudeignore. The permissions docs say it "has no effect" and tell you to move its entries into Read deny rules.
  • A line in CLAUDE.md. "Never read .env" shapes what Claude tries, but the docs are plain about it: "Permission rules are enforced by Claude Code, not by the model."

Other people have tested this. The Register found in January 2026 that Claude Code read a .env file despite a .claudeignore entry, and again despite a .gitignore entry, while a deny rule in .claude/settings.json blocked it. A developer's test in August 2026 found the same pattern: with no rule, the agent opened a planted .env file in every run while debugging a database error, and a Read deny rule stopped it every time.

Which deny rules block .env files?

Put deny rules in ~/.claude/settings.json so they apply in every project. These cover the usual places keys live:

json
{
  "permissions": {
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(secrets/**)",
      "Read(~/.aws/**)",
      "Read(~/.ssh/**)"
    ]
  }
}

The rules use gitignore patterns, and small differences decide what they cover:

Rule Blocks Doesn't block
Read(./.env) .env in the folder you started in services/api/.env
Read(.env) .env at any depth under that folder .env in a parent folder
Read(.env.*) .env.local, .env.production, and .env.example too prod.env
Read(secrets/**) a secrets folder at any depth files outside it
Read(//**/.env) .env anywhere on the disk nothing

Three more details from the permissions docs save time:

  • One leading slash is not an absolute path. In user settings, Read(/secrets/**) means ~/.claude/secrets/**. Use ~/ for your home folder and // for the root of the disk.
  • A Read deny rule also blocks Edit and Write on that path, so Claude can't overwrite your .env either. (Write is covered from v2.1.228.)
  • You can carve out a file. If you want Claude to read .env.example, add "Read(!.env.example)" after the .env.* rule. A ! pattern removes files from the rules listed before it in the same file.

Run /permissions in a session to see every rule and the settings file it came from.

What do deny rules miss?

Deny rules are checked against what Claude asks for, not against what the operating system does. The docs list where they stop. They apply to Claude's file tools, to file commands Claude Code recognises in Bash (cat, head, tail, sed, tee) and to redirects such as < .env. They "don't apply to a command that reads files without naming them, such as grep -r pattern .", or to "a Python or Node script that opens files itself".

So with deny rules alone, each of these still shows Claude your keys:

bash
grep -r STRIPE .
python3 -c "print(open('.env').read())"
node -e "require('dotenv').config(); console.log(process.env)"

None of them looks like an attack. A model debugging a failing test can write any of them on its own. The first one doesn't even prompt, because grep is on Claude Code's built-in list of read-only commands.

A table: Read deny rules alone block the Read tool and cat, but not grep -r or scripts; with the sandbox on, grep -r and scripts are blocked too; neither stops MCP servers, hooks or printed output
Deny rules stop the obvious reads. The sandbox stops the rest of the shell.

How does the sandbox close those gaps?

The sandbox makes the operating system enforce the block on the running process: Seatbelt on macOS, bubblewrap on Linux and WSL2. On native Windows, Claude Code runs commands unsandboxed, so use WSL2 there. It's off by default.

Turn it on with /sandbox in a session, or for every project in ~/.claude/settings.json:

json
{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "filesystem": {
      "denyRead": ["~/**/.env", "~/**/.env.*", "~/.aws", "~/.ssh"]
    }
  }
}

What each line does, per the sandboxing docs:

  • enabled starts every shell command Claude runs, and every process those commands start, inside the boundary.
  • failIfUnavailable makes Claude Code exit if the sandbox can't start. Without it, a missing dependency means commands quietly run unsandboxed.
  • allowUnsandboxedCommands: false turns off the escape hatch where Claude retries a failed command outside the sandbox. With the hatch open you get a prompt titled "Bash command (unsandboxed)", which is easy to approve without reading.
  • denyRead blocks those paths for sandboxed commands. Claude Code also adds the paths from your Read deny rules to this list. I spell out the home-folder patterns anyway, so the sandbox block doesn't depend on how a relative rule gets translated.

The defaults explain why denyRead is needed. Sandboxed commands can write only to the working directory and a temp folder, but they can read "most of the machine, including credential files such as ~/.ssh and ~/.aws/credentials", and the docs add that "there is no built-in credential deny list". Network access goes through a local proxy that allows only the domains you approve, starting from none, and UDP and ICMP traffic (so ping) can't leave at all.

With this on, the grep -r and Python examples above fail to open .env, because the operating system refuses the read, not because a pattern matched the command.

Order of checks: a PreToolUse hook runs first, then deny, ask and allow rules, then the sandbox enforces the block on the running command, so the .env file is never read
Each layer catches what the one before it can't see.

Test it once, in a scratch project:

  1. Create .env with a made-up line such as CANARY_KEY=not-a-real-key.
  2. Ask Claude to read the file, then to run grep -r CANARY ., then python3 -c "print(open('.env').read())".
  3. The Read tool should refuse and name the rule, and both commands should fail with a permission error. If anything prints the canary, open /sandbox and check the Config tab, which shows the settings Claude Code resolved.

For the sandbox itself, the docs suggest asking Claude to run touch ~/sandbox-probe. Inside the sandbox on macOS it fails with Operation not permitted.

What about keys in exported variables?

Files are half the problem. Sandboxed commands inherit Claude Code's environment, "including any secrets in its environment", so an export OPENAI_API_KEY=… in your ~/.zshrc reaches every command Claude runs. In the August test above, printenv asked for approval first, but any script can print what it inherited.

Three settings help:

  • sandbox.credentials lists variables to unset before each sandboxed command:

    json
    {
      "sandbox": {
        "credentials": {
          "envVars": [
            { "name": "OPENAI_API_KEY", "mode": "deny" },
            { "name": "STRIPE_SECRET_KEY", "mode": "deny" }
          ]
        }
      }
    }

    The same block has a mask mode: commands see a placeholder, and the sandbox proxy swaps in the real value only on requests to hosts you allow. It needs the proxy's TLS termination, which the docs mark as experimental.

  • CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 strips credentials from every subprocess Claude Code starts, sandboxed or not, including hooks and local MCP servers. The environment variables reference says it recognises a credential "by its variable name or by the shape of its value" (NPM_TOKEN, DB_PASSWORD, a DATABASE_URL with a password in it), and it leaves GITHUB_TOKEN in place on purpose. Setting it also turns off the sandbox's auto-allow mode, so expect more prompts.

  • Keep keys out of the env block of settings.json. The settings reference notes those values are plain text and "reach every subprocess Claude Code starts".

The cleaner fix is to stop exporting keys at all. Start Claude Code from a shell that doesn't have them, and give keys to one command at a time with keyfold run or op run, as the earlier post shows.

When is a hook worth writing?

A PreToolUse hook runs your script before every matching tool call, ahead of the permission rules, in every permission mode. It gets the call as JSON on standard input. Exiting with code 2 blocks the call and sends your message on standard error to Claude as the reason. Use one for a rule the patterns can't express, such as "no shell command that names a .env file, whatever the program".

This script adapts the protect-files example in Anthropic's hooks guide. I tested it against file paths and commands before putting it here:

bash
#!/bin/bash
# .claude/hooks/block-env.sh: refuse file tool calls and commands that name a .env file
set -eo pipefail
INPUT=$(cat)
TARGET=$(jq -r '.tool_input.file_path // .tool_input.command // empty' <<<"$INPUT")
TARGET=${TARGET//.env.example/}   # the example file is fine

if grep -Eq "(^|[[:space:]/\"'=<])\.env" <<<"$TARGET"; then
  echo "Blocked by block-env.sh: .env files are off limits. Ask me instead." >&2
  exit 2
fi
exit 0

Make it executable with chmod +x, then register it in .claude/settings.json:

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Edit|Write|Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-env.sh",
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

The onFailure line matters more than the script. By default, a hook that crashes or can't be found counts as a "non-blocking error" and the tool call goes ahead, so a typo in the path turns your guard off without a sound. With "onFailure": "block" (Claude Code v2.1.295 or later) a broken hook blocks instead, and set -eo pipefail makes the script fail, and so block, if jq is missing.

Know the limit: a hook reads the command as text. cat .e''nv or a file name decoded from base64 gets past any pattern. A hook catches an agent's honest mistakes; the sandbox is what holds against a command written to get around it. Hooks also run outside the sandbox with your full access, so review a hook script the way you'd review any code you run.

What do these settings still not cover?

  • Printed output. If a command Claude is allowed to run prints a key, such as a test that logs its config or an error message with a database URL in it, the key is in the conversation. No setting filters output.
  • Processes outside the sandbox. Claude's own file tools follow permission rules, not the sandbox. Local MCP servers, hooks and commands you type at the ! prompt run with your full access. The sandbox's domain list doesn't limit WebFetch either; WebFetch has its own WebFetch(domain:…) rules.
  • Your own paste. A key you paste into the prompt is in the conversation whatever the settings say. Rotate it afterwards.

If you use Keyfold with Claude Code, two details follow from the above. No Keyfold tool returns a secret value, but keyfold_run starts its command inside Keyfold's MCP server process, which is outside Claude Code's sandbox. The checks on that path are Claude Code's own prompt for the tool call, which shows what Claude is about to do, and Keyfold's approval sheet, which shows the client, project and environment and the command it will run. Keep Claude Code's prompt on for keyfold_run even so: under an "Allow for 1 hour" grant Keyfold shows no new sheet, so a later command could run without you seeing it. And because the macOS sandbox blocks every Unix socket by default, a keyfold run that Claude starts inside the sandbox can't reach the app until you add Keyfold's socket, ~/Library/Application Support/com.cwksolutions.keyfold/agent.sock, to sandbox.network.allowUnixSockets.

Open the approval sheet in the live demoOpens the live demo, with made-up keys

A setup you can copy

  1. Add the Read deny rules to ~/.claude/settings.json.
  2. Turn on the sandbox with failIfUnavailable, without unsandboxed retries, and with denyRead entries for .env files and credential folders.
  3. Set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, or list your key names under sandbox.credentials.
  4. Remove the export lines for keys from your shell profile.
  5. Add the hook with "onFailure": "block" if you want a second net.
  6. Test once with a canary .env, and again after a Claude Code update that changes permissions.

Steps 1 to 3 in one file:

json
{
  "permissions": {
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(secrets/**)",
      "Read(~/.aws/**)",
      "Read(~/.ssh/**)"
    ]
  },
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "filesystem": {
      "denyRead": ["~/**/.env", "~/**/.env.*", "~/.aws", "~/.ssh"]
    }
  },
  "env": {
    "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB": "1"
  }
}

The most reliable .env rule is the one you don't need. If keys live in an encrypted vault and reach a command only when you approve it, there's no file in the project for Claude to open. That's what I built Keyfold for: keys by project and environment, handed to commands after a click in the app, with no tool that hands a value back to the model.

FAQ

Does .gitignore stop Claude Code reading .env files?

No. In Claude Code, .gitignore only hides files from the @ file picker. The Read tool, cat and scripts still open them. Use Read deny rules, and the sandbox for everything else.

Do deny rules still apply in auto mode or bypassPermissions?

Yes. The permission modes page says "Deny rules block in every mode, including bypassPermissions". The sandbox holds in every mode too, because the operating system enforces it.

Does the sandbox work on Windows?

Not natively. On native Windows, Claude Code runs commands unsandboxed; inside WSL2 the sandbox works the same as on Linux. Deny rules and hooks work everywhere.

Will the sandbox break my tests?

It can, if your tests read .env or need a host you haven't allowed. In Manual mode Claude Code asks before a command reaches a new domain, and the /sandbox Config tab shows what's allowed. Tests that receive keys as environment variables when they start don't need the file at all.

Where can I see how Keyfold handles agent requests?

The live demo shows the approval sheet with made-up keys, and the security page explains what the CLI and MCP server can and can't ask for. Why Keyfold's MCP server has no reveal tool covers the design.