Claude Code hooks are shell commands (or HTTP calls, prompts and agents) that Claude Code runs automatically at fixed points such as PreToolUse, PermissionRequest, Notification and Stop. You define them in the hooks block of settings.json, each hook receives the event as JSON on stdin, and it answers with an exit code (2 blocks) or a JSON object on stdout.
Claude Code hooks are commands that Claude Code runs on its own at specific moments of a session: before a tool runs, when it needs your permission, when it sends a notification, when Claude finishes a reply, and many more. Because the harness runs them, not the model, they always happen. That makes hooks the right tool for rules you never want to depend on the model remembering, such as "never touch .env" or "tell me when you are waiting".
This guide covers what hooks are, the full list of events, the configuration format, how input and output work, the security rules, and three examples you can paste into your own settings. If you are new to how Claude Code decides what to run, start with the Claude Code permissions guide, since several hook events plug directly into that system.
What are Claude Code hooks?
In Claude Code, a hook is a handler attached to a lifecycle event. When the event fires, Claude Code runs every matching handler, passes it the event data as JSON, and reads its result to decide what to do next. The official docs describe them as a way to get deterministic control: certain actions always happen rather than relying on the model to choose them.
There are five handler types:
| Type | What it does |
|---|---|
command | Runs a shell command. The event JSON arrives on stdin. |
http | POSTs the event JSON to a URL and reads the response body as output. |
mcp_tool | Calls a tool on a configured MCP server. |
prompt | Sends a prompt to a Claude model for a single-turn yes or no decision. |
agent | Spawns a subagent that can use tools to verify a condition (marked experimental). |
Most people only ever need command hooks. The rest of this guide focuses on them. For a one-paragraph definition you can share, see the glossary entry on agent hooks.
Which hook events does Claude Code support?
Claude Code currently documents more than thirty hook events. The ones you will use most are PreToolUse, PostToolUse, PermissionRequest, Notification, Stop and SessionStart. The full list, as published in the hooks reference:
| Event | Fires when |
|---|---|
SessionStart | A session begins or resumes |
Setup | Claude Code starts with --init-only, or --init / --maintenance in -p mode |
UserPromptSubmit | You submit a prompt, before Claude processes it |
UserPromptExpansion | A command you typed expands into a prompt |
PreSkillShellCommand | Before a skill's injected shell command runs |
PreToolUse | Before a tool call executes |
PermissionRequest | A tool call needs a permission decision |
PermissionDenied | Auto mode denies a tool call |
PostToolUse | After a tool call succeeds |
PostToolUseFailure | After a tool call fails |
PostToolBatch | After a batch of parallel tool calls resolves |
Notification | Claude Code sends a notification |
MessageDisplay | While assistant text is displayed |
SubagentStart / SubagentStop | A subagent is spawned or finishes |
TaskCreated / TaskCompleted | A task is created or marked completed |
Stop | Claude finishes responding |
StopFailure | A turn ends because of an API error |
TeammateIdle | An agent team teammate is about to go idle |
InstructionsLoaded | CLAUDE.md or .claude/rules/*.md is loaded |
ConfigChange | A config file changes during a session |
CwdChanged | The working directory changes |
DirectoryAdded | A directory is added with /add-dir |
FileChanged | A watched file changes on disk |
WorktreeCreate / WorktreeRemove | A worktree is created or removed |
PreCompact / PostCompact | Before and after context compaction |
PreModelSwitch / PostModelSwitch | Around a model switch |
Elicitation / ElicitationResult | An MCP server asks you for input, and after you answer |
SessionEnd | The session terminates |
The list grows with new releases, so check the official reference before you rely on a newer event. Running /hooks inside Claude Code opens a read-only browser that lists every event, including the ones with no hooks configured.
How do you configure hooks in settings.json?
Claude Code hooks live under a hooks key in a settings file, nested in three levels: event name, then a list of matcher groups, then the handlers. Here is the shape:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/check-bash.sh",
"timeout": 30
}
]
}
]
}
}Where you put this block decides its scope:
| Location | Scope |
|---|---|
~/.claude/settings.json | All your projects, on this machine only |
.claude/settings.json | One project, can be committed and shared |
.claude/settings.local.json | One project, kept out of git |
| Managed policy settings | Organization wide, set by an admin |
A plugin's hooks/hooks.json | While the plugin is enabled |
| Skill or subagent frontmatter | While that skill or subagent is active |
Hooks from all levels are merged, they do not replace each other. To add an event to a file that already has hooks, add it as a sibling key inside the same hooks object. For the rest of the settings file, see the settings.json reference.
Useful handler fields include timeout (seconds), statusMessage, once, and if, which filters by tool and arguments using permission rule syntax such as Bash(rm *). Setting "disableAllHooks": true turns hooks off, although it cannot disable managed hooks from outside managed settings.
How do matchers work?
A matcher narrows which occurrences of an event run your hook. For tool events (PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionDenied), the matcher is the tool name. For Notification, it is the notification type. For SessionStart, it is the source such as startup or resume.
The rules, from the hooks reference:
"*",""or no matcher at all matches everything.- Letters, digits,
_,-, spaces,,and|are matched as exact strings, soEdit|Writematches either tool. - Any other character turns the matcher into an unanchored JavaScript regex, for example
mcp__memory__.*. - Some events have no matcher support (
UserPromptSubmit,Stop,PostToolBatchand others). A matcher on those is silently ignored.
What input does a hook receive?
A Claude Code command hook receives one JSON object on stdin. Every event includes common fields such as session_id, transcript_path, cwd, permission_mode and hook_event_name, and each event adds its own. A PreToolUse hook for a Bash call gets something like this:
{
"session_id": "abc123",
"cwd": "/Users/you/myproject",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test"
}
}Other events carry different fields: Notification adds message, an optional title and notification_type; Stop adds stop_hook_active and last_assistant_message; PermissionRequest adds tool_name, tool_input and optional permission_suggestions. The usual way to read these in a shell script is jq, which you can install on macOS with brew install jq.
Claude Code also sets environment variables for hooks. The most useful is CLAUDE_PROJECT_DIR, the project root where the session started, which lets you reference scripts by an absolute path.
How do exit codes and JSON output work?
A Claude Code hook answers in one of two ways: with an exit code and stderr, or with exit 0 and a JSON object on stdout. Pick one approach per hook.
Exit codes:
- 0: success. Claude Code reads any JSON on stdout. For most events, exit 0 with no output means "no opinion". On
PreToolUse, exit 0 does not approve the call; the normal permission flow still applies. - 2: blocking error. On events that can block, such as
PreToolUse,UserPromptSubmitandPreCompact, the action is stopped and stderr becomes the reason. OnStop, exit 2 makes Claude keep going. OnNotification, it has no effect. - Any other code: a non-blocking error. The action proceeds and a hook error notice appears. Exit 1 does not block, so use exit 2 for policy.
JSON output gives finer control. Universal fields include continue (set to false to stop Claude entirely), stopReason and systemMessage. Event-specific answers go inside hookSpecificOutput. For PreToolUse, the key field is permissionDecision, which accepts allow, deny, ask and, in -p mode only, defer. When several hooks disagree, deny wins over defer, then ask, then allow.
PermissionRequest uses a different shape (a decision object with behavior: "allow" or "deny") and ignores exit code 2. The PermissionRequest hook guide covers it in detail.
Example 1: a desktop notification when Claude needs you
This hook shows a macOS notification whenever Claude Code fires a Notification event, which happens when it waits for a permission answer or has been idle after replying. It is the example the official hooks guide uses as a first hook. Add it to ~/.claude/settings.json:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}If nothing appears, macOS is probably blocking Script Editor, which osascript uses to post notifications. Run osascript -e 'display notification "test"' once, then enable notifications for Script Editor in System Settings. More options, including terminal-notifier and sounds, are in the guide to Claude Code notifications on Mac.
Example 2: block a dangerous command with PreToolUse
This PreToolUse hook refuses any Bash command containing rm -rf and tells Claude why. Save it as ~/.claude/hooks/block-rm.sh and make it executable with chmod +x:
#!/bin/bash
COMMAND=$(jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q 'rm -rf'; then
jq -n '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Destructive command blocked by hook"
}
}'
else
exit 0
fiRegister it:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "~/.claude/hooks/block-rm.sh" }
]
}
]
}
}A deny from a PreToolUse hook holds in every permission mode, including bypassPermissions and --dangerously-skip-permissions, because these hooks fire before any permission mode check. That makes them a good safety net if you ever skip permissions. Keep in mind that a string match is easy to sidestep, so treat this as a guardrail, not a sandbox.
Example 3: log every Bash command Claude runs
This PostToolUse hook appends each successful Bash command to a file, which gives you a simple audit trail:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"
}
]
}
]
}
}PostToolUse fires after the tool has run, so it cannot undo anything. If you need to log attempts as well, add the same command under PreToolUse. To check what a hook did, start Claude Code with claude --debug-file /tmp/claude.log and follow the log in another terminal.
What are the security risks of hooks?
Claude Code command hooks run with your full user permissions. The official reference states that they can modify, delete or access any file your account can reach, and asks you to review and test every hook before adding it. In practice:
- Read every hook in a repository's
.claude/settings.jsonbefore you trust the folder. In interactive sessions, Claude Code holds back hooks until you accept the workspace trust dialog. - Treat the JSON on stdin as untrusted input. Quote shell variables (
"$VAR"), reject paths containing.., and skip sensitive files like.envand.git/. - Use absolute paths for scripts, for example through
$CLAUDE_PROJECT_DIR. - Build JSON output with
jqrather than string concatenation, so quotes are escaped. - Be careful with hooks that approve things. A
PermissionRequestorPreToolUsehook that returnsallowwith a broad matcher quietly removes the human from the loop. The auto approve risks post explains why.
Answering hook events from the menu bar
Hooks are also how outside tools connect to Claude Code. Allowbar, a Mac menu bar app for Claude Code and Codex, works this way: it adds its own entries to ~/.claude/settings.json and leaves your other settings and hooks untouched. Events go to a small local server on your Mac, nothing is sent to a cloud service.
When Claude Code asks for permission, a Dynamic Island style panel slides down with the project, the tool and the exact command, with Allow, Block and Terminal buttons. Allowbar never approves anything on its own: if you do not answer, or the app is closed, the question goes back to the terminal as usual. It also lists every session with its state and tells you when a task is done. It is Mac only (macOS 14 or later) and supports Claude Code and Codex.
Allowbar is in private beta. Join the waitlist; the launch price is $9.99 instead of $29.90.
Sources:
- Claude Code hooks reference
- Automate actions with hooks (hooks guide)
- Configure your terminal for Claude Code
Frequently asked questions
Where do I put Claude Code hooks?
Put them under the hooks key of a settings file. Use ~/.claude/settings.json for hooks that apply to all your projects, .claude/settings.json for project hooks you want to commit, and .claude/settings.local.json for project hooks you keep private. Run /hooks to see what is loaded and where each hook comes from.
Why is my Claude Code hook not firing?
Check that the event name and matcher are right (matchers are case sensitive), that the script is executable, and that jq is installed if the script uses it. If your shell profile prints text on startup, it can corrupt the hook's JSON output. Start Claude Code with --debug-file to see what ran.
Does exit code 1 block a tool call?
No. Only exit code 2 blocks, and only on events that can block, such as PreToolUse. Exit code 1 is treated as a non-blocking error and the action continues.
Can a hook approve permission prompts automatically?
Yes. A PreToolUse hook can return permissionDecision: "allow" and a PermissionRequest hook can return behavior: "allow". Deny rules in your settings still apply. Keep the matcher as narrow as possible, since a broad one approves file writes and shell commands without you seeing them.
Do hooks work in non-interactive mode?
Yes, hooks run with claude -p too. Some behavior differs: the defer decision only exists in -p mode, and in a -p run without a permission host, a call that would prompt is denied unless something such as a PermissionRequest hook approves it.