A hook is your own command that Claude Code runs at a fixed point in its loop: before a tool call, after it, when Claude tries to stop. It gets the event as JSON on stdin and answers with an exit code. A line in CLAUDE.md asks Claude to do something; a hook makes it happen every time.
Use a hook when "please" is not enough
- the model decides whether to follow it
- costs tokens every session
- right for conventions and judgement
- runs on every matching event, no model choice
- no tokens unless it writes feedback
- right for formatting, gates, checks
Rule of thumb: every "after every edit, please…" line in your CLAUDE.md is a hook nobody has written yet.
The Claude Code docs put it the same way in their feature overview: write a hook when you want something to happen every time without asking. Each hook event is a point in the agent loop you would otherwise write by hand. Hooks are not where judgement goes. A check that needs to read code and reason about it belongs in a subagent or a skill (see skills vs subagents vs MCP).
Know the events that matter
The hooks reference lists 30 events as of October 2026. These eight cover most setups:
SessionStart- When a session starts or resumes. Load context, set environment variables.
UserPromptSubmit- When you press enter. Add context, or reject the prompt.
PreToolUse- Before a tool call. Block it, rewrite it or approve it.
PermissionRequest- When a call needs approval. Answer the dialog from a script.
PostToolUse- After a call succeeds. Format, lint, run fast tests.
Stop- When Claude finishes its turn. Refuse to stop until checks pass.
SubagentStop- When a subagent finishes. Check its output.
Notification- When Claude needs your attention. Send a desktop ping or a chat message.
Others cover failures (PostToolUseFailure, StopFailure), batches of parallel calls (PostToolBatch), compaction, worktrees, file changes and model switches.
Wire it up: event, matcher, handler
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write|Read",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-env.sh",
"timeout": 10
}
]
}
]
}
}
- Event
- the key under
hooks:PreToolUse,Stop… - Matcher
- filters by tool name for tool events:
Bash,Edit|Write, a regex likemcp__github__.*. Omit it to match everything. - Handler
command(a shell command),http,mcp_tool,prompt(one model call that returns a decision) oragent(a subagent that can read files).
Two newer fields save a lot of script code. if takes one permission rule, such as "Bash(git *)" or "Edit(*.ts)", and runs the handler only when the call matches. onFailure: "block" makes a crashed or mistyped policy hook block the action instead of silently letting it through (Claude Code v2.1.295 or later). Reference scripts through ${CLAUDE_PROJECT_DIR}, never a relative path.
Read the contract: JSON in, exit code out
Every hook gets the same common fields plus the event's own. This is what PreToolUse receives on stdin when Claude tries to edit a secrets file:
{
"session_id": "abc123",
"cwd": "/home/me/shop",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Edit",
"tool_input": {
"file_path": "/home/me/shop/.env.local",
"old_string": "STRIPE_KEY=sk_test_...",
"new_string": "STRIPE_KEY=sk_live_..."
},
"tool_use_id": "toolu_01ABC"
}
| Exit | What happens |
|---|---|
| 0 | success: the action goes ahead unless JSON you print on stdout says otherwise. Plain stdout reaches Claude only on a few events, such as SessionStart and UserPromptSubmit. |
| 2 | blocking error: stops the action on events that can block, and Claude reads your stderr as the reason. |
| other | non-blocking error, including exit 1: the action goes ahead and you see a “hook error” notice. |
"Stops the action" depends on the event: a blocked PreToolUse cancels the call, a PostToolUse exit 2 cannot undo the tool but shows Claude the stderr, and a Stop exit 2 sends Claude back to work. For richer answers, exit 0 and print JSON: PreToolUse takes hookSpecificOutput.permissionDecision (allow, deny, ask, defer) and can rewrite the call with updatedInput.
Example 1 Keep Claude out of .env files
#!/usr/bin/env bash
# .claude/hooks/block-env.sh (PreToolUse, matcher "Edit|Write|Read")
path=$(jq -r '.tool_input.file_path // empty')
case "$(basename "$path")" in
.env|.env.*)
echo "Blocked: $path holds secrets. Ask the user to change it by hand." >&2
exit 2 ;; # exit 2 = deny; stderr is the reason
esac
exit 0 # no opinion: normal permission rules apply
{"type": "tool_use", "name": "Edit",
"input": {"file_path": "/home/me/shop/.env.local", …}}PreToolUse:Edit hook error: […/block-env.sh]: Blocked: /home/me/shop/.env.local holds secrets. Ask the user to change it by hand.
I can't edit .env.local. Please switch the Stripe key there yourself; the code change is done.
Write the reason for Claude, not for a log file: it decides what to do next from that one line. Pair the hook with a permission rule such as "deny": ["Read(.env*)", "Edit(.env*)"]. Deny rules are evaluated whatever a hook returns, so the rule is the hard wall and the hook adds the explanation and the cases a pattern cannot express. How rules, modes and hooks stack is in permissions and hooks.
Example 2 Lint every file Claude edits
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/lint-file.sh" }
]
}
]
#!/usr/bin/env bash
# .claude/hooks/lint-file.sh (PostToolUse, matcher "Edit|Write")
input=$(cat)
path=$(jq -r '.tool_input.file_path // empty' <<<"$input")
case "$path" in *.ts|*.tsx) ;; *) exit 0 ;; esac
cd "$CLAUDE_PROJECT_DIR"
if ! out=$(npx --no-install eslint --fix "$path" 2>&1); then
echo "eslint found problems it could not fix in $path:" >&2
echo "$out" | tail -n 20 >&2
exit 2 # the edit stands; Claude sees the errors
fi
Linting at build time finds problems twenty edits later. This finds them on the edit that caused them, and eslint --fix repairs most in place. When something is left over, exit 2 puts the errors in front of Claude while the file is still in its head. Keep it fast: a PostToolUse hook runs on every edit, so a 3-second linter makes every edit 3 seconds slower. Use the project's own binary (npx --no-install) so versions match CI.
Example 3 Don't let Claude stop until tests pass
#!/usr/bin/env bash
# .claude/hooks/tests-before-stop.sh (Stop; no matcher)
input=$(cat)
# Already continuing because of this hook once? Let Claude stop this time.
if [ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ]; then exit 0; fi
cd "$(jq -r '.cwd' <<<"$input")"
if ! out=$(npm test --silent 2>&1); then
echo "Tests are failing. Fix them before you finish:" >&2
echo "$out" | tail -n 30 >&2
exit 2 # on Stop, exit 2 means: keep working
fi
- Claude says donethe Stop hook runs
- Tests failexit 2, failures on stderr
- Claude continueswith the failures as feedback
- Stops again
stop_hook_activeis true: let it go
This is the hook that changes what "done" means. It is also the one that can loop forever, which is why the input carries stop_hook_active. Claude Code also caps forced continuations at eight in a row, but the count resets every time Claude calls a tool, so a fix-and-retest cycle can run on. The version above allows one retry and then lets Claude stop and report. For a long autonomous run, /goal and the Stop hook are the two ways to keep Claude working toward a checkable condition (see loop engineering).
Put each hook at the right level
| Location | Applies to |
|---|---|
~/.claude/settings.json | all your projects; not shared |
.claude/settings.json | this repo; committed for the team |
.claude/settings.local.json | this repo, just you; gitignored |
| managed policy settings | the whole organisation; set by admins |
a plugin's hooks/hooks.json | while the plugin is enabled |
| skill or subagent frontmatter | while that skill or subagent is active |
Hooks merge across levels instead of overriding each other: a project hook adds to your user hooks and cannot remove a managed one. Run /hooks to see what actually loaded. Team gates (lint, tests) go in the committed project file; personal ones (a desktop ping) in your user file. Hooks also run inside subagents, with agent_type in the input, and the Agent SDK exposes the same events as callbacks in your own code (see Agent SDK patterns). The wider picture of layers and scopes is harness engineering.
Exiting 1 to "block": only exit 2 blocks. Writing the reason to stdout: on most events Claude never sees stdout, so use stderr with exit 2. A relative script path that breaks when Claude cds. A slow PostToolUse hook on every edit. A Stop hook with no way out. And trusting a hook alone for security: hooks run with your user's permissions, so review any you did not write, and keep hard limits in permission rules and the sandbox (see guardrails).
“How would you stop a coding agent from touching production config?” Layer it: a deny rule for the paths (evaluated first, whatever else happens), a PreToolUse hook for the cases a pattern cannot express (a kubectl context, a branch name) that returns a reason the agent can act on, a sandbox for the shell, and a human approval for the irreversible remainder (approval gates).
Your PreToolUse hook prints "Blocked: no force pushes" and exits 1. What happens to git push --force?
It runs. Exit 1 is a non-blocking error: you see a hook error notice and the action goes ahead. Exit 2 (with the message on stderr) or return JSON with permissionDecision: "deny". Better still, add Bash(git push --force *) to the deny rules.
A PostToolUse lint hook exits 2 on errors. A teammate says the edit should have been rolled back. Is that right?
No. PostToolUse fires after the tool already ran, so exit 2 cannot undo it; it shows Claude the stderr so it fixes the file next. To prevent a bad write, check in PreToolUse instead.
Your Stop hook runs the test suite and exits 2 on failure. On a flaky test Claude loops for ages. What do you change?
Check stop_hook_active and let Claude stop once it has already been sent back (it will then report the failure), cap how many times you push it, and fix or quarantine the flaky test. Do not rely on the eight-in-a-row cap: it resets whenever Claude calls a tool, and a fix attempt is a tool call.
- A hook is a command (or HTTP call, MCP tool, prompt, agent) that runs at a fixed event in the loop, with the event as JSON on stdin.
- Config is event, then matcher, then handler;
ifnarrows by permission rule,onFailure: "block"makes policy hooks fail closed. - Exit 0 proceeds, exit 2 blocks and sends stderr to Claude, anything else is a warning that does not block.
PreToolUsegates,PostToolUsegives feedback,Stopredefines done.- Hooks merge across user, project, local, managed and plugin levels; pair them with deny rules for anything that must never happen.