Claude Code hooks: events, exit codes and examples
Claude Code hooks are commands you configure to run automatically at set points in a session: before a tool call, after a file edit, when Claude finishes a reply, and so on. Anthropic defines them as "user-defined shell commands, HTTP endpoints, MCP tool calls, LLM prompts, or subagents that execute automatically at specific points in Claude Code's lifecycle" (hooks reference, read November 2026). The difference from an instruction in CLAUDE.md is that a hook always runs. Claude can forget an instruction; it can't skip a hook.
The events that matter most
The reference lists 34 events as of November 2026. Most people only ever use a handful:
| Event | When it fires | What it can do |
|---|---|---|
PreToolUse | Before a tool call runs | Allow, deny or ask about the call, or change its input |
PostToolUse | After a tool call succeeds | Run a formatter or linter, give Claude feedback; it can't undo the call |
UserPromptSubmit | When you send a prompt, before Claude reads it | Block the prompt or add context |
Stop | When Claude finishes replying | Make Claude keep going, for example until tests pass |
Notification | When Claude Code sends a notification | Show a desktop alert |
SessionStart | When a session starts, resumes or compacts | Load context or set environment variables |
PreCompact | Before the context is compacted | Block compaction |
The rest cover subagents, permission requests, git worktree creation, model switches, configuration changes and more. Anthropic sorts the common ones by how often they fire: once per session (SessionStart, SessionEnd), once per turn (UserPromptSubmit, Stop), and on every tool call (PreToolUse, PostToolUse).
Where hooks go
Hooks live in Claude Code's settings files:
~/.claude/settings.jsonapplies to all your projects on that computer..claude/settings.jsonapplies to one project and can be committed, so your team shares it..claude/settings.local.jsonapplies to one project and stays out of git.- Managed policy settings apply organization-wide, set by an admin.
Plugins, skills and subagents can carry hooks too. Entries from different levels add up rather than replace each other. Cloud sessions don't read your local ~/.claude/settings.json, so put hooks a cloud session needs in the project file.
How a hook is written
A hook has three layers: the event, a matcher that filters when it fires, and one or more handlers. This one, from Anthropic's guide, runs Prettier on every file Claude edits or writes:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}
The hook receives the event as JSON on standard input, which is why the command reads tool_input.file_path with jq.
Matchers are exact names or lists such as Edit|Write. A matcher with any other character, such as Edit., is treated as a regular expression, and it isn't anchored, so Edit. matches NotebookEdit too. MCP tools are named mcp__<server>__<tool>, so mcp__github__.* matches every tool from a GitHub server. Some events, such as Stop and UserPromptSubmit, ignore matchers and fire every time.
For finer control there is an if field that uses permission rule syntax: "Bash(git )" fires only for git commands, "Edit(.ts)" only for TypeScript files.
Exit codes and decisions
What the hook's process returns decides what happens next:
- Exit 0 means success. If the hook prints JSON, Claude Code reads it as a decision.
- Exit 2 blocks the action, on events that can block. Whatever the hook wrote to standard error becomes the message. Anthropic notes that with exit 2, "even a permissionDecision of 'allow' doesn't let the action through."
- Any other exit code is a non-blocking error. The action goes ahead.
For PreToolUse, the JSON route gives four outcomes in a hookSpecificOutput object: allow, deny, ask or defer. A permissionDecisionReason explains the choice; for a denial it goes to Claude, for "ask" it goes to you. When several hooks disagree, deny wins, then defer, then ask, then allow. Hooks can't override your settings: an "allow" doesn't get past a deny rule.
Here is Anthropic's own example of a hook blocking a protected file. The script lives at .claude/hooks/protect-files.sh:
#!/bin/bash
# protect-files.sh
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
# Normalize Windows backslash separators so the patterns below match
FILE_PATH="${FILE_PATH//\\//}"
PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")
for pattern in "${PROTECTED_PATTERNS[@]}"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0
Make it executable with chmod +x, then register it as a PreToolUse hook with the matcher Edit|Write and the command "$CLAUDE_PROJECT_DIR"/.claude/hooks/protect-files.sh. The guide adds a warning: "Claude can still change the protected files with shell commands." It suggests adding deny rules such as Edit(/.env) and turning on the sandbox as well.
Timeouts and failure
Command hooks time out after 600 seconds by default, prompt hooks after 30 and agent hooks after 60. Matching hooks for one event run in parallel.
A hook that fails doesn't stop anything. A timed-out PreToolUse hook lets the call continue through the normal permission flow, so the docs warn against relying on a hook that hangs to act as a gate. Set onFailure: "block" if a timeout should block. The same goes for a script that crashes with an exit code other than 2. The exception is WorktreeCreate, where any non-zero exit makes worktree creation fail. Write any blocking hook so that its own failure asks or blocks.
Security
Anthropic's documentation warns: "Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration."
In an interactive session, Claude Code holds back every hook until you accept the workspace trust dialog for that folder. In -p mode or through the SDK there is no dialog, so hooks committed in a repository's .claude/settings.json run in a folder you never trusted. Read a repository's settings before running Claude Code non-interactively in it.
To see what is configured, type /hooks for a read-only list that labels where each hook comes from. To switch them all off, set "disableAllHooks": true; that doesn't touch hooks an admin set in managed settings.
Hooks in Codex and Cursor
Both have their own version, and our Codex vs Claude Code comparison covers the wider differences. Codex hooks are on by default, live in ~/.codex/hooks.json or a trusted project's .codex/hooks.json, and need you to review and trust each hook's exact definition before it runs. Codex's docs carry a similar caveat: "A PreToolUse error, timeout, or malformed response can let the tool run" (Codex hooks, read November 2026). Cursor reads .cursor/hooks.json, treats exit code 2 as a deny, and says it can load hooks written for Claude Code (Cursor hooks, read November 2026).
How Neotask uses hooks around Claude Code
Neotask's Code page runs Claude Code, Codex, Cursor and other coding agents on your own accounts with each vendor. Hooks show up in a few places.
A credentials check on shell commands. Neotask can connect to Claude Code in two ways. When a project uses the Agent Client Protocol connection, Neotask adds one PreToolUse hook on shell commands. Claude Code's ask rules match a file name letter for letter, while macOS and Windows open .ENV as the same file as .env, so a read-only command naming a credentials file in other letter case could run without a prompt. The hook reads the command in any letter case, path separator or quoting, and returns ask when it names a credentials file. Because Claude Code lets a command run when a hook fails, the hook is written to ask if its own check fails to load. Neotask then decides it by the thread's approval mode: in Ask and Auto a person is asked, and in Full access the command runs.
Agents can't edit their own hooks. In Safe Mode, Neotask refuses an agent's writes to Claude Code's settings files, .claude/hooks, .claude/commands, .claude/agents, .mcp.json and CLAUDE.md. Otherwise an agent could add a hook that allows its own next command.
Company boundaries switch off personal hooks. When a company run is kept out of certain folders, Neotask turns the sandbox on. If your personal Claude Code settings contain hooks, a status line or plugins, it stops loading them for that run and carries your other settings over, because a personal hook could reach past the boundary.
Codex approvals go through a hook relay. When Neotask runs Codex through Codex's app server, it installs hooks on PreToolUse, PostToolUse, PermissionRequest and Stop that pass each gated call to Neotask as an approval card titled "Codex permission request", with allow once, allow for 30 minutes, or deny. If the relay can't be reached, the call is blocked rather than allowed. Approvals don't time out, and the hook's timeout is set longer than any wait so that Codex never runs a tool because a hook timed out.
Frequently asked questions
Where do I put Claude Code hooks? In a settings file: ~/.claude/settings.json for all projects, .claude/settings.json for a shared project setting, or .claude/settings.local.json for a private one.
How do I block a command with a hook? Use a PreToolUse hook that exits with code 2 and writes the reason to standard error, or prints JSON with "permissionDecision": "deny".
Can a hook approve a tool call? It can skip the permission prompt with "permissionDecision": "allow", but it can't get past a deny rule in your settings.
Do hooks run in subagents? Yes. Hooks from settings files, managed settings and plugins also run inside subagents.