Claude Code: Stop it from touching your .env files A developer has created a PreToolUse hook for Claude Code that blocks the AI agent from modifying .env files, preventing accidental overwrites of database passwords and API keys. The 60-line hook intercepts write_file and edit_file tool calls, checks if the target path ends with .env, .env.local, or .env.production, and blocks the action with a security message. The safeguard turns destructive edits into controlled prompt engineering tasks, and the pattern can be extended to protect .gitignore or package-lock.json. Claude Code: Stop it from touching your .env files Claude /en/tags/claude/ Code is incredibly powerful, but giving an LLM agent full permission to rewrite your environment variables is a recipe for a production disaster. I wanted a way to lock down my .env files without manually babysitting every single tool call, so I implemented a PreToolUse hook to act as a safety guard.The logic is simple: the hook intercepts the tool call, checks if the target file is a .env file, and kills the process if it detects an unauthorized edit attempt. It's about 60 lines of code, but it saves a massive amount of anxiety. Here is how to set up this safeguard in your AI workflow: Implementation Steps 1. Create a hook file in your project directory e.g., .claude/hooks/protect-env.ts . 2. Implement the logic to intercept write file or edit file tool calls. 3. Configure your Claude Code environment to execute this hook before tool execution. Here is the core logic for the hook: export async function PreToolUse toolCall: ToolCall : Promise