Keep Claude Code out of your .env files
Short version: add Read(./.env)-style deny rules to .claude/settings.json. They’re built in and cover more than you might expect. Then add a PreToolUse hook for the shell commands they don’t cover.
What Read deny rules already cover
From the Claude Code permissions docs:
- A
Read(path)deny rule blocks Claude’s file tools from reading that path. Claude Code also makes a best-effort attempt to apply it to Grep, Glob and@filementions. - In Bash commands Claude Code can analyze, Read deny rules also apply to redirection targets and to file commands it recognizes, such as
cat,head,tail,sedandtee. - They don’t apply to commands that read files without naming them, like
grep -r pattern ., or to scripts that open files themselves, like a Python or Node program. - A
.claudeignorefile has no effect. Move its entries into Read deny rules.
Step 1: deny rules
Paths starting with ./ are relative to the project. List the variants your project uses. A broad Read(./.env.*) would also hide .env.example, which the agent usually needs.
Step 2: a hook for the rest
Commands such as source .env, cp .env /tmp/x or less apps/web/.env name the file, so a command check can catch them. Save this as .claude/hooks/block-env-files.sh and chmod +x it:
#!/usr/bin/env bash
# block-env-files.sh: keep the agent from reading .env files (.env, .env.local, .env.production ...).
# .env.example / .env.sample / .env.template / .env.dist stay readable.
# Works as: Cursor beforeReadFile + beforeShellExecution, Claude Code PreToolUse (Read|Grep|Bash).
# Needs jq.
input=$(cat)
event=$(jq -r '.hook_event_name // empty' <<<"$input")
path=$(jq -r '.file_path // .tool_input.file_path // .tool_input.path // empty' <<<"$input")
cmd=$(jq -r '.command // .tool_input.command // empty' <<<"$input")
# a word that is a .env file name (optionally with a directory in front), not an example/template
ENV_RE='(^|[[:space:]/"'"'"'=<:])\.env(\.[A-Za-z0-9_-]+)*([[:space:]"'"'"';|&)>]|$)'
SAFE_RE='\.env\.(example|sample|template|dist)([[:space:]"'"'"';|&)>]|$)'
hit=no
if [ -n "$path" ]; then
base=${path##*/}
if [[ "$base" =~ ^\.env(\.[A-Za-z0-9_-]+)*$ ]] && ! [[ "$base" =~ ^\.env\.(example|sample|template|dist)$ ]]; then hit=yes; fi
fi
if [ "$hit" = no ] && [ -n "$cmd" ]; then
# drop the safe names first, then look for any remaining .env file name
stripped=$(printf '%s' "$cmd" | sed -E 's/\.env\.(example|sample|template|dist)//g')
if printf '%s' "$stripped" | grep -Eq "$ENV_RE"; then hit=yes; fi
fi
reason="Blocked: .env files hold secrets and are off-limits to the agent. Use .env.example for variable names, or ask the user."
if [ "$hit" = yes ]; then
case "$event" in
beforeReadFile) jq -n --arg r "$reason" '{permission: "deny", user_message: $r}' ;;
beforeShellExecution) jq -n --arg r "$reason" '{permission: "deny", user_message: $r, agent_message: $r}' ;;
*) jq -n --arg r "$reason" '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}' ;;
esac
exit 0
fi
case "$event" in
beforeReadFile|beforeShellExecution) echo '{"permission": "allow"}' ;;
esac
exit 0Step 3: settings.json
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.local)",
"Read(./.env.*.local)",
"Read(./.env.production)",
"Read(./.env.development)",
"Read(./secrets/**)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Read|Grep",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-env-files.sh",
"timeout": 10
}
]
}
]
}
}The matcher Bash|Read|Grep runs the hook for shell commands and for file reads and searches. For Read it checks tool_input.file_path, and for Grep it checks tool_input.path. .env.example and similar template files stay readable.
Step 4: test
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"source .env"}}' \
| .claude/hooks/block-env-files.shYou should see "permissionDecision": "deny". Restart Claude Code and run /hooks to check it’s loaded.
What still gets through
grep -r API_KEY .run from the project root, and programs that read.envthemselves (your app’s own dotenv loader, for example). For OS-level enforcement, the docs recommend enabling Claude Code’s sandbox.- Anything already in the conversation. If a secret was pasted or printed earlier, rotate it.
Best fix of all: keep production secrets out of the working copy. Use development-only keys locally.