Stop the Cursor agent from reading .env files with a beforeReadFile hook
Short version: Cursor’s hooks include beforeReadFile, which runs before the agent reads a file and can return {"permission": "deny"}. Pair it with beforeShellExecution, because the agent can also run cat .env in the terminal.
Why you need two hooks
beforeReadFile covers the agent’s file-read tool. Shell commands go through a different hook, beforeShellExecution, which receives the full command string. If you only add the first, cat .env.local or source .env in the agent’s terminal still works. One script can handle both, because every Cursor hook receives hook_event_name in its input.
Step 1: save the script
Save as .cursor/hooks/block-env-files.sh, then chmod +x .cursor/hooks/block-env-files.sh. Needs jq.
#!/usr/bin/env bash
# block-env-files.sh: keep the agent from reading .env files (.env, .env.local, .env.production ...).
# .env.example / .env.sample / .env.template / .env.dist stay readable.
# Works as: Cursor beforeReadFile + beforeShellExecution, Claude Code PreToolUse (Read|Grep|Bash).
# Needs jq.
input=$(cat)
event=$(jq -r '.hook_event_name // empty' <<<"$input")
path=$(jq -r '.file_path // .tool_input.file_path // .tool_input.path // empty' <<<"$input")
cmd=$(jq -r '.command // .tool_input.command // empty' <<<"$input")
# a word that is a .env file name (optionally with a directory in front), not an example/template
ENV_RE='(^|[[:space:]/"'"'"'=<:])\.env(\.[A-Za-z0-9_-]+)*([[:space:]"'"'"';|&)>]|$)'
SAFE_RE='\.env\.(example|sample|template|dist)([[:space:]"'"'"';|&)>]|$)'
hit=no
if [ -n "$path" ]; then
base=${path##*/}
if [[ "$base" =~ ^\.env(\.[A-Za-z0-9_-]+)*$ ]] && ! [[ "$base" =~ ^\.env\.(example|sample|template|dist)$ ]]; then hit=yes; fi
fi
if [ "$hit" = no ] && [ -n "$cmd" ]; then
# drop the safe names first, then look for any remaining .env file name
stripped=$(printf '%s' "$cmd" | sed -E 's/\.env\.(example|sample|template|dist)//g')
if printf '%s' "$stripped" | grep -Eq "$ENV_RE"; then hit=yes; fi
fi
reason="Blocked: .env files hold secrets and are off-limits to the agent. Use .env.example for variable names, or ask the user."
if [ "$hit" = yes ]; then
case "$event" in
beforeReadFile) jq -n --arg r "$reason" '{permission: "deny", user_message: $r}' ;;
beforeShellExecution) jq -n --arg r "$reason" '{permission: "deny", user_message: $r, agent_message: $r}' ;;
*) jq -n --arg r "$reason" '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}' ;;
esac
exit 0
fi
case "$event" in
beforeReadFile|beforeShellExecution) echo '{"permission": "allow"}' ;;
esac
exit 0It blocks .env and any .env.<something> file in any folder. It lets .env.example, .env.sample, .env.template and .env.dist through, so the agent can still learn which variables exist. Files like .envrc or env.ts aren’t touched.
Step 2: register both hooks
{
"version": 1,
"hooks": {
"beforeReadFile": [
{ "command": ".cursor/hooks/block-env-files.sh", "timeout": 10, "failClosed": true }
],
"beforeShellExecution": [
{ "command": ".cursor/hooks/block-env-files.sh", "timeout": 10, "matcher": "\\.env" }
]
}
}Project hooks run from the project root, so the path is .cursor/hooks/..., not ./hooks/.... Two optional settings are used here:
"failClosed": trueonbeforeReadFile. By default, a hook that crashes or times out is logged and the read goes ahead. WithfailClosed, a broken hook (for example,jqmissing) blocks the read instead."matcher": "\\.env"onbeforeShellExecution. For that hook, the matcher is a regex tested against the command string, so the script only starts for commands that mention.env.
Step 3: test it
echo '{"hook_event_name":"beforeReadFile","file_path":"/repo/.env.local","content":"X=1"}' \
| .cursor/hooks/block-env-files.sh{
"permission": "deny",
"user_message": "Blocked: .env files hold secrets and are off-limits to the agent. Use .env.example for variable names, or ask the user."
}Cursor reloads hooks.json on save. To confirm it’s active, open the Hooks tab under Customize or the Hooks output channel, then ask the agent to open .env.
Worth knowing
- The
beforeReadFileinput includes the file’scontent. Your hook runs locally, so nothing is sent anywhere, but don’t log the input to a shared place. - For permission hooks such as this one, Cursor treats invalid JSON or a response that doesn’t match the schema as a block. The script always prints valid JSON, including
{"permission": "allow"}when it has no objection. - Exit code 2 from a command hook also blocks, the same as Claude Code.
Limits
- A command that reads files without naming them, such as
grep -r API_KEY ., or a Node or Python script that opens.envitself, gets past a name check. Keep production secrets out of the working copy entirely if you can, and use a secrets manager or per-environment variables. - It is a pattern check, not a sandbox.
Using Claude Code too? The same script works there. See keeping Claude Code out of .env files.