Claude Code hooks: five examples that make it safer
A hook is a rule Claude Code runs itself, every time
A Claude Code hook is a command you configure that Claude Code itself runs at a fixed point, such as just before a tool runs or right after a file is edited. Because Claude Code runs it, not the model, it fires every time, which makes hooks the place for rules that must not be skipped. A hook that blocks an action holds even in bypass permissions mode.
That is the real difference from writing the same rule in CLAUDE.md. An instruction in CLAUDE.md is something the model reads and usually follows. A hook is code that runs whether the model remembers or not; Anthropic's hooks guide calls it "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them." Anthropic's own three minute video, Hooks in Claude Code, introduces the same idea. For a business letting an AI agent work in real repositories, that is the line between a policy and a hope.
If Claude Code is about to work in repositories or systems your business depends on, we can help you put these guards in place first. Book a call with GenovaFlow AI
Each hook is an event, a matcher and a command
Every hook has three parts. The event says when it fires, the matcher narrows which occurrences count, and the command is what runs. The event list is long, but most useful hooks sit on a handful: PreToolUse before a tool call, which can block it; PostToolUse after a tool call succeeds; Notification when Claude needs you; SessionStart when a session begins; Stop when Claude finishes responding; and ConfigChange when a settings file changes.
When an event fires, Claude Code sends the hook a small JSON document on standard input, with fields such as tool_name and tool_input; for a shell command, tool_input.command holds the command itself. Most examples in the docs read it with jq, so install that first. The hook answers through its exit code. Exit 0 means no objection, and on PreToolUse the call then goes through the normal permission prompt, because exit 0 does not approve anything. Exit 2 blocks the action, and whatever the hook wrote to standard error is passed to Claude as the reason, so it can change course.
For finer control a hook can exit 0 and print JSON instead, for example a permissionDecision of deny, ask or allow with a reason. When several hooks match the same call, they all run in parallel and the most restrictive answer wins, in the order deny, defer, ask, allow. The matcher for tool events is the tool name, such as Bash, Edit|Write or mcp__github__.* for every tool on one MCP server.
The quickest hook to try is the guide's first one: a desktop notification whenever Claude is waiting for you. On a Mac it goes in ~/.claude/settings.json, and /hooks inside Claude Code shows it once it loads:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}Five hooks that make Claude Code safer to run
The five below are the ones worth having before Claude Code touches anything that matters. Four are taken from Anthropic's docs as written; the third combines two documented pieces. Project hooks go in .claude/settings.json so the whole team gets them through version control.
1. Block edits to .env and other protected files
The guide's protected files example is a short script that reads the file path from the hook input, compares it with a list of patterns and exits 2 if it matches. Claude sees the "Blocked" message and adjusts instead of retrying blindly.

Save it as .claude/hooks/protect-files.sh, make it executable with chmod +x, and register it to run before every edit or write:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
}
]
}
]
}
}2. Block a dangerous command before it runs
The same pattern works for shell commands. This script from the hook output section of the guide refuses any command that drops a table. Register it on PreToolUse with the matcher Bash, and swap the pattern for whatever your team must never run, such as a force push to the main branch.
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q "drop table"; then
echo "Blocked: dropping tables is not allowed" >&2
exit 2
fi
exit 03. Ask a person before any MCP tool that writes
Instead of blocking, a hook can return ask, which shows you the normal permission prompt for that call. Combined with a matcher such as mcp__.*__write.*, which the guide gives as a pattern for write tools across servers, it puts a human in front of every write an MCP server makes. Adjust the pattern to the tool names your servers really use.
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__.*__write.*",
"hooks": [
{
"type": "command",
"command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PreToolUse\", \"permissionDecision\": \"ask\", \"permissionDecisionReason\": \"Writes through MCP need a person\"} }'"
}
]
}
]
}
}It is the same rule a well run support agent follows: risky or irreversible actions wait for a person.
4. Log every command Claude runs
An audit trail is one line. This PostToolUse hook from the guide's matcher examples appends every shell command Claude ran to a file you can review later:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"
}
]
}
]
}
}5. Record every settings change
The fifth catches changes to the rules themselves. A ConfigChange hook fires when a settings or skills file changes during a session, and the guide's audit example writes one JSON line per change with the time, the source and the file. Exit 2 from the same hook would block the change instead.
{
"hooks": {
"ConfigChange": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"
}
]
}
]
}
}Put each hook where the right people can change it
Where a hook lives decides who it applies to and who can change it. The guide's location table lists ~/.claude/settings.json for all your own projects, .claude/settings.json for one project and shareable through the repository, .claude/settings.local.json for one project and kept out of git, managed policy settings for the whole organisation, plugins, and the frontmatter of a skill or subagent while it runs.
For a team, the managed tier is the one that counts. Hooks from every level are added together rather than replacing each other, and a user's disableAllHooks cannot switch off managed hooks. An administrator can go further with allowManagedHooksOnly, which blocks user, project, local and plugin hooks so that only the organisation's own run. Hooks from settings and policy also fire inside subagents, so a guard does not disappear when Claude delegates.
Five facts that decide whether a hook really protects you
A hook is only as safe as its weakest assumption, and the docs are frank about where those are. First, a hook runs with your own permissions. The hooks reference opens its security section with the warning that command hooks "can modify, delete, or access any files your user account can access," so a hook from someone else's repository deserves the same review as any script.

Second, trust depends on how Claude Code is started. An interactive session holds back every hook until you accept the workspace trust dialog, but a claude -p or Agent SDK run treats the folder as trusted, so hooks committed in a repository run there without asking. Before scripting Claude Code over code you did not write, review its .claude/ folder or run with --settings '{"disableAllHooks": true}', as the reference suggests.
Third, a guard can fail open. Command hooks have a default timeout of 600 seconds, and on PreToolUse a hook that times out does not block the tool call; the call carries on through the normal permission flow. If a guard must hold even when it hangs, set "onFailure": "block" on it. Fourth, a matcher only sees what it names. Claude can change files through shell commands as well as with Edit and Write, so the guide suggests also matching Bash|PowerShell or adding a Stop hook that checks the working tree when a hook must catch every change. The if filter is best effort too, and the docs say a hard allow or deny belongs in the permission rules.
Fifth, a PostToolUse hook reacts after the fact. The limitations list is plain that it "can't undo actions since the tool has already executed," which is why every blocking example above sits on PreToolUse. The reverse is the good news: a deny from a PreToolUse hook blocks the tool in every permission mode, including bypassPermissions and --dangerously-skip-permissions.
Hooks can also cut what Claude has to read
Hooks are not only guards. Anthropic's costs guide gives the example of a hook that, instead of letting Claude read a 10,000 line log, greps it for errors and passes on only the matching lines, "reducing context from tens of thousands of tokens to hundreds." The rtk tool in our eleven fixes for Claude Code token usage works the same way: its install command hooks it into Claude Code so command output arrives already trimmed.
Start with the protected files hook and the command log, because they cost nothing and catch the worst surprises, then add the rest as your team relies on Claude Code for more. More Claude Code guides are in the Claude Code section, and for where Claude Code fits next to workflow tools that come with their own audit logs, see the comparison of AI automation tools.
If you want these guards set up once for every developer, through managed settings rather than one laptop at a time, that is part of what we do in custom AI agent builds.
Questions people ask
Where are Claude Code hooks stored?
In settings files. Hooks for all your projects go in ~/.claude/settings.json, hooks for one project in .claude/settings.json (shared through the repository) or .claude/settings.local.json (kept out of git), and organisation hooks in managed policy settings. Plugins, skills and subagents can carry hooks too. Run /hooks to see every hook that loaded, grouped by event, as the hooks guide describes.
What is the difference between hooks and skills in Claude Code?
A skill is a set of instructions and files that Claude chooses to use when a task matches, so it depends on the model deciding to follow it. A hook is a command Claude Code runs itself at a fixed event, whether the model thinks of it or not. Use a skill to teach Claude how to do something, and a hook for a rule that must always hold.
Can a hook block a command in bypass permissions mode?
Yes. A PreToolUse hook that returns permissionDecision: "deny" blocks the tool even in bypassPermissions mode or with --dangerously-skip-permissions, because these hooks fire before any permission mode check. A hook that returns allow cannot loosen your deny rules, as the hooks guide explains.
Why is a Claude Code hook not firing?
Check the event and the matcher first: PreToolUse fires before a tool runs and PostToolUse after, and a matcher of Edit|Write never sees changes made through Bash. Make sure the script is executable, that you accepted the workspace trust dialog for the folder, and run /hooks to confirm it loaded. For each hook's exit code, standard output and standard error, start Claude Code with claude --debug-file /tmp/claude.log and read that log, per the troubleshooting notes.
Are Claude Code hooks safe?
They are as safe as the commands in them. Command hooks run with your full user permissions, so review any hook before you add it, especially one committed in a repository you did not write. Note that claude -p runs treat the folder as trusted and run its hooks without asking. The hooks reference lists the practices: quote variables, block path traversal, use absolute paths and skip sensitive files.