Claude Code Hooks: 12 Working Examples, Windows Included
Claude Code hooks explained with 12 working examples: every event, settings.json setup, exit codes, Windows and PowerShell fixes, and the hooks I run daily.
Claude Code hooks are shell commands (or HTTP calls, MCP tools, prompts or agents) that Claude Code runs for you at fixed points in a session: before a tool call, after a file edit, when Claude needs your input, when it finishes a turn. You define them in settings.json, and because the harness runs them rather than the model, they fire every time instead of whenever Claude remembers to. This guide covers every hook event as of November 2026, a minimal setup, 12 examples (several from my own daily setup on Windows) and the fixes for hooks that don’t fire.
Everything factual below was checked against the official hooks reference and hooks guide on November 30, 2026. Claude Code ships changes weekly, so check those pages if something here doesn’t match your version. For more Claude Code setups, see the Claude Code hub.
TL;DR
- Hooks live under a
"hooks"key in~/.claude/settings.json(all projects),.claude/settings.json(one project, shareable) or.claude/settings.local.json(one project, private). Plugins, skills and subagents can ship them too. - There are 34 hook events. The ones most people need are
PreToolUse,PostToolUse,Notification,Stop,SessionStartandUserPromptSubmit. - Exit code 0 means success, exit 2 blocks (on events that can block), and any other code is a non-blocking error. Exit 1 does not block anything.
- On Windows, shell-form hooks run in Git Bash if it’s installed and in PowerShell if it isn’t. Set
"shell": "powershell"or use exec form ("args": [...]) to stop guessing. - Hooks run with your full user permissions. Read every hook a plugin or repo brings before you enable it.
Every Claude Code hook event
The “Can block” column follows the docs’ exit code 2 table. “Typical use” is my summary.
| Event | When it fires | Can block? | Typical use |
|---|---|---|---|
SessionStart | A session begins, resumes, clears, compacts or forks | No | Load branch info or reminders into context |
Setup | --init-only, or --init/--maintenance in -p mode | No | One-time CI preparation |
UserPromptSubmit | You submit a prompt, before Claude sees it | Yes | Add context, reject prompts |
UserPromptExpansion | A typed command expands into a prompt | Yes | Gate specific slash commands |
PreSkillShellCommand | Before a skill’s injected shell command runs | Yes | Vet commands inside skills |
PreToolUse | Before a tool call runs | Yes | Block dangerous commands, rewrite input |
PermissionRequest | A tool call needs a permission decision | Via JSON only | Auto-approve or deny prompts |
PermissionDenied | Auto mode denies a tool call | No | Tell the model it may retry |
PostToolUse | After a tool call succeeds | No (stderr goes to Claude) | Format, lint, test |
PostToolUseFailure | After a tool call fails | No | Log failures |
PostToolBatch | After a batch of parallel tool calls resolves | Yes | Stop the loop before the next model call |
Notification | Claude Code sends a notification | No | Desktop alerts |
MessageDisplay | While assistant text is displayed | No | Change what you see on screen |
SubagentStart | A subagent is spawned | No | Inject rules into the subagent |
SubagentStop | A subagent finishes | Yes | Make a subagent keep going |
TaskCreated | A task is created via TaskCreate | Yes | Validate tasks |
TaskCompleted | A task is marked complete | Yes | Run tests before a task closes |
Stop | Claude finishes responding | Yes | Quality gates, “did you save notes?” |
StopFailure | The turn ends on an API error | No | Alert on rate limits |
TeammateIdle | An agent team teammate is about to go idle | Yes | Keep a teammate working |
InstructionsLoaded | A CLAUDE.md or .claude/rules/*.md file loads | No | Audit which instructions loaded |
ConfigChange | A config file changes mid-session | Yes (not policy settings) | Log or block settings edits |
CwdChanged | The working directory changes | No | Reload direnv |
DirectoryAdded | A directory is added with /add-dir | No | Set up the new repo |
FileChanged | A watched file changes on disk | No | React to .env edits |
WorktreeCreate | A worktree is being created | Yes (any non-zero exit) | Replace default git worktree logic |
WorktreeRemove | A hook-created worktree is removed | Yes (any non-zero exit) | Clean up |
PreCompact | Before context compaction | Yes | Steer the compaction summary |
PostCompact | After compaction | No | Logging |
PreModelSwitch | Before a requested model switch | Yes | Stop expensive model switches |
PostModelSwitch | After the model changes | No | Add context for the new model |
Elicitation | An MCP server asks for user input | Yes | Answer or decline MCP forms |
ElicitationResult | After you answer an MCP elicitation | Yes | Check the response |
SessionEnd | The session ends | No | Cleanup (1.5-second budget by default) |
Quick start: your first hook in two minutes
A hook config has three levels: the event, a matcher group that filters it, and one or more handlers. Here is a minimal Stop hook that appends a line to a log every time Claude finishes a turn. It works on macOS, Linux and Windows with Git Bash installed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$(date) turn finished\" >> ~/claude-stops.log"
}
]
}
]
}
}
Put it in ~/.claude/settings.json. If the file already has a "hooks" object, add "Stop" next to the existing events instead of replacing it. Type /hooks in Claude Code to confirm it’s listed (the menu is read-only and shows where each hook comes from). Edits are normally picked up by the file watcher, so you rarely need a restart.
Your hook gets its input as JSON on stdin: session_id, transcript_path, cwd, hook_event_name, plus event fields such as tool_name and tool_input. Matchers come in two kinds. A value made only of letters, digits, _, -, spaces, , and | is an exact name or list (Edit|Write). Anything else is an unanchored JavaScript regex, so Edit.* also matches NotebookEdit. Omit the matcher or use "*" to match everything.
12 Claude Code hooks examples
1. Get a notification when Claude needs you
The Notification event fires on types like permission_prompt (a prompt has waited about six seconds) and idle_prompt (Claude finished about 60 seconds ago and you haven’t typed). The docs’ Windows version opens a message box:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
}
]
}
]
}
}
Windows note: the dialog can open behind your terminal. If you use Windows Terminal, a quieter option is the terminalSequence output field, which lets Claude Code emit an OSC 9 notification for you (the docs list Windows Terminal among the supported terminals). This one-liner prints the right JSON:
1
2
$seq = "$([char]27)]9;Claude Code needs your attention$([char]7)"
@{ terminalSequence = $seq } | ConvertTo-Json -Compress
Save it as a .ps1 and call it with the exec-form pattern shown in example 4. It only works in interactive sessions.
2. Auto-format every file Claude edits
PostToolUse with an Edit|Write matcher runs after each file edit. The official example pipes the path to Prettier:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}
It needs jq. On Windows that means Git Bash plus a jq binary on your PATH. If you don’t want jq, read stdin in Python or Node instead.
3. Block edits to .env and lock files
Exit code 2 from a PreToolUse hook blocks the call and sends your stderr to Claude, so it can change approach. Save as .claude/hooks/protect-files.sh:
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}" # normalize Windows backslashes
for pattern in ".env" "package-lock.json" ".git/"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0
Register it under PreToolUse with matcher Edit|Write and "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh". Claude can still touch those files through shell commands, so pair this with Edit(...) deny rules in permissions.deny.
4. Block rm -rf and Remove-Item -Recurse on Windows
This one shows two features at once. The if field uses permission-rule syntax so the script only spawns for matching commands, and exec form (args) runs PowerShell with no shell quoting at all:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "powershell.exe",
"args": ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"]
},
{
"type": "command",
"if": "PowerShell(Remove-Item *)",
"command": "powershell.exe",
"args": ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"]
}
]
}
]
}
}
1
2
3
4
5
6
7
8
9
# .claude/hooks/block-rm.ps1
$callInput = [Console]::In.ReadToEnd() | ConvertFrom-Json
$command = $callInput.tool_input.command
if ($command -match 'rm -rf|Remove-Item.*-Recurse') {
@{ hookSpecificOutput = @{
hookEventName = "PreToolUse"
permissionDecision = "deny"
permissionDecisionReason = "Destructive command blocked by hook" } } | ConvertTo-Json
} else { exit 0 }
One if holds exactly one rule, which is why each tool gets its own handler. The docs call if best-effort, so use permission deny rules when you need a hard guarantee.
5. Re-inject project context after compaction
Compaction can drop details. A SessionStart hook with the compact matcher runs after every compaction, and its plain stdout goes straight into Claude’s context:
1
2
3
4
5
6
7
8
9
10
11
12
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{ "type": "command", "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing.'; git log --oneline -5" }
]
}
]
}
}
For rules that never change, CLAUDE.md is simpler. Use this for things that change, like recent commits.
6. My daily driver: a Stop hook that makes Claude save its notes
This is the only hook in my global settings, and it runs on every session on my Windows machine. I keep project notes in a plain Markdown folder that several coding agents share. Agents forget to update it, so the Stop hook counts how much work happened since the last write to that folder. Past a threshold, it blocks the stop once and tells Claude to save decisions and next steps or say nothing needs saving. The same script first copies Claude Code’s plan files from ~/.claude/plans/ into my notes, inside its own try, so a plan never gets lost and a failed copy never blocks anything.
The config, with my paths made generic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "py -3 \"C:/Users/you/.claude/hooks/memory_nudge.py\"",
"timeout": 30
}
]
}
]
}
}
And a trimmed version of the script, which I tested before publishing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# ~/.claude/hooks/memory_nudge.py
import json, os, re, sys
THRESHOLD = 6 # how much unsaved work before the nudge fires
NOTES = "/notes/" # any write under this folder counts as a save
STATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "state")
WORK = re.compile(r'"name":\s*"(Edit|Write|WebSearch|WebFetch)"')
def unsaved_work(transcript, after):
count, last = 0, 0
with open(transcript, encoding="utf-8", errors="replace") as f:
for last, line in enumerate(f, 1):
if '"tool_use"' not in line:
continue
if NOTES in line.replace("\\\\", "/"):
count = 0 # a save resets the counter
elif last > after and WORK.search(line):
count += 1
return count, last
def main():
event = json.loads(sys.stdin.buffer.read().decode("utf-8") or "{}")
if event.get("stop_hook_active"):
return # never block twice in a row
path = event.get("transcript_path")
if not path or not os.path.exists(path):
return
sid = re.sub(r"[^\w-]", "_", event.get("session_id", "x"))
state = os.path.join(STATE_DIR, sid + ".json")
try:
after = json.load(open(state)).get("nudged_at", 0)
except (OSError, ValueError):
after = 0
count, last = unsaved_work(path, after)
if count < THRESHOLD:
return
os.makedirs(STATE_DIR, exist_ok=True)
json.dump({"nudged_at": last}, open(state, "w"))
print(json.dumps({"decision": "block", "reason": (
"Save anything durable from this session to ~/notes "
"(decisions, gotchas, next steps), or say in one line "
"that nothing needs saving.")}))
if __name__ == "__main__":
try:
main()
except Exception:
pass # fail open
What I learned running it:
- Check
stop_hook_active. It’struewhen Claude is already continuing because of a Stop hook, and without the check you get a loop. Claude Code caps it at eight consecutive continuations (raise it withCLAUDE_CODE_STOP_HOOK_BLOCK_CAP), but eight wasted turns still cost money. My runaway cost checklist covers that failure mode. - Block with JSON on exit 0, not exit 2. On
Stop, if stdout is blank and stderr mentionsNo such file, Claude Code assumes a missing script and treats exit 2 as non-blocking. Adecision: "block"with areasoncan’t be misread. - Fail open. The whole
main()sits in atry, because a bug in a note-taking hook should never trap a session. - On Windows,
py -3finds the installed Python 3 from Git Bash or PowerShell alike. Forward slashes avoid escaping backslashes twice (once for JSON, once for Bash). Reading stdin as bytes and decoding UTF-8 means a non-ASCII path doesn’t depend on Windows’ default code page. - The transcript can lag. The docs say
transcript_pathmay not include the latest messages yet, which is fine for counting earlier work. For the final reply, readlast_assistant_messagefrom the Stop input.
You can also write this in exec form, which skips shell quoting: "command": "py", "args": ["-3", "C:/Users/you/.claude/hooks/memory_nudge.py"].
7. Inject rules into every subagent
I didn’t write this one. A coding-style plugin I use registers a SubagentStart hook, and every subagent I spawn starts with the plugin’s rules already in its context. SubagentStart can’t block, but it can return additionalContext:
1
2
3
4
5
6
{
"hookSpecificOutput": {
"hookEventName": "SubagentStart",
"additionalContext": "Follow the project's security guidelines for this task"
}
}
The plugin pairs it with SessionStart and UserPromptSubmit hooks, each with a 5-second timeout and a statusMessage, so the spinner says what’s loading instead of pausing silently.
8. Run a plugin script the Windows-safe way
An SEO plugin I run validates structured data after every Edit|Write. Its hook uses exec form with node as the command, and node then launches a Python script. That pattern is deliberate. The docs note that on Windows, exec form needs a real executable, and the .cmd and .bat shims in node_modules/.bin aren’t one. node.exe is, so this works on every OS:
1
2
3
4
5
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"]
}
Path placeholders such as ${CLAUDE_PLUGIN_ROOT} and ${CLAUDE_PROJECT_DIR} are substituted into each argument as plain strings, so spaces in paths need no quoting.
9. Fire only on git push with if
A security plugin I use suggests a scan after you push. It hangs several handlers off one PostToolUse Bash matcher and filters each with if:
1
2
3
4
5
6
7
8
9
10
11
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/hooks.sh\" tip push || true",
"if": "Bash(git push *)",
"timeout": 5
}
]
}
The || true is worth noticing. It forces exit 0, so the script can only influence Claude through JSON output, never by an accidental exit 2. The same plugin sets "onFailure": "continue" on a PermissionRequest hook so a crash never blocks you, and marks its metrics hook "async": true so it never slows a turn.
10. Run tests in the background
"async": true starts the hook and lets Claude keep working. Its additionalContext arrives on the next turn. Async hooks can’t block, and timeout isn’t enforced on them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/run-tests-async.sh",
"args": [],
"async": true
}
]
}
]
}
}
The script runs npm test and prints {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": "Tests failed after editing ..."}}. Use jq -nc to build that JSON so quotes in test output don’t break it. In claude -p runs, Claude Code kills async hooks that are still running at teardown.
11. Auto-approve leaving plan mode
PermissionRequest hooks can answer a permission prompt for you. The docs’ example approves only ExitPlanMode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PermissionRequest": [
{
"matcher": "ExitPlanMode",
"hooks": [
{
"type": "command",
"command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input}}}'"
}
]
}
]
}
}
Keep the matcher narrow. An empty matcher here would approve every prompt, including shell commands.
12. Let a model decide whether the work is done
A type: "prompt" hook sends the hook input to a Claude model and expects {"ok": true} or {"ok": false, "reason": "..."}. On Stop, ok: false sends Claude back to work with the reason as its next instruction:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."
}
]
}
]
}
}
Prompt hooks default to a 30-second timeout. type: "agent" hooks can read files and run tools before deciding, but the docs still label them experimental.
Security: hooks run as you
The docs put it plainly: command hooks “execute shell commands with your full user permissions.” A hook can read your SSH keys or delete your home folder as easily as it can run Prettier.
In an interactive session, Claude Code holds back hooks until you accept the workspace trust dialog for the folder. In -p and SDK sessions there is no dialog and the folder counts as trusted, so a cloned repo’s .claude/settings.json hooks run immediately. Before scripting claude -p over someone else’s repo, read its .claude/ folder or pass --settings '{"disableAllHooks": true}'.
Plugin hooks merge with yours once the plugin is enabled. When I checked my own machine for this post, 3 of my 10 enabled plugins registered hooks on 8 different events, on top of the one hook I wrote. None looked malicious, but I hadn’t read all of them before installing. Open each plugin’s hooks/hooks.json and the scripts it calls.
On the defensive side, a hook’s permissionDecision: "deny" blocks a tool even in bypassPermissions mode, so PreToolUse is the right place for guardrails. Organizations can restrict hooks to managed ones with allowManagedHooksOnly.
Malicious skills and plugins are not hypothetical. The skills.sh credential theft checklist walks through a real campaign and what to check.
Troubleshooting Claude Code hooks
Hook not firing. Run /hooks and confirm it’s under the right event. Matchers are case-sensitive. mcp__memory matches nothing because it’s treated as an exact string; use mcp__memory__.*. A matcher on an event without matcher support (such as Stop or UserPromptSubmit) is silently ignored. Skill hooks only appear after the skill is invoked.
It ran but didn’t block. Exit 1 is a non-blocking error. Use exit 2, or exit 0 with a JSON decision. On PreToolUse, a timed-out hook doesn’t block either, unless you set "onFailure": "block".
JSON is ignored. Stdout must be one JSON object and nothing else. Git Bash can source your profile, and one echo there breaks it; wrap profile echoes in if [[ $- == *i* ]]. Also check field placement: permissionDecision and additionalContext belong inside hookSpecificOutput.
Timeouts. The default is 600 seconds for command, HTTP and MCP tool hooks, cut to 30 on UserPromptSubmit and model-switch events. SessionEnd hooks share a 1.5-second budget unless you set a longer timeout. Set your own per hook, in seconds.
Windows paths and shells.
- Shell form runs in Git Bash if installed, otherwise PowerShell. A Bash script with no Git Bash fails, so set
"shell": "powershell"or install Git for Windows (or pointCLAUDE_CODE_GIT_BASH_PATHat it). - In PowerShell hooks write
$env:CLAUDE_PROJECT_DIRor${CLAUDE_PROJECT_DIR}. The bare$CLAUDE_PROJECT_DIRresolves to$null. blocking because Git Bash wasn't foundmeans aPreToolUseorPermissionRequesthook failed without Git Bash and blocked the call. Add"onFailure": "continue"if the call should go ahead.PowerShell started no programmeans yourcommandis only a quoted path. Put&before it with"shell": "powershell", or use exec form.
See what happened. Start with claude --debug and read ~/.claude/debug/<session-id>.txt, or press Ctrl+O for the transcript view. Look for Hooks: lines with durations to spot slow hooks.
FAQ
Where is the official Claude Code hooks documentation?
The hooks reference (events, schemas, exit codes) and the hooks guide (examples, troubleshooting). Old docs.claude.com/en/docs/claude-code/hooks links redirect there.
Do Claude Code hooks work on Windows?
Yes. With Git Bash installed, shell-form hooks run in Git Bash; without it, they run in PowerShell. For predictable behavior, set "shell": "powershell" or use exec form with a real .exe such as powershell.exe, node or py. My Stop hook has run daily on Windows through Git Bash with py -3.
How do I get a Claude Code hooks notification when Claude is waiting?
Add a Notification hook. Match permission_prompt for approvals or idle_prompt for “Claude finished a minute ago”, or leave the matcher empty for both. Example 1 has the Windows command. To react the instant a permission prompt appears, use a PermissionRequest hook instead.
How do Claude Code skills and hooks work together?
Skills can declare hooks in their frontmatter, in the same format as settings.json. Those hooks register only after the skill is invoked and are removed when you /clear or leave the session. "once": true removes a skill hook after its first successful run, and it’s honored only in skill frontmatter.
Are there good Claude Code hooks on GitHub?
Anthropic’s repo has a Bash command validator example, and many plugins ship a hooks/hooks.json you can read. Treat any hook from GitHub as code you’re about to run with your own permissions, and read it first.
What are the best Claude Code hooks to start with?
A Notification alert, a PostToolUse formatter and a PreToolUse guard on destructive commands. A Stop hook is worth adding once you have a habit you want enforced, like saving notes or running tests. If you’re still choosing tools, my Cursor vs Claude Code comparison and Copilot vs Claude Code vs OpenCode cover the wider picture.
Sources
- Claude Code hooks reference, accessed November 30, 2026
- Automate actions with hooks (guide), accessed November 30, 2026
- Bash command validator example
- My own
~/.claude/settings.json, Stop hook script and installed pluginhooks.jsonfiles, reviewed November 30, 2026
