Hooks: Deterministic Automation
Product facts change. The configuration format below is the one the official hooks reference documents as of October 2026. Event lists and hook types grow over time, so check the current reference before you rely on a name that is not in this lesson.
After this lesson, you will be able to:
- Write a hook in .claude/settings.json: the event name, a matcher string, and a list of command hooks
- Read the JSON a hook receives on stdin and pull fields out of it with jq
- Use exit code 2 to block an action, and explain why exit code 1 does not block
- Pick between a hook and a line in CLAUDE.md for a given rule
Before you start
#How Hooks Think
You add a PreToolUse hook that runs eslint --max-warnings 0 . on the whole repo, with no matcher, so it fires before every tool call. What breaks first?
#Hook Events
These are the events the official reference documents as of October 2026. Newer versions add more, so treat this table as the core set.
| Event | Fires when | Common use | Can it block? |
|---|---|---|---|
| PreToolUse | Before a tool call runs | Refuse dangerous commands, audit | Yes |
| PostToolUse | After a tool call succeeds | Format or lint the edited file | No (the tool already ran), but stderr is shown to Claude |
| UserPromptSubmit | You submit a prompt, before Claude sees it | Policy check, add context | Yes |
| Stop | Claude finishes its turn | Digest, or force Claude to keep going | Yes (makes Claude continue) |
| SubagentStop | A subagent finishes | Same as Stop, for fan-out work | Yes |
| Notification | Claude needs your attention | Forward "permission needed" to chat | No |
| PreCompact | Before the context is compacted | Save notes before detail is dropped | No |
| SessionStart | A session starts or resumes | Load project state | No |
| SessionEnd | A session ends | Save state, post a summary | No |
CompactBefore, CompactAfter and FileWatcherChange. If a tutorial lists them, its config will not work.#Hook Configuration
~/.claude/settings.json (all projects), .claude/settings.json (shared with the team), or .claude/settings.local.json (yours only). The hooks key is an object keyed by event name. Each event holds a list of entries, and each entry has a matcher string and a hooks list:{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh"
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-force-push.sh"
}
]
}
]
}
}
matcheris matched against the tool name and is a plain string or a regular expression:Bash,Edit|Write, ormcp__github__.*. An empty string or*matches every tool. Events with no tool (such asStop) take no matcher.type: "command"runs a shell command.$CLAUDE_PROJECT_DIRis the project root, which keeps the path valid wherever Claude's working directory is.- Type
/hooksinside Claude Code to see what is configured. Hooks are read when a session starts, so restart the session after you edit the file.
#Hook Types
"type": "prompt") ask a fast model a yes or no question about what just happened, for example "do these changes include a secret?". Use them for fuzzy judgments a regular expression cannot express, and keep command hooks for anything you can check mechanically.Newer versions add further types, such as calling an HTTP endpoint or running a verifier agent. As of October 2026 these are best checked in the current reference before you depend on them.
#What a Hook Receives
session_id, cwd and hook_event_name, and tool events add the tool call:{
"session_id": "abc123",
"cwd": "/home/you/project",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": { "command": "git push --force origin main" }
}
Edit and Write the interesting field is tool_input.file_path. For Bash it is tool_input.command. For UserPromptSubmit it is prompt. Use jq to read them:#!/usr/bin/env bash
# .claude/hooks/block-force-push.sh
cmd=$(jq -r '.tool_input.command // empty')
if echo "$cmd" | grep -Eq 'git push.*(--force|-f).*(main|master)'; then
echo "Blocked: never force-push to main." >&2
exit 2
fi
exit 0
$CLAUDE_PROJECT_DIR.#Exit Codes and Blocking
The exit code is the whole control surface for a simple hook:
| Exit code | Meaning |
|---|---|
| 0 | Success. Stdout is added to the conversation for some events (UserPromptSubmit, SessionStart) |
| 2 | Blocking error. For PreToolUse the tool call is refused and stderr goes to Claude, so it can adjust. For UserPromptSubmit the prompt is rejected. For Stop, Claude is told to continue |
| any other non-zero (such as 1) | Non-blocking error. The action goes ahead and stderr is shown to you |
exit 1 does not block anything. A guard written with exit 1 looks like it works, prints a message, and then lets the command run. Use exit 2 for every guard.{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}} to deny, or "allow" / "ask" to settle the normal permission prompt. An allow only skips the prompt: your deny rules still apply (see the Permissions lesson), so a hook cannot unlock a command that a deny rule bans.PostToolUse is different: the tool has already run, so exit 2 cannot undo it. It only feeds your message back to Claude, which is the right way to say "ruff found three errors, fix them".
#Hooks vs Instructions in CLAUDE.md
| Need | Hook | CLAUDE.md |
|---|---|---|
| "Always format after edits" | ✅ runs every time | ⚠️ Claude might forget |
| "Don't force-push to main" | ✅ blocks at runtime | ⚠️ Claude might do it once |
| "Use kebab-case filenames" | ⚠️ hard to check mechanically | ✅ guides the decision |
| "When the question is vague, propose a plan first" | ❌ wrong layer | ✅ guides behavior |
#Common Hook Recipes
.claude/hooks/ and run chmod +x on them.#Format after an edit
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh" }]
}
]
}
}
#!/usr/bin/env bash
# .claude/hooks/format.sh: route each file to the right formatter
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
*.py) ruff format "$f" ;;
*.ts|*.tsx) npx prettier --write "$f" ;;
esac
exit 0
One script routes by file extension, so you do not need one hook per language.
#Block secrets before a commit
#!/usr/bin/env bash
# PreToolUse on Bash: scan staged changes when Claude runs git commit
cmd=$(jq -r '.tool_input.command // empty')
case "$cmd" in
*"git commit"*)
if git diff --cached | grep -Eq '(API_KEY|SECRET|PRIVATE_KEY)'; then
echo "Blocked: staged changes look like they contain a secret." >&2
exit 2
fi ;;
esac
exit 0
A real project would call a scanner such as gitleaks here. A grep for three words is a teaching stand-in and misses most secrets.
#Guard the prompt
#!/usr/bin/env bash
# UserPromptSubmit: the JSON has a "prompt" field
p=$(jq -r '.prompt // empty')
if echo "$p" | grep -qi 'delete production'; then
echo "Blocked: file a ticket for destructive production work." >&2
exit 2
fi
exit 0
UserPromptSubmit runs before Claude sees the message, so it suits company policy checks.#Audit every Bash command
#!/usr/bin/env bash
# PreToolUse on Bash: append a line to a log, never block
printf '%s %s\n' "$(date -u +%FT%TZ)" "$(jq -r '.tool_input.command // empty')" >> ~/.claude/bash-audit.log
exit 0
#Log each finished turn
Stop fires when Claude finishes a turn, and SessionEnd fires when you leave the whole session. A Stop hook receives stop_hook_active, which is true if the hook itself already forced Claude to continue. Check it before you exit 2, or you create an endless loop.#Key Takeaways
- Hooks give deterministic enforcement: the rule runs every time its event fires
hooksis an object keyed by event; each entry has amatcherstring and ahookslist of{type, command}- A command hook gets the event as JSON on stdin; read it with
jq - Exit 2 blocks. Exit 1 does not. Always test a guard by triggering it
- Judgment goes in CLAUDE.md; mechanical checks go in hooks
#Quick Check
Your team keeps forgetting to run `ruff format` after Python edits. What is the best fix?
You want a hook to refuse any Bash command that contains `rm -rf /`. Which setup is correct?