Hooks in Claude Code are actions that Claude Code runs at set points in a session. Most of the time, a hook is a shell command. Hooks fire, for example, before a tool call or when Claude finishes a response. You declare them in settings.json. A hook can block the action or send a message back to Claude.
The examples and version numbers in this post apply to Claude Code v2.1.330.
Which hook events does Claude Code support?
The hooks reference lists more than thirty events. The table covers the ones you’ll use most, with what exit 2 does on each.
| Event | Fires | Effect of exit 2 |
|---|
PreToolUse | Before a tool call | Blocks the call |
PermissionRequest | When Claude Code is about to ask you for permission | None, decide through JSON instead |
PostToolUse | After a tool call succeeds | Shows stderr to Claude, the tool already ran |
UserPromptSubmit | When you send a prompt | Blocks the prompt |
Stop | When Claude finishes responding | Claude keeps working |
SessionStart | When a session starts or resumes | Shows stderr to you only |
Notification | When Claude Code sends a notification | None |
Stop doesn’t fire when you interrupt Claude. An API error fires StopFailure instead.
Where does a hook go in settings.json?
A hook has three levels. First the event, then a group whose matcher filters when it fires, then the handlers to run. All events live in one hooks object. Add a new event next to the existing ones rather than replacing the object.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
],
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
The first hook runs Prettier on every file Claude edits, using jq to read the path. The second shows a macOS notification when Claude is waiting on you.
Put personal hooks in ~/.claude/settings.json and project hooks in .claude/settings.json. Hooks from these files add up rather than override each other. The type field takes command, http, mcp_tool, prompt or agent.
The /hooks command shows your hooks read-only, with where each one comes from. To add one, you edit the file. Claude Code usually picks up the change on its own.
How do you write a matcher that fires?
On tool events, the matcher filters on the tool name.
- A matcher made only of letters, digits,
_, -, ,, | and spaces is compared as plain text. Edit|Write matches those two tools.
- Any other character turns it into an unanchored JavaScript regular expression. So
Edit.* also matches NotebookEdit.
mcp__memory matches no tool at all. Write mcp__memory__.* to cover every tool from the memory server.
- Matching is case-sensitive, so
bash never fires.
- On events without matcher support, such as
Stop, the field is silently ignored.
Since v2.1.85, the if field also filters on arguments, using permission rule syntax. With "if": "Bash(git *)", the hook runs for git commands. It holds a single rule. On events other than tool events, a hook with an if never runs. The docs call this filter best-effort. For a guaranteed block, use a deny permission rule.
What do exit codes and JSON output do?
A command hook gets the event as JSON on stdin. It answers with its exit code, and sometimes with a JSON object on stdout.
| Exit code | Result |
|---|
0 | Success. Claude Code applies any JSON the hook printed |
2 | Blocking error. Stderr becomes the reason, and the effect depends on the event |
Anything else, 1 included | Non-blocking error. The action goes ahead |
That last row catches people out, since 1 is the usual Unix failure code. A guard hook that exits 1 blocks nothing. To make a hook that crashes or times out block the action, see the post on onFailure.
This script refuses edits to sensitive files. Save it as .claude/hooks/protect-files.sh and make it executable with chmod +x.
#!/bin/bash
FILE_PATH=$(jq -r '.tool_input.file_path // empty')
for pattern in ".env" "package-lock.json" ".git/"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0
Register it on PreToolUse for the Edit and Write tools.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh",
"args": []
}
]
}
]
}
}
The args array, even empty, switches the hook to exec form, added in v2.1.139. Claude Code then runs the script without a shell, so the path needs no quoting. Claude can still change these files through a Bash command. The docs suggest adding deny rules and the sandbox for that.
For a finer answer, exit 0 and print a single JSON object. On PreToolUse, the decision goes inside hookSpecificOutput.
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database writes are not allowed"
}
}
permissionDecision takes allow, deny, ask or defer. A deny holds even in bypassPermissions mode. An allow doesn’t override your deny rules. On PostToolUse or Stop, you use a top-level "decision": "block" with a reason field instead.
What are the most common pitfalls?
Text before the JSON. Some setups load your shell profile even for a hook, such as BASH_ENV pointing at ~/.bashrc. If that profile runs an echo, its text lands before your JSON. Claude Code then reads plain text and ignores your decision, with no error. In ~/.zshrc or ~/.bashrc, wrap those echo lines in if [[ $- == *i* ]]. That test is only true in an interactive shell.
A field at the wrong level. A permissionDecision outside hookSpecificOutput is silently ignored. The debug log then shows Hook JSON output had unrecognized keys.
A Stop hook that loops. A hook that always refuses to let Claude stop keeps sending it back to work. Claude Code overrides it after eight blocks in a row with no tool call in between. When the stop_hook_active input field is true, Claude is already continuing because of a Stop hook. Exit 0 in that case.
A badly set timeout. Claude Code waits for a hook to finish, for up to 600 seconds by default on a command hook. Set timeout, in seconds, to match how long the script really takes. For a long task such as a test suite, add "async": true. The hook then runs in the background and can no longer block the action.
A repository you didn’t write. Hooks run with your full user permissions. In an interactive session, they wait until you accept the folder’s trust dialog. With claude -p, there’s no dialog, and the repository’s hooks run. On an unknown repository, add --settings '{"disableAllHooks": true}'.
How do you debug a hook that doesn’t fire?
Run /hooks and check that the hook shows up under the right event. If it’s missing, check the file location and the JSON. A trailing comma or a comment is enough to break it. Since v2.1.327, /status also lists hook matchers that never match.
Next, test the script on its own with sample JSON.
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh
echo $?
Then start claude --debug and read ~/.claude/debug/<session-id>.txt. Since v2.1.296, each command hook on a tool event leaves a Hooks: line there with its outcome and duration. With CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose set, the log also shows how hook matchers were evaluated.
The official hooks guide covers more troubleshooting cases.
What changed in recent versions?
- v2.1.251: new
PreModelSwitch and PostModelSwitch events, to block or annotate a model switch.
- v2.1.295:
onFailure field on command and http hooks, extended to mcp_tool hooks in v2.1.328.
- v2.1.326: a
"decision": "block" holds in more cases. A hook that always prints one may start blocking calls.
- v2.1.329: a folder’s trust dialog now says where its hooks are declared.
- v2.1.330: the
model field of a prompt hook accepts aliases such as haiku or sonnet.
Module 5 of the course builds on these basics to put together a complete setup. To see where hooks sit next to your written instructions, read the post on the CLAUDE.md file.