Claude Code hooks: auto-format, run tests and block risky commands
You can write "always run Prettier after editing" or "never touch .env" in your CLAUDE.md, and Claude will follow it most of the time. Most of the time is fine for style advice. It's not fine for the rule that keeps your production secrets out of a diff, or the one that says tests must pass before the agent reports success.
Hooks are the part of Claude Code that turns those rules into code. A hook is a shell command that Claude Code runs at a fixed point, such as before a tool call, after a file edit or when Claude finishes a reply. It runs every time, whether or not the model remembered the instruction. This post covers how hooks are wired up and then gives four that pay for themselves in the first week, each tested against sample input.
Where hooks live
Hooks go in a hooks block inside a Claude Code settings file. Which file you pick decides who gets them:
| File | Applies to | Commit it? |
|---|---|---|
~/.claude/settings.json |
Every project you open | No, it's yours |
.claude/settings.json |
This project, for everyone | Yes |
.claude/settings.local.json |
This project, only you | No, it's gitignored |
Hooks from all three files add up; a project hook doesn't replace a personal one. Team rules like "format on save" and "never edit migrations" belong in .claude/settings.json so every clone gets them. Personal ones, such as a desktop notification, go in your home directory. Edits to these files are normally picked up while Claude Code is running, and the /hooks command lists every hook that's active, with the file each one came from.
How a hook is put together
The structure has three levels: the event, a matcher that filters which tool calls it fires on, and the commands to run.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npx prettier --write \"$(jq -r '.tool_input.file_path')\"" }
]
}
]
}
}
The events you'll use most:
| Event | Fires | Can it block? |
|---|---|---|
PreToolUse |
Before a tool runs | Yes, it can stop the call |
PostToolUse |
After a tool succeeds | No, but it can send feedback to Claude |
Stop |
When Claude finishes a reply | Yes, it can make Claude keep working |
UserPromptSubmit |
When you send a prompt | Yes, and it can add context |
SessionStart |
On start, resume, /clear or after compaction |
No, but its output is added to context |
Notification |
When Claude needs your attention | No |
For tool events the matcher is the tool name: Bash, Edit|Write, or a regular expression such as mcp__github__.* for every tool from one MCP server. Names are matched exactly, so bash won't match the Bash tool. Leave the matcher out to match everything.
Each hook gets a JSON description of the event on stdin. For a PreToolUse call to Bash it includes, among other fields:
{
"hook_event_name": "PreToolUse",
"cwd": "/home/user/my-project",
"tool_name": "Bash",
"tool_input": { "command": "npm test", "description": "Run test suite" }
}
File tools put the path in tool_input.file_path. The examples below read these fields with jq, so install it first (brew install jq, apt-get install jq, or the Windows binary from the jq site).
Exit codes decide what happens
The hook's exit code is how it talks back:
| Exit code | Meaning |
|---|---|
0 |
Success. Claude Code reads stdout as JSON if it's a single JSON object. |
2 |
Block. The action stops (on events that can block), and stderr is shown to Claude as the reason. |
Anything else, including 1 |
A non-blocking error. You see a hook error notice and the action goes ahead. |
That last row catches almost everyone once. A guard script that ends with exit 1 looks like it blocks, but the command runs anyway. Use exit 2 for "no", and write the reason to stderr in words the model can act on: "Blocked: migrations are generated, run npm run db:generate instead" gets a better next step than "denied".
An exit code of 0 doesn't mean "allowed", either. It means the hook has no objection, and the normal permission prompt still applies.
Hook 1: format every file Claude edits
Agents produce code that's correct and formatted slightly differently from yours, and the formatting noise then hides the real change in review. A PostToolUse hook fixes it at the source. In .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}
--ignore-unknown makes Prettier skip file types it doesn't handle instead of failing on them. For a Python project, swap the command for ruff format "$f"; for Go, gofmt -w "$f". The formatter runs on your machine and sends nothing to the model, so it costs no tokens.
Hook 2: block edits to files Claude shouldn't touch
Some files should only change by hand or by a generator: .env, lockfiles, generated migrations, anything in .git/. Save this as .claude/hooks/protect-files.sh:
#!/bin/bash
file=$(jq -r '.tool_input.file_path // empty')
file="${file//'\'//}" # Windows backslashes to slashes, so the patterns match
for pattern in "/.env" "package-lock.json" "/.git/" "/migrations/"; do
if [[ "$file" == *"$pattern"* ]]; then
echo "Blocked: $file matches protected pattern '$pattern'. Ask the user to change it." >&2
exit 2
fi
done
exit 0
Register it as a PreToolUse hook on the file tools:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
]
}
]
}
}
Run chmod +x .claude/hooks/protect-files.sh on macOS and Linux. $CLAUDE_PROJECT_DIR is the project root where the session started, so the path works whatever directory Claude has moved into.
Two details came out of testing. The leading slash in /.env means src/environment.ts isn't caught by accident, while .env.local still is. And watch the backslash replacement: written as ${file//\\//}, bash 5.2 removes every forward slash from the path instead, so /repo/.git/config became repo.gitconfig and slipped past the /.git/ check. The quoted form above converts C:\repo\.env to C:/repo/.env and leaves Unix paths alone.
This hook only covers Claude's file tools. A Bash command like echo KEY=x >> .env writes the file without going through Edit. For secrets, back the hook with a permissions deny rule and keep real keys out of the repo; the vibe coding security checklist covers both.
Hook 3: deny destructive git and shell commands
A PreToolUse hook on Bash sees the full command before it runs. Instead of exiting with 2, this one prints JSON with permissionDecision: "deny" and a reason, which is the structured way to say no. Save as .claude/hooks/guard-bash.sh:
#!/bin/bash
cmd=$(jq -r '.tool_input.command // empty')
deny() {
jq -n --arg reason "$1" '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: $reason
}
}'
exit 0
}
if grep -Eq 'git push.*(--force|-f)( |$)' <<<"$cmd"; then
deny "Force push is blocked. Use --force-with-lease or push a new branch."
fi
if grep -Eq 'git (reset --hard|clean -[a-z]*f)' <<<"$cmd"; then
deny "This discards uncommitted work. Use git stash, or ask the user first."
fi
if grep -Eq 'rm -[a-zA-Z]*r[a-zA-Z]* +(/|~|\$HOME)/?( |$)' <<<"$cmd"; then
deny "Recursive delete of / or the home directory is blocked."
fi
exit 0
Register it with "matcher": "Bash" in the same way as hook 2. Against sample input it denied git push --force origin main, git push -f, git reset --hard HEAD~1, git clean -fd, rm -rf / and rm -rf ~. It let through git push --force-with-lease, rm -rf node_modules, rm -rf /tmp/build and npm test.
The JSON goes to stdout and the script exits 0, because JSON output is only read on a zero exit. Pick one style per hook: exit 2 with a message on stderr, or exit 0 with JSON. A deny from a hook holds in every permission mode, including when you've told Claude to skip permission prompts.
Treat this as a guard rail, not a sandbox. Pattern matching on command strings is easy to sidestep: the same delete can hide in a script file, a find -delete or a different flag order. It stops the common accidents. For untrusted work, run the agent in a container or use Claude Code's sandboxing.
Hook 4: run the tests before Claude says it's done
This is the hook that changes how an agent session feels. A Stop hook runs when Claude finishes a reply. If it exits 2, Claude doesn't stop: it reads your stderr and keeps working. Save as .claude/hooks/tests-before-stop.sh:
#!/bin/bash
input=$(cat)
if [ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ]; then
exit 0 # already continuing because of this hook once: let Claude stop
fi
cd "$CLAUDE_PROJECT_DIR" || exit 0
if [ -z "$(git status --porcelain)" ]; then
exit 0 # nothing changed, Claude only answered a question: skip the tests
fi
if ! out=$(npm test --silent 2>&1); then
echo "Tests fail. Fix them before you finish. Last lines of output:" >&2
tail -n 30 <<<"$out" >&2
exit 2
fi
exit 0
And the settings, with a timeout in seconds sized for your suite:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/tests-before-stop.sh",
"timeout": 300
}
]
}
]
}
}
Each check in the script is there for a reason:
Stopfires after every reply, including "what does this function do?". Thegit statuscheck skips the suite when the working tree is clean.stop_hook_activeistruewhen Claude is already continuing because a stop hook blocked it. Exiting early on that flag gives Claude one extra attempt to fix the tests instead of an endless loop on a test that can't pass. Claude Code also caps consecutive stop-hook blocks on its own, but don't build on that limit.tail -n 30matters for cost. Everything on stderr goes into Claude's context as input tokens, and a full Jest or pytest log can run to thousands of lines. The last 30 lines usually hold the failure summary.
Tested in a scratch repo: with a clean tree it exited 0 without running anything; with a failing suite it exited 2 and passed the failure line through; on the follow-up stop with stop_hook_active set it let Claude finish; with a passing suite it exited 0.
Two small hooks worth adding
A notification when Claude is waiting on you, in ~/.claude/settings.json. This is the Linux version; on macOS use osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"':
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{ "type": "command", "command": "notify-send 'Claude Code' 'Claude Code needs your attention'" }
]
}
]
}
}
And a reminder that survives compaction. When a long session is compacted, details from early on can drop out. A SessionStart hook with the compact matcher runs right after, and its stdout is added to Claude's context:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{ "type": "command", "command": "echo 'Reminder: use pnpm, not npm. Run pnpm test before committing.' && git log --oneline -5" }
]
}
]
}
}
Keep it to the handful of rules that keep getting lost. Long-lived project instructions still belong in your AGENTS.md or CLAUDE.md.
When a hook doesn't fire
Work through these in order:
- Run
/hooks. If the hook isn't listed, the settings file has a JSON error or the hook is in a file Claude Code isn't reading. - Check the matcher against the real tool name.
Edit|Writedoesn't coverNotebookEditor MCP tools. - Run the script by hand with sample input:
echo '{"tool_input":{"command":"git push -f"}}' | .claude/hooks/guard-bash.sh. Most bugs show up here, before Claude is involved. - "Command not found" usually means a relative path or a missing
chmod +x. Use"$CLAUDE_PROJECT_DIR"/.... - If your JSON output is ignored, something else is printing to stdout first, often an unconditional
echoin your shell profile. Also check thatpermissionDecisionsits insidehookSpecificOutput. - Start Claude Code with
claude --debug-file /tmp/claude.logto get a log line per hook with its exit status and duration.
On Windows, one more: if git converts your .sh files to CRLF line endings, bash fails on the stray carriage returns. Add *.sh text eol=lf to .gitattributes before you commit the hooks.
Treat project hooks as code you run
Command hooks run with your full user permissions, without asking each time. A .claude/settings.json in a repository you clone can define hooks, so read it the way you'd read a postinstall script before you trust the folder. Claude Code asks you to trust a workspace before its settings-file hooks run in an interactive session. To turn every hook off for one run, start with claude --settings '{"disableAllHooks": true}'.
Hooks and token spend
Most hooks cost nothing, because they run locally and their output never reaches the model. Two cases do cost tokens: stderr from an exit-2 hook and context added by SessionStart or UserPromptSubmit both become input on the next request. Keep that text short. A Stop hook that blocks also triggers another model turn, which is the point, but it adds up across a day of sessions.
If you run Claude Code through ChromaLab, per-key daily budgets keep a stop-hook loop in an unattended session from running past a set number of tokens; see per-key controls and Run Claude Code on any model through ChromaLab. The full event list and every output field are in Anthropic's hooks reference, with more examples in the hooks guide.
Checklist
- Team hooks in
.claude/settings.jsonand committed; personal ones in~/.claude/settings.json. jqinstalled on every machine that runs the hooks.- Scripts under
.claude/hooks/, executable, called through"$CLAUDE_PROJECT_DIR", and LF line endings forced in.gitattributes. - Blocking hooks exit
2with a reason on stderr, or exit0with JSON. Neverexit 1for "no". - Each script tested by piping sample JSON into it before you rely on it.
- Stop hooks check
stop_hook_activeand trim their output. - Hooks in cloned repositories read before you trust the folder.