Claude Code hooks: events, config and examples
By Maximo Correa · 2026-11-16
Claude Code hooks are user-defined shell commands, HTTP endpoints, MCP tool calls, prompts or subagents that run automatically at set points in a session, such as before a tool call or when a prompt is submitted. Unlike an instruction in CLAUDE.md, a hook always runs, because Claude Code fires it, not the model.
What Claude Code hooks are
Hooks are user-defined shell commands, HTTP endpoints, MCP tool calls, LLM prompts, or subagents that Claude Code runs automatically at specific points in its lifecycle. The official hooks guide puts the benefit in one sentence: hooks give you "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them."
That is the difference between a hook and an instruction. A line in CLAUDE.md asks Claude to format files after editing them, and Claude may or may not comply on a given turn. A hook runs Prettier after every edit because Claude Code itself runs it, not the model. (If you want to know why instructions get skipped, see why Claude ignores your CLAUDE.md.)
Hooks are the right tool when the answer is a rule, not a judgment: format this file, refuse this command, tell me when you are waiting on me. When you need judgment, the docs offer prompt-based and agent-based hooks that ask a Claude model to decide.
In Flowy's index, 481 of 4,286 published repositories ship hooks (Flowy's index, 2026-11-16, published listings). For comparison, 4,038 ship skills. Hooks are the rarer building block, and you can browse the repositories that ship them. The glossary entry for a Claude Code hook gives the short definition.
The hook events
Claude Code fires hooks at named events. The reference groups them into three cadences: per session (SessionStart, SessionEnd), per turn (UserPromptSubmit, Stop, StopFailure), and on every tool call inside the agentic loop (PreToolUse, PostToolUse). The full event table in the reference lists 33 (as of 2026-11-16) events. Grouped by what they react to:
| Area | Events |
|---|---|
| Session | SessionStart, Setup, SessionEnd, InstructionsLoaded, ConfigChange |
| Prompts | UserPromptSubmit, UserPromptExpansion, MessageDisplay |
| Tools and permissions | PreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch |
| Finishing | Stop, StopFailure, Notification |
| Subagents and tasks | SubagentStart, SubagentStop, TaskCreated, TaskCompleted, TeammateIdle |
| Files and directories | CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove |
| Context and model | PreCompact, PostCompact, PreModelSwitch, PostModelSwitch |
| MCP | Elicitation, ElicitationResult |
You will use four of these most. PreToolUse runs before a tool call and can block it. PostToolUse runs after a tool call succeeds. UserPromptSubmit runs when a prompt is submitted, before Claude processes it. Notification runs when Claude Code sends a notification, such as when it is waiting for you.
Subagents have their own pair, SubagentStart and SubagentStop, and the tool events fire inside subagents too. The subagents guide covers how.
Where hooks are configured
Hooks live in JSON settings files, and where you put one decides who it applies to.
| Location | Scope | Shareable |
|---|---|---|
~/.claude/settings.json | All your projects | No, local to your machine |
.claude/settings.json | Single project | Yes, can be committed to the repo |
.claude/settings.local.json | Single project | No, gitignored |
| Managed policy settings | Organization-wide | Yes, admin-controlled |
Plugin hooks/hooks.json | When the plugin is enabled | Yes, bundled with the plugin |
| Skill or subagent frontmatter | While the skill or subagent is active | Yes, defined in the file |
Hook entries merge across levels: user, project and local settings add their own hooks without removing managed ones. Type /hooks in Claude Code to open a read-only browser of every configured hook, labeled by where it comes from. To switch all hooks off without deleting them, set "disableAllHooks": true in your settings.
If you install a plugin that ships hooks, those hooks run when the plugin is enabled. Open /hooks after installing to see them.
The three levels of nesting
A hook configuration has three levels. You choose an event, add a matcher group that filters when it fires, and define one or more handlers to run. Here is the smallest useful shape:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "your-command-here" }
]
}
]
}
}
The matcher filters on a field that depends on the event. For tool events it is the tool name, so Bash matches the Bash tool and Edit|Write matches either of two tools. For Notification it is the notification type, such as permission_prompt or idle_prompt. For SessionStart it is how the session started: startup, resume, clear, compact, or fork. An empty or omitted matcher matches every occurrence.
There are five handler types: command, http, mcp_tool, prompt and agent. Most hooks are command. An optional if field narrows a handler further with permission rule syntax, such as "Bash(git *)" or "Edit(*.ts)", so the command only spawns when the tool call matches. When an event fires, its matching hooks run in parallel.
What a hook receives and how it answers
A command hook receives the event as JSON on stdin. Every event carries common fields such as session_id, transcript_path, cwd and hook_event_name. Tool events add tool_name, tool_input and tool_use_id. A PostToolUse hook also receives tool_response, the result the tool returned.
Your hook answers with its exit code:
| Exit code | Meaning |
|---|---|
| 0 | Success. The action goes ahead. Claude Code applies any JSON you printed to stdout |
| 2 | Blocking error. On events that can block, Claude Code stops the action. Your stderr is the reason |
| Any other | Non-blocking error. The action goes ahead and you see a hook error notice in the transcript |
Exit 2 is the part people get wrong, because whether it blocks depends on the event. The reference has a per-event table. A few rows that matter:
| Event | Can exit 2 block it? |
|---|---|
PreToolUse | Yes, blocks the tool call |
UserPromptSubmit | Yes, the prompt never reaches Claude |
Stop | Yes, Claude is prevented from stopping and continues |
PostToolUse | No. The tool already ran, so stderr is shown to Claude |
Notification | No. Exit code and stderr are ignored |
SessionStart | No. Stderr is shown to the user only |
PermissionRequest | No. Deny through the decision object instead |
So a hook that "blocks" a command must be on PreToolUse. Put the same script on PostToolUse and it can only complain after the fact.
If you want finer control than allow or block, print a JSON object on stdout and exit 0. For PreToolUse that object can set a permissionDecision of "deny" with a reason. For PostToolUse it can add context or feedback for Claude. Print exactly one JSON object with nothing else on stdout, because anything else is read as plain text or a parse failure. A hook that exits 0 with invalid JSON counts as a non-blocking error, so the action goes ahead.
One more behavior worth knowing: on UserPromptSubmit, UserPromptExpansion, SessionStart and PostModelSwitch, plain-text stdout is added as context that Claude can see and act on. A hook that prints a reminder on UserPromptSubmit puts that reminder in front of Claude on every prompt. That documented behavior is how a skill router can stay in context, and it is why a hook is a nudge, not a gate. Whether Claude then loads the skill is a separate step, covered in what skill routing is.
Worked examples
Each example below is a complete configuration. Every one needs jq on your PATH to read the hook's JSON input.
Format files after every edit
This uses PostToolUse with an Edit|Write matcher, so it runs only after Claude edits or creates a file. It pulls the file path out of tool_input and hands it to Prettier. Add it to .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\""
}
]
}
]
}
}
To test it, ask Claude to add a line with single-quoted strings to a JavaScript file. With Prettier's default settings the hook rewrites them to double quotes.
One limit to know: a PostToolUse hook matching Edit|Write does not run when a Bash command rewrites the same file. For file changes from any source, the reference points to the FileChanged event.
Block a dangerous command
This is the case where exit 2 earns its keep. The reference ships a script that blocks rm commands. Save it as .claude/hooks/block-rm.sh and run chmod +x on it:
#!/bin/bash
input=$(cat) # reads the JSON input from stdin
command=$(jq -r '.tool_input.command' <<<"$input")
if [[ "$command" == rm* ]]; then
echo "Blocked: rm commands are not allowed" >&2
exit 2 # Blocking error: tool call is prevented
fi
exit 0 # No decision: the normal permission flow applies
Then register it on PreToolUse for the Bash tool:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh"
}
]
}
]
}
}
A command that starts with rm is blocked, and Claude receives your stderr text as the tool's error. Every other command falls through to the normal permission flow. Read the script's test closely: it matches commands that start with rm. It is a guardrail for a known mistake, and it does not stop find . -delete or a script that calls rm inside. Treat it as a tripwire, and use permission rules and sandboxing for real containment.
Get notified when Claude needs you
Claude Code can wait on you for a permission approval while you work in another window. A Notification hook turns that wait into a desktop alert. This one uses the permission_prompt matcher, which fires when Claude needs you to approve a tool use and the prompt has waited about six seconds. On Linux, using notify-send:
{
"hooks": {
"Notification": [
{
"matcher": "permission_prompt",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
}
]
}
]
}
}
On macOS, swap the command for osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'. Use the idle_prompt matcher instead to be pinged when Claude finished responding about 60 seconds ago and you have not typed since. Put this one in ~/.claude/settings.json, not the project file, because a notification is a personal preference and not a team rule.
Safety: hooks run with your full permissions
The hooks reference carries this warning:
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.
Two practical consequences follow from the docs.
Read a hook before you trust it. This applies to every repository and plugin you pull in. A .claude/settings.json committed to a repo can define hooks, and so can a plugin. In an interactive session Claude Code holds back hooks from every settings file until you accept the workspace trust dialog for the folder. In a -p or SDK session it never shows that dialog and treats the folder as trusted, so hooks committed in a repository you have never opened run anyway. The docs advise reviewing a repository's .claude/ settings before you script claude -p over it, or turning hooks off for that run with --settings '{"disableAllHooks": true}'.
Follow the reference's practices for your own scripts. Validate and sanitize input. Quote shell variables as "$VAR". Check for .. to block path traversal. Use absolute paths. Skip sensitive files such as .env and .git/.
Hooks next to skills, subagents and plugins
Hooks are one of four extension points, and they do different jobs. A skill gives Claude instructions it chooses to load. A subagent runs a task in an isolated context. A plugin packages any of these, hooks included, for sharing. A hook is the only one that runs without Claude deciding to.
To see hooks in the wild, browse the hooks directory. Read the hook command before you enable anything. It runs as you.
Sources
