ClaudeCode 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 #
- Create a hook file in your project directory (e.g.,
.claude/hooks/protect-env.ts
).
- Implement the logic to intercept
write_file
or edit_file
tool calls.
- 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<HookResult> {
const { toolName, arguments: args } = toolCall;
// Define protected files
const protectedFiles = ['.env', '.env.local', '.env.production'];
if (toolName === 'write_file' || toolName === 'edit_file') {
const path = args.path;
if (protectedFiles.some(file => path.endsWith(file))) {
return {
result: 'block',
message: `Security Block: Claude is not allowed to modify ${path} directly. Please provide the values manually.`
};
}
}
return { result: 'allow' };
}
Productivity Gains #
Since adding this, my deployment process is much safer. Instead of the agent accidentally overwriting a DB password or an API key during a refactor, it now stops and asks me for the specific value. This turns a potentially destructive action into a controlled prompt engineering task.
For anyone building a real-world LLM agent integration, these kinds of "guardrail" hooks are essential. You can easily extend this pattern to protect your .gitignore
or your package-lock.json
to prevent the agent from messing up your dependency versions.
Next World-Model-Optimizer: Distilling Frontier LLMs for Agents →