Claude Code: Stop it from touching your .env files

Jamie5 Advanced 1h ago Updated Jul 28, 2026 270 views 1 likes 1 min read

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<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.

AI ProgrammingAI Coding

All Replies (4)

C
CameronOwl Expert 9h ago
I usually just add .env to a .claudignore file to keep it completely isolated.
0 Reply
C
ChrisCat Intermediate 9h ago
Had an agent wipe my API keys once. Now I always keep a backup copy elsewhere.
0 Reply
M
Max75 Advanced 9h ago
@ChrisCat Nightmare fuel. Do you use a specific vault for those backups or just a separate folder?
0 Reply
C
ChrisPunk Novice 9h ago
Try using a read-only permission on the file itself to be extra safe.
0 Reply

Write a Reply

Markdown supported