Claude Code Hooks: Events, Exit Codes and 8 Recipes
Short answer: Claude Code hooks are commands that Claude Code runs automatically at set points in a session. You add them under a "hooks" key in ~/.claude/settings.json (or .claude/settings.json per project), pick an event such as PreToolUse, PostToolUse, Stop or PermissionRequest, optionally filter by tool with a matcher, and control the outcome with exit code 2 or JSON on stdout.
TL;DR
- 33 events as of November 2026, from
SessionStarttoSessionEnd; the five most people use arePreToolUse,PostToolUse,Notification,StopandPermissionRequest. - Structure: event → matcher group →
hooksarray → handler (command,http,mcp_tool,promptoragent). - Exit 0 means carry on, exit 2 blocks (on events that can block), any other code is a non-blocking error.
- JSON output gives finer control: allow, deny or ask on
PreToolUse, allow or deny onPermissionRequest, keep working onStop. - Hooks run with your full user permissions, so read any hook before you add it.
Checked 14 November 2026 against Anthropic’s hooks reference and hooks guide. We make FavTray, so weigh our take accordingly; it appears once below as an example of a PermissionRequest hook.
What are Claude Code hooks?
Claude Code hooks are user-defined commands that run automatically when something specific happens in a Claude Code session, like a tool call, a file edit or the end of a turn. Anthropic’s guide describes them as “deterministic control”: the action always happens, instead of relying on the model to remember to do it.
That’s the difference from writing “always run Prettier” in CLAUDE.md. An instruction is a request the model may follow. A hook is code that runs every time its event fires, whatever the model decides.
| Mechanism | What it is | Runs every time? | Best for |
|---|---|---|---|
| Hooks | Commands or prompts tied to lifecycle events | Yes, when the event and matcher fit | Formatting, notifications, logging, guardrails |
CLAUDE.md | Instructions loaded into context | No, the model chooses | Conventions, project background |
Permission rules (/permissions) | Allow, ask and deny lists for tools | Yes | Hard allow and deny decisions |
| Skills | Instructions and scripts Claude loads on demand | No, Claude or you invoke them | Repeatable multi-step tasks |
Anthropic’s reference is blunt about one boundary: the if filter on hooks is best-effort, so for a hard allow or deny you should use the permission system, with hooks as an extra layer.
Which hook events does Claude Code support?
As of November 2026 the hooks reference lists 33 events. They cover the session (SessionStart, SessionEnd), your prompt (UserPromptSubmit), every tool call (PreToolUse, PermissionRequest, PostToolUse), the end of a turn (Stop), subagents, tasks, compaction, config changes and MCP elicitations. These are the ones worth knowing first:
| Event | When it fires | Matcher filters on | Can it block? |
|---|---|---|---|
SessionStart | A session starts or resumes | startup, resume, clear, compact, fork | No |
UserPromptSubmit | You submit a prompt, before Claude sees it | (no matcher) | Yes, rejects the prompt |
PreToolUse | Before a tool call runs | Tool name (Bash, Edit, Write, mcp__…) | Yes, cancels the call |
PermissionRequest | Claude Code is about to ask you for permission | Tool name | Through JSON decision, not exit 2 |
PostToolUse | After a tool call succeeds | Tool name | No, the tool already ran |
PostToolUseFailure | After a tool call fails | Tool name | No |
Notification | Claude Code sends a notification | Type (permission_prompt, idle_prompt, …) | No |
Stop | Claude finishes responding (not on Ctrl+C) | (no matcher) | Yes, Claude keeps working |
SubagentStart / SubagentStop | A subagent starts or finishes | Agent type | SubagentStop only |
PreCompact / PostCompact | Before and after context compaction | manual, auto | PreCompact only |
ConfigChange | A settings or skills file changes mid-session | Config source | Yes (except policy settings) |
FileChanged | A watched file changes on disk | Literal filenames | No |
SessionEnd | The session ends | clear, logout, prompt_input_exit, … | No |
The rest (Setup, UserPromptExpansion, PermissionDenied, PostToolBatch, MessageDisplay, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, CwdChanged, DirectoryAdded, WorktreeCreate, WorktreeRemove, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult) are covered in the full reference. New events arrive often, so check there before relying on one.
How do you configure hooks in settings.json?
You add a "hooks" object to a Claude Code settings file, keyed by event name. Each event holds a list of matcher groups, and each group holds a hooks array of handlers:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-bash.sh",
"timeout": 30
}
]
}
]
}
}
Where do Claude Code hook settings live?
| File | Applies to | Shared with your team? |
|---|---|---|
~/.claude/settings.json | Every project on your Mac | No |
.claude/settings.json | One project | Yes, commit it |
.claude/settings.local.json | One project | No, it’s gitignored |
| Managed policy settings | The whole organisation | Set by admins |
Plugin hooks/hooks.json, skill or subagent frontmatter | While that plugin, skill or subagent is active | Yes |
Hooks from all levels merge rather than replace each other. Type /hooks inside Claude Code to see a read-only list of what loaded and where each hook came from. To switch every hook off without deleting anything, set "disableAllHooks": true.
What handler types are there?
type | What it does | Default timeout |
|---|---|---|
command | Runs a shell command, event JSON on stdin | 600 s |
http | POSTs the event JSON to a URL | 600 s |
mcp_tool | Calls a tool on a configured MCP server | 600 s |
prompt | Asks a Claude model for a yes or no decision | 30 s |
agent | Runs a subagent that can use tools (experimental) | 60 s |
Override any of them with "timeout" in seconds. UserPromptSubmit command hooks default to 30 seconds, and all SessionEnd hooks share a 1.5-second budget.
How do matchers work in Claude Code hooks?
A matcher decides which tool calls, or which subtypes of an event, a hook group runs for. "*", "" or no matcher at all means everything. A matcher made only of letters, digits, _, -, spaces, commas and | is an exact name or list, like Edit|Write. Anything else is treated as an unanchored JavaScript regex.
Bashmatches only the Bash tool. Matchers are case-sensitive.Edit|Writematches either tool.Edit.*also matchesNotebookEdit; use^Edit$for an exact regex match.- MCP tools are named
mcp__<server>__<tool>, somcp__github__.*matches every tool from thegithubserver.
For finer filtering on tool events, add an if field using permission-rule syntax, such as "if": "Bash(git *)" or "if": "Edit(*.ts)".
What do Claude Code hook exit codes mean?
Exit code 0 means success, exit code 2 means “block this”, and any other code is a non-blocking error that shows a hook error notice while Claude carries on. On exit 2, Claude Code ignores stdout and uses your stderr text as the reason.
| Exit code | Result | Where your output goes |
|---|---|---|
| 0 | Continue | stdout parsed as JSON if it’s one JSON object; plain text becomes context on SessionStart and UserPromptSubmit |
| 2 | Block (on events that can block) | stderr goes to Claude, or to you, as the reason |
| 1 or other | Non-blocking error, action continues | stderr shown as a hook error notice |
Two traps catch most people. Exit 1 does not block anything. And exit 2 can’t block on PermissionRequest (deny through JSON there), PostToolUse (the tool already ran, so Claude only sees your stderr) or Notification (exit code and stderr are ignored).
How do you return JSON from a hook?
Print one JSON object to stdout and exit 0. Every event accepts continue (set false to stop Claude), stopReason and systemMessage; event-specific decisions go in hookSpecificOutput with hookEventName set. To deny a tool call from PreToolUse with a reason:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Destructive command blocked by hook"
}
}
permissionDecision takes allow, deny, ask or defer. When several hooks answer, the most restrictive wins, in the order deny, defer, ask, allow. A deny from PreToolUse holds even with --dangerously-skip-permissions.
On Stop, {"decision": "block", "reason": "Run the tests first"} keeps Claude working, and the reason becomes its next instruction. Check the stop_hook_active field in the input so you don’t loop forever; Claude Code also overrides a Stop hook after eight blocks in a row.
Build the JSON with jq rather than by gluing strings together, so quotes inside values are escaped. Every hook receives JSON on stdin with session_id, transcript_path, cwd and hook_event_name, plus tool_name and tool_input on tool events. The recipes below read it with jq (brew install jq).
What are the most useful Claude Code hook examples?
These eight recipes cover what people search for most: notifications, guardrails, formatting and approvals. Merge each one into your existing "hooks" object rather than replacing it.
1. How do I get a Mac notification when Claude Code needs input?
Use a Notification hook that runs osascript. This is Anthropic’s own macOS example:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
If no banner shows, allow Script Editor under System Settings › Notifications. Terminal-specific setup for Ghostty, iTerm2 and tmux is in our guide to Claude Code notifications on Mac.
2. How do I play a sound when Claude Code finishes?
A Stop hook fires the moment each turn ends:
{
"hooks": {
"Stop": [
{
"hooks": [
{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }
]
}
]
}
}
It fires after every turn, not only at the end of a whole task, and not when you interrupt with Ctrl+C.
3. How do I stop Claude Code running rm -rf?
Save this as .claude/hooks/block-rm-rf.sh and run chmod +x on it:
#!/bin/bash
cmd=$(jq -r '.tool_input.command // empty')
if echo "$cmd" | grep -Eq 'rm[[:space:]]+-[a-zA-Z]*([rR][a-zA-Z]*f|f[a-zA-Z]*[rR])'; then
echo "Blocked: recursive force delete. Ask the user to run it themselves." >&2
exit 2
fi
exit 0
Register it on PreToolUse with the matcher Bash and the command "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm-rf.sh". A regex won’t catch every spelling (rm -r -f, a script that deletes for you), so pair it with a deny rule such as "Bash(rm -rf *)" under permissions.deny.
4. How do I stop Claude Code editing .env files?
Anthropic’s guide has a protect-files.sh script on PreToolUse with the matcher Edit|Write. It reads .tool_input.file_path, loops over patterns such as .env, package-lock.json and .git/, and exits 2 with a “Blocked:” message on a match. Claude sees the message and changes approach. Claude can still change those files through shell commands, so Anthropic recommends Edit deny rules or sandboxing as well.
5. How do I auto-format files after Claude Code edits them?
Run Prettier from PostToolUse on Edit|Write, in your project’s .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\""
}
]
}
]
}
}
Swap in ruff format, gofmt -w or swift-format for other languages. A successful run prints nothing; the file just comes back formatted.
6. How do I log every command Claude Code runs?
Add a second handler to your PreToolUse Bash group:
{ "type": "command", "command": "jq -r .tool_input.command >> ~/.claude/bash.log" }
Hooks in the same group run in parallel, so the log line is written even when the rm guard in recipe 3 blocks the command.
7. How do I remind Claude of project rules after compaction?
Compaction summarises the conversation and can drop details. A SessionStart hook with the matcher compact puts them back, because plain stdout from SessionStart is added to Claude’s context:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{ "type": "command", "command": "echo 'Use pnpm, not npm. Current task: auth refactor.' && git log --oneline -5" }
]
}
]
}
}
Fewer re-explanations after compaction also helps with Claude Code token usage.
8. How do I auto-approve one kind of permission prompt?
Use a PermissionRequest hook with the narrowest matcher you can. Anthropic’s example approves ExitPlanMode, so a finished plan doesn’t stop for a prompt:
{
"hooks": {
"PermissionRequest": [
{
"matcher": "ExitPlanMode",
"hooks": [
{
"type": "command",
"command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input}}}'"
}
]
}
]
}
}
An empty or .* matcher here would approve every prompt, including shell commands and file writes. Never do that. A hook’s allow also doesn’t override deny rules in your settings.
How do apps use the PermissionRequest hook?
Apps that let you approve Claude Code away from the terminal are built on the same event. The hook passes each permission request to the app, waits, and prints a hookSpecificOutput.decision with "behavior": "allow" or "deny" back to Claude Code once you choose.
FavTray is a macOS menu bar app with 15+ developer and productivity tools, free with daily limits, $4.99 once for Lifetime. Its notch island, FavShelf, adds PermissionRequest, Stop and Notification hooks (plus a PreToolUse hook for Claude’s questions) to ~/.claude/settings.json next to yours, and talks to them over a local socket. Requests appear under the notch with Approve and Deny. If you don’t answer within 55 seconds, Claude Code asks in the terminal as usual; FavTray never approves or denies on its own. Turning it off removes only FavTray’s hooks. Approvals are a Pro feature, with a 7-day free trial on every install.
Other apps do the same with different prices and agent support; we compare them in approve Claude Code from the notch. Whatever you install, open /hooks afterwards and read what it added.
How do you debug a Claude Code hook that isn’t working?
Start with /hooks: if the hook isn’t listed under the event you expect, Claude Code never loaded it. Then work through these:
-
Validate the JSON. Trailing commas and comments aren’t allowed in
settings.json. -
Check the matcher’s case.
bashwon’t match theBashtool. -
Make scripts executable with
chmod +x, and use absolute paths or$CLAUDE_PROJECT_DIR. -
Test the script by hand with sample input:
echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | .claude/hooks/block-rm-rf.sh echo $? -
Read the debug log. Start
claude --debug, trigger the hook, then open~/.claude/debug/<session-id>.txt. Press Ctrl+O in a session for the transcript view. -
Silence your shell profile. An
echoin~/.zshrcthat runs before your JSON makes Claude Code treat the output as plain text. Wrap it inif [[ $- == *i* ]]; then … fi. -
Put fields at the right level.
permissionDecisionbelongs insidehookSpecificOutput; at the top level it’s silently ignored.
Are Claude Code hooks safe?
They’re as safe as the commands in them. Anthropic’s warning is direct: command hooks “execute shell commands with your full user permissions” and can modify, delete or read any file your account can.
- Workspace trust: in an interactive session, Claude Code holds back hooks until you accept the trust dialog for the folder. In
claude -pand SDK runs there’s no dialog, so a cloned repo’s.claude/settings.jsonhooks run straight away. Review them first, or run with--settings '{"disableAllHooks": true}'. - Quote variables (
"$VAR"), reject..in file paths, and skip.env,.git/and keys. - Read third-party hooks. Plugins and notch apps add hooks too;
/hooksshows where each came from.
Hooks pair well with the rest of your setup: watch your limits with our Claude Code usage limits guide, and if you run more than one login, see tools for multiple Claude Code accounts. FavTray’s plans and pricing cover the notch approvals described above.
Sources (checked 14 November 2026): Anthropic’s Claude Code hooks reference, hooks guide, permissions and settings docs; jq; Prettier; FavShelf behaviour from the FavShelf page.
Frequently Asked Questions
What are Claude Code hooks?
Claude Code hooks are shell commands, HTTP calls, MCP tools or model prompts that Claude Code runs automatically at fixed points in a session, such as before a tool runs, after a file edit or when Claude finishes responding. You define them under a hooks key in settings.json. Unlike instructions in CLAUDE.md, they always run, so they suit formatting, notifications and guardrails.
Where do I put Claude Code hooks?
Put them in a settings file under a hooks key. Use ~/.claude/settings.json for hooks that apply to every project, .claude/settings.json in a repository for hooks your team shares through git, or .claude/settings.local.json for project hooks only you use. Plugins, skills and subagents can also carry hooks. Hooks from every level are merged, and the /hooks command shows what loaded.
How do I block a command with a Claude Code hook?
Add a PreToolUse hook with the matcher Bash that reads the command from tool_input.command on stdin and exits with code 2 when it matches something you forbid. Claude Code cancels the tool call and passes your stderr text to Claude as the reason. Exit code 1 does not block. For a hard rule, also add a deny rule under permissions in settings.json.
Why is my Claude Code hook not running?
Type /hooks and check the hook is listed under the right event. Matchers are case-sensitive, so bash will not match the Bash tool. Check the JSON has no trailing commas, the script is executable with chmod +x, and jq is installed if the command uses it. Interactive sessions also hold back hooks until you accept the folder's workspace trust dialog. claude --debug writes a log with every hook run.
Can a Claude Code hook approve permission requests automatically?
Yes. A PermissionRequest hook can print JSON with hookSpecificOutput.decision.behavior set to allow or deny, and Claude Code answers the prompt for you. Keep the matcher narrow, because an empty matcher would approve every prompt. A hook's allow never overrides a deny rule in your settings. Notch apps such as FavTray use the same event to show the prompt on screen and send back your choice.
Do Claude Code hooks work on Mac, Linux and Windows?
Yes. Command hooks run in a shell on macOS and Linux, and on Windows they use Git Bash or, with shell set to powershell, PowerShell. Recipes in this guide use macOS tools such as osascript and afplay for alerts, and jq for reading the JSON input, which you can install on a Mac with brew install jq.