Stop Claude Code from overwriting your .env with a PreToolUse write guard
Permission deny rules can stop Claude Code from reading .env and key files. That still leaves a hole: a Write or Edit call can create or overwrite those paths. A small PreToolUse hook closes it. The hook Save
Permission deny rules can stop Claude Code from reading .env and key files. That still leaves a hole: a Write or Edit call can create or overwrite those paths. A small PreToolUse hook closes it.
The hook
Save this as .claude/hooks/block-secret-writes.sh and make it executable (chmod +x):
#!/usr/bin/env bash
# Reads the tool call as JSON on stdin; exit code 2 blocks it.
path=$(jq -r '.tool_input.file_path // .tool_input.path // ""')
if echo "$path" | grep -Ei '\.env([.-]|$)|\.(pem|key|p12|pfx)$|private.?key|id_rsa|wallet|mnemonic|credentials?'; then
echo "Blocked: '$path' looks secret-bearing. Do not let the agent write credentials, keys, or wallet material." >&2
exit 2
fi
exit 0
Register it in .claude/settings.json so it only runs on file writes:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{ "type": "command", "command": ".claude/hooks/block-secret-writes.sh" }]
}
]
}
}
What happens
When Claude tries to save a matching path, the hook exits with code 2. The write never happens, and the stderr message goes back to Claude so it can explain the block instead of retrying.
Tips
- Pair this with Read deny rules for
.env,~/.ssh/**, and~/.aws/**. Deny stops reads; this hook stops writes. - Keep the pattern list tight. If a project legitimately uses a
.keyextension for something safe, add an allow exception rather than deleting the hook. - Commit the hook so every teammate gets the same guardrail.
- Test with a harmless fixture such as
example.env, not a real secret.
Want the rest of the setup?
I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.