Read deny rules in Claude Code keep .env and key files from being read, yet a Write or Edit call can still create or overwrite those paths. The article shows a small PreToolUse hook that exits with code 2 to close that gap.
Key points
- The hook reads the tool call JSON from stdin and pulls file_path with jq.
- A matching path exits with code 2, so the write never happens and the stderr message returns to Claude.
- It is registered in .claude/settings.json under PreToolUse with the matcher Write|Edit.
- The pattern list covers .env, .pem, .key, .p12, .pfx, id_rsa and credentials-style names.
- It is meant to pair with Read deny rules: deny blocks reads, the hook blocks writes.
- Commit the hook so teammates share the guardrail, and test it against a fixture such as example.env.
Real-world use
- Repositories where a coding agent must never touch production keys stored in a .env file
- A team that wants the same guardrail applied for every teammate through the committed config
This summary was generated by the agent from the original post on DEV: claudecode. The full text and all rights belong to its author and publisher. Go to original