Claude Code hooks: events, examples and a review gate
Zihua Li · · 10 min read
A line in CLAUDE.md asks Claude to run the formatter; a hook runs it. That difference is the whole point of Claude Code hooks: some things in a session should happen every time, whether or not the model remembers, and some things should never happen at all.
Claude Code hooks are commands that Claude Code runs automatically at fixed points in a session, such as before a tool call, after a file edit, when Claude needs your input or when it finishes responding. They are defined under a hooks key in a settings.json file, receive the event as JSON on stdin, and can block an action by exiting with code 2. Their primary purpose is deterministic control: formatting, guardrails, notifications and checks that always run instead of depending on the model.
What Claude Code hooks are
A hook is a handler attached to a lifecycle event. Most hooks are shell commands ("type": "command"), and Claude Code also supports four other types: http posts the event to a URL, mcp_tool calls a tool on a configured MCP server, prompt asks a model for a yes-or-no decision, and agent starts a subagent that can read files before deciding (agent hooks are marked experimental). When an event fires, every matching hook runs in parallel, and Claude Code merges the results.
What makes hooks different from instructions is who executes them. Claude reads CLAUDE.md and may judge that a guideline doesn’t apply. A hook runs because the event happened. That makes hooks the right home for rules with no exceptions, like “never edit the lockfile by hand,” and for chores you want done identically every time, like formatting.
The flip side is that hooks run with your full user permissions. A hook command can read, change or delete anything your account can, so treat a hook in a repository’s .claude/settings.json the way you would treat a script in its package.json: read it before you trust it.
Claude Code hook events
As of November 2026 the hooks reference lists more than 30 events, from SessionStart to SessionEnd, including newer ones such as FileChanged, CwdChanged, PostToolBatch and PreModelSwitch. A handful carry most real-world hooks:
| Event | When it fires | Can it block? |
|---|---|---|
| PreToolUse | Before a tool call runs (Bash, Edit, Write, Read, MCP tools…) | Yes: exit 2 or permissionDecision "deny" stops the call |
| PostToolUse | After a tool call succeeds | The tool already ran; stderr or a "block" reason goes to Claude |
| UserPromptSubmit | When a prompt is submitted, before Claude sees it | Yes: rejects the prompt; can also add context |
| Notification | When Claude needs permission or has been idle waiting for you | No: for side effects such as desktop alerts |
| Stop | When Claude finishes responding | Yes: keeps Claude working, with your reason as the next instruction |
| SubagentStart / SubagentStop | When a subagent is spawned or finishes | SubagentStop can keep the subagent working |
| SessionStart | When a session starts, resumes, clears or compacts | No: stdout is added to Claude’s context |
| PreCompact / PostCompact | Around context compaction | PreCompact can block compaction |
| PermissionRequest | When Claude Code is about to show you a permission prompt | Answers the prompt for you through JSON (allow or deny) |
| SessionEnd | When the session ends | No: cleanup only, on a short time budget |
The distinction that matters most is before versus after. PreToolUse fires while the action can still be stopped, so guardrails belong there. PostToolUse fires once the tool has already run, so it suits follow-up work like formatting the file that was just written, or telling Claude that a linter now complains about it.
How to configure hooks in settings.json
Hooks live under a single hooks object with three levels of nesting: the event name, a list of matcher groups, and inside each group a list of handlers. Every example in this post follows the same shape:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh",
"timeout": 60
}
]
}
]
}
}The matcher filters when the group fires. For tool events it matches the tool name: Bash, Edit|Write, or a regular expression such as mcp__github__.* for every tool from one MCP server. Matchers are case-sensitive, and an empty matcher fires on every occurrence. Other events match other things: SessionStart matches how the session started (startup, resume, clear, compact), and Notification matches the notification type, such as permission_prompt or idle_prompt. To narrow a tool hook further by its arguments, a handler can add an if field in permission-rule syntax, such as "Bash(git *)"; the docs describe that filter as best-effort, so it isn’t a substitute for a permission rule.
Where the hooks object lives decides who gets it:
~/.claude/settings.json: every project on your machine. Good for notifications and personal habits..claude/settings.json: one project, committed to the repository, so the whole team runs the same hooks..claude/settings.local.json: one project, your machine only.- Managed policy settings for organization-wide hooks, a plugin’s
hooks/hooks.json, and the frontmatter of a skill or a subagent, where the hook runs only while that skill or subagent is active.
Type /hooks at the Claude Code prompt to open a read-only browser of every configured hook, labeled with its source. Claude Code’s file watcher normally picks up edits to settings files without a restart. To switch all hooks off temporarily, set "disableAllHooks": true; there is no switch for a single hook, so to remove one, delete its entry.
Hook input, exit codes and JSON output
A command hook talks to Claude Code through four channels: JSON on stdin, its exit code, stdout and stderr. For a PreToolUse hook on a Bash call, stdin looks like this:
{
"session_id": "abc123",
"cwd": "/home/user/my-project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite"
},
"tool_use_id": "toolu_01ABC123..."
}Every event includes session_id, transcript_path, cwd and hook_event_name; tool events add tool_name and tool_input, and PostToolUse adds tool_response. Inside a subagent, agent_type names the subagent. jq is the usual way to pull a field out: jq -r '.tool_input.command'.
The exit code carries the decision:
- Exit 0 means no objection. On
PreToolUseit does not approve the call; the normal permission flow still applies. OnSessionStartandUserPromptSubmit, plain stdout is added to Claude’s context. - Exit 2 blocks the action on events that can be blocked, and stderr becomes the reason. On
PreToolUse, Claude reads that message as the tool’s error and can change course. - Any other code is a non-blocking error on most events: you see a hook error notice and the action goes ahead. That includes exit 1, so a policy hook that should stop something has to exit 2.
For finer control, exit 0 and print one JSON object to stdout instead. A PreToolUse hook returns its verdict inside hookSpecificOutput:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Use the staging database for this task"
}
}permissionDecision takes allow, deny, ask or, in non-interactive -p runs, defer. When several hooks disagree, the most restrictive answer wins. Other events use a top-level "decision": "block" with a reason, which is how a Stop hook sends Claude back to work. The JSON has to be the only thing on stdout; a shell profile that echoes a greeting will quietly break it.
Two more fields are worth knowing from day one. timeout sets a hook’s limit in seconds; command hooks default to 600 seconds (30 on UserPromptSubmit), prompt hooks to 30 and agent hooks to 60. onFailure: "block" (Claude Code v2.1.295 or later) makes a hook that crashes, can’t start or times out block the action instead of letting it through. Scripts referenced from settings should use "$CLAUDE_PROJECT_DIR", which points at the project root where the session started, so they resolve wherever Claude has cd’d to.
Claude Code hooks examples
The examples below follow the formats in the official hooks guide. Each one uses jq, so install it first (brew install jq or apt-get install jq), and make scripts executable with chmod +x.
Format every file Claude edits
A PostToolUse hook on Edit|Write reads the edited path from stdin and runs Prettier on it. Put it in the project’s .claude/settings.json so everyone on the team gets it:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}A successful hook shows nothing in the conversation; the reformatted file is the proof. Swap the command for ruff format, gofmt -w or your own formatter. Since Claude can also write files through Bash, use a FileChanged hook when a file must be reformatted no matter what wrote it.
Block edits to protected files and dangerous commands
Guardrails go on PreToolUse. The first script refuses edits to paths you never want Claude to touch; the second refuses a short list of shell commands:
#!/bin/bash
# .claude/hooks/protect-files.sh
file=$(jq -r '.tool_input.file_path // empty')
for pattern in ".env" "package-lock.json" ".git/" "migrations/"; do
if [[ "$file" == *"$pattern"* ]]; then
echo "Blocked: $file matches protected pattern '$pattern'. Ask the user first." >&2
exit 2
fi
done
exit 0#!/bin/bash
# .claude/hooks/guard-bash.sh
cmd=$(jq -r '.tool_input.command // empty')
if grep -Eiq 'rm -rf /|git push .*--force|drop table' <<<"$cmd"; then
echo "Blocked: '$cmd' is on this project's never-run list. Find another way or ask the user." >&2
exit 2
fi
exit 0Register both, with each script on its own matcher:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh",
"onFailure": "block"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-bash.sh",
"onFailure": "block"
}
]
}
]
}
}Because the scripts exit 2, Claude sees the Blocked: message and looks for another approach rather than retrying blindly. onFailure: "block" means a typo in the script path stops the tool call instead of silently disabling the guard. A deny from a PreToolUse hook holds in every permission mode, including bypassPermissions. Pattern matching on command strings has gaps, though: Claude can reach a file through a command the pattern doesn’t foresee. Pair the hook with permissions.deny rules, and with sandboxing where it matters.
Get a desktop notification when Claude needs you
The Notification event fires when Claude is waiting for a permission decision or has finished and sat idle for about a minute. Add this to your user settings in ~/.claude/settings.json:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}On Linux, use notify-send 'Claude Code' 'Claude Code needs your attention' as the command. On macOS, if nothing appears, Script Editor probably lacks notification permission: run osascript -e 'display notification "test"' once, then allow Script Editor under System Settings > Notifications. To be told only when a turn ends, put the same command on a Stop hook instead.
Testing and debugging hooks
Test a hook outside Claude Code by piping sample JSON into it and checking the exit code, for example echo '{"tool_input":{"command":"rm -rf /"}}' | .claude/hooks/guard-bash.sh; echo $?. Inside a session, Ctrl+O opens the transcript view, where blocked actions show the hook’s message and failures show a hook error notice. For the full story, start Claude Code with claude --debug and read the debug log.
The usual causes of a hook that does nothing:
- The matcher doesn’t match the tool name exactly (
bashis notBash), or the hook sits on the wrong event. - The script isn’t executable, or its path is relative.
- JSON output fields are at the wrong level:
permissionDecisionbelongs insidehookSpecificOutput, and misplaced fields are ignored without an error. - A
Stophook that always blocks keeps Claude going until Claude Code overrides it; checkstop_hook_activein the input and exit early when it’strue.
One security note from the docs: in interactive sessions, Claude Code holds back hooks from settings files until you accept the workspace trust dialog, but claude -p and SDK runs treat the folder as trusted. Before scripting claude -p over a repository you didn’t write, read its .claude/ settings or run with --settings '{"disableAllHooks": true}'.
Hooks vs CLAUDE.md, skills and subagents
Claude Code has four ways to shape a session, and they split by who decides. CLAUDE.md is guidance Claude reads every session and applies with judgment. Skills are procedures Claude loads when a task calls for them. Subagents are separate workers with their own context and tools. Hooks are the only one of the four that Claude Code executes without asking the model, which is why the rules you’d otherwise repeat in CLAUDE.md in capital letters belong here. Hooks also differ from Git hooks: those fire on Git operations whoever makes them, while Claude Code hooks fire on Claude’s actions inside a session.
Claude Code hooks are handlers in settings.json that run at lifecycle events such as PreToolUse, PostToolUse, Notification and Stop. A command hook reads the event as JSON on stdin, exits 0 to allow, exits 2 to block with stderr as Claude’s feedback, or prints JSON for finer control. Command hooks time out after 600 seconds by default, adjustable per hook.
A review gate before Claude opens a pull request
A natural next hook is one that checks Claude’s work before it leaves your machine. TheHeyDeer CLI is built for that moment: heydeer review reviews the branch’s commits plus uncommitted changes to tracked files against the default branch, verifies each finding against the code, and with --json prints the finished review as a single JSON object on stdout. Install it with curl -fsSL https://heydeer.ai/install.sh | sh (or npm install -g heydeer with Node.js 22+), then run heydeer login.
The obvious design, running the review inside a PreToolUse hook on gh pr create, fits hooks poorly. A review takes minutes. The hook would hold the session for that long, a stalled PreToolUse hook that hits its timeout lets the command through, and Claude couldn’t fix anything until the hook returned. The better pattern lets Claude do the work and uses the hook only as the gate: block gh pr create with exit 2 and an instruction, and open the gate once a review has finished for the current commit.
#!/bin/bash
# .claude/hooks/review-gate.sh
# PreToolUse: block "gh pr create" until HeyDeer has reviewed the current HEAD.
# PostToolUse: record HEAD once "heydeer review --json" has returned a finished review.
input=$(cat)
cmd=$(jq -r '.tool_input.command // empty' <<<"$input")
cd "$(jq -r '.cwd' <<<"$input")" || exit 0
head=$(git rev-parse HEAD 2>/dev/null) || exit 0
marker="$(git rev-parse --absolute-git-dir)/heydeer-reviewed"
if [[ "$(jq -r '.hook_event_name' <<<"$input")" == "PostToolUse" ]]; then
if [[ "$cmd" == *"heydeer review"* && "$cmd" == *"--json"* ]] &&
jq -e '.tool_response | tostring | contains("publicationFindings")' <<<"$input" >/dev/null; then
echo "$head" > "$marker"
fi
exit 0
fi
[[ "$cmd" =~ gh[[:space:]]+pr[[:space:]]+create ]] || exit 0
[[ -f "$marker" && "$(cat "$marker")" == "$head" ]] && exit 0
cat >&2 <<'EOF'
HeyDeer hasn't reviewed this commit yet. From the repository root, run
heydeer review --json "<what this change does and the issue it fixes>"
with a Bash timeout of 600000 ms and wait for the JSON. Fix the findings in
result.publicationFindings that you agree with, commit, and run the review again.
Then retry gh pr create, and list any finding you left open in the PR description.
EOF
exit 2The same script handles both events. On PreToolUse it only reacts to gh pr create, compares HEAD with the commit recorded in a marker file inside the Git directory, and blocks with instructions when they differ. On PostToolUse it records HEAD after a heydeer review --json call whose output contains the review’s findings list, so the marker reflects a finished review rather than a promise. The instruction asks for a ten-minute Bash timeout because Claude Code’s Bash tool defaults to two minutes and moves longer commands to the background. Register it on both events:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/review-gate.sh" }
]
}
],
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/review-gate.sh" }
]
}
]
}
}In practice the loop runs like this. Claude finishes the change and tries gh pr create. The hook blocks it, and Claude reads the instruction, runs the review, and works through result.publicationFindings, where each finding has a severity, a title, a file and line, and an explanation. If it commits fixes, HEAD moves, so the gate asks for another run; that later review covers what changed since the last one and rechecks the findings still open. Once a review has finished for the commit being pushed, gh pr create goes through. Note that heydeer review exits 0 whether or not it found anything, which is why the gate checks for a finished review and leaves the judgment about each finding to Claude and to you. Check the gate by hand before relying on it:
echo '{"hook_event_name":"PreToolUse","cwd":"'"$PWD"'","tool_input":{"command":"gh pr create --fill"}}' \
| .claude/hooks/review-gate.sh; echo "exit $?"For the same habit without a hook, an instruction in CLAUDE.md or AGENTS.md asking the agent to run the review before opening a pull request works with Claude Code, Codex and Cursor; the CLI docs include one. The AI code review CLI page covers what a local review sends and how it’s charged, and the Claude Code review skill guide covers Claude’s own /code-review.
Sources
Frequently asked questions
What is the primary purpose of hooks in Claude Code?
The primary purpose of hooks in Claude Code is deterministic control over a session. A hook is a command Claude Code runs at a fixed lifecycle point, so formatting after edits, blocking dangerous commands, sending notifications or injecting context always happens, instead of depending on Claude choosing to do it.
Where do Claude Code hooks go?
Claude Code hooks go under the hooks key of a settings file: ~/.claude/settings.json for all your projects, .claude/settings.json for one project and shared through Git, or .claude/settings.local.json for one project on your machine only. Plugins, skills and subagent files can also carry hooks, and administrators can set them in managed policy settings. Type /hooks in Claude Code to see every configured hook and where it comes from.
What does exit code 2 mean in a Claude Code hook?
Exit code 2 in a Claude Code hook means “block this action.” On a PreToolUse hook it stops the tool call and Claude receives the hook’s stderr as the reason, so it can adjust. Exit 0 means no objection, and any other exit code is a non-blocking error on most events, so a policy hook should use exit 2 rather than exit 1.
How long can a Claude Code hook run?
A Claude Code command hook can run for 600 seconds by default, as of November 2026, and you can change that per hook with the timeout field in seconds. Prompt hooks default to 30 seconds and agent hooks to 60. A PreToolUse command hook that times out doesn’t block the tool call unless the hook sets onFailure to "block".
Can a Claude Code hook block commands in bypassPermissions mode?
A Claude Code PreToolUse hook that denies a tool call blocks it in every permission mode, including bypassPermissions and --dangerously-skip-permissions, because PreToolUse hooks run before any permission-mode check. A hook that returns "allow" works the other way only partly: deny rules in settings still apply.
How do I get a notification when Claude Code needs me?
To get a notification when Claude Code needs you, add a Notification hook to ~/.claude/settings.json that runs your platform’s notification command, such as osascript on macOS or notify-send on Linux. The Notification event fires when Claude waits for a permission decision or has been idle for about a minute after responding.
Do Claude Code hooks run inside subagents?
Claude Code hooks on tool events run inside subagents: PreToolUse and PostToolUse hooks from settings files, managed settings and plugins fire for a subagent’s tool calls the same way they do in the main conversation. A subagent file can also define hooks in its frontmatter that run only while that subagent is active.



