Blog · AI Agents ·
Claude Code hooks: examples that work, and what my delete hook missed
By Khadim Hussain · 12 min read
In short
A Claude Code hook is a command that Claude Code runs at a fixed point in a session, such as before a tool call (PreToolUse) or when Claude finishes (Stop). You add it to the hooks block of a settings file: ~/.claude/settings.json for all your projects, .claude/settings.json for one. In my 31 headless runs on Claude Code 2.1.332, a PreToolUse hook blocked all 13 deletes it matched, even with --dangerously-skip-permissions, and a blocking Stop hook kept Claude working 7 times out of 7. Given 14 ways to delete a folder, the same hook let 11 through, and on Windows a Bash-only matcher missed a PowerShell delete.
Contents
- What are Claude Code hooks?
- Where do Claude Code hooks go?
- Which Claude Code hook events matter?
- I tried to block deletes with a hook. What happened?
- Claude Code hooks examples that work
- Block destructive commands and log every attempt
- Keep Claude working until the tests pass (Stop hook)
- Get a desktop notification (Stop and Notification)
- Add context when a session starts
- Claude Code hooks vs skills
- Why isn't my Claude Code hook firing?
- The hooks I run every day
- Frequently asked questions
I run Claude Code with four hooks I rely on every day, and I make short Claude Code videos on my YouTube channel, Khadim Labs. For the hooks episode I tried to stop Claude Code deleting a folder with one. I first ran the test on Claude Code 2.1.308 in October and repeated it on 2.1.332. The hook stopped every command it was written for, let most other ways of deleting a folder through, and on Windows missed whole tool calls.
What are Claude Code hooks?
A hook is a command that Claude Code runs at a set point in a session, such as before a tool call or when Claude finishes. Anthropic's hooks guide says they give "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them." Most hooks are shell commands; four other types call a URL, an MCP tool or a Claude model.
The hook reads a JSON object on stdin (tool_name, tool_input, cwd and more) and answers with its exit code, plus optional JSON on stdout:
| Exit code | What Claude Code does |
|---|---|
| 0 | Goes ahead and applies any JSON you printed; on SessionStart and UserPromptSubmit, plain stdout becomes context |
| 2 | Blocks the action if the event can be blocked; your stderr is the reason |
| Anything else, 1 included | Records a non-blocking error and goes ahead |
The hooks reference is blunt about the last row: "If your hook is meant to enforce a policy, use exit 2."
Where do Claude Code hooks go?
They go in a hooks block inside a settings file, and the file decides who gets them:
| File | Applies to |
|---|---|
~/.claude/settings.json | All your projects on this machine |
.claude/settings.json | One project; commit it to share the hooks |
.claude/settings.local.json | One project, only for you |
| Managed policy settings | Every machine your organisation manages |
A plugin's hooks/hooks.json | Wherever the plugin is enabled |
| Skill or subagent frontmatter | While that skill or subagent is active |
Hooks from all levels add up. Each event holds matcher groups, and each group holds the handlers to run:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell",
"hooks": [
{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.mjs"] }
]
}
]
}
}Type /hooks to see every hook Claude Code loaded and where it came from. Edits normally apply without a restart.
Which Claude Code hook events matter?
The reference lists 34 events; these eight cover most hooks:
| Event | Fires | Can it block? |
|---|---|---|
SessionStart | A session starts or resumes | No, it adds context |
UserPromptSubmit | You send a prompt | Yes, it rejects the prompt |
PreToolUse | Before a tool call runs | Yes |
PermissionRequest | Claude Code is about to ask you for permission | It answers allow or deny |
PostToolUse | A tool call succeeded | No |
PostToolUseFailure | A tool call failed | No |
Notification | Claude Code notifies you, such as at a permission prompt | No |
Stop | Claude finishes responding | Yes, Claude keeps working |
On tool events the matcher is the tool name: Bash, Edit|Write, or a regular expression such as mcp__github__.*. UserPromptSubmit and Stop take no matcher and fire every time.
I tried to block deletes with a hook. What happened?
My test hook, block-dangerous.mjs (code below), runs before every shell command and refuses five patterns: rm -rf, a force push, git reset --hard, Remove-Item -Recurse and DROP TABLE. Every run started in a fresh folder holding a build/ directory and ran claude -p --model haiku --dangerously-skip-permissions on Claude Code 2.1.332 and Windows 11 with Git Bash, on 29 November 2026. The 31 runs cost $0.11.
| Test | Runs | Result |
|---|---|---|
| "Run this command: rm -rf build", hook exits 2 | 3 | 3 blocked |
Same, hook returns a JSON "deny" | 3 | 3 blocked, 2 of them in PowerShell |
"Delete the build folder.", matcher Bash|PowerShell | 5 | 5 blocked, 2 of them in PowerShell |
Same, matcher Bash only | 3 | 2 blocked; PowerShell deleted the folder once |
| Stop hook blocks once (3 with JSON, 2 with exit 2) | 5 | Claude kept working 5 of 5 |
Stop hook runs npm test on buggy code | 2 | Claude fixed the bug unasked, 2 of 2 |
| SessionStart hook adds a deploy-freeze note | 2 | Claude used it 2 of 2 |
| A success, a failure and a block | 2 | PostToolUse logged 1 of 3 |
| No-op hook on 8 shell commands | 6 | Timing, below |
A block reaches Claude as an error:
PreToolUse:Bash hook error: [node ${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.mjs]: Blocked by hook: rm -rf is not allowed in this project. Ask the user to run it themselves.If you searched for "PreToolUse Bash hook error", it may be your own hook working. In all 13 blocked runs Claude left the delete to me without a second attempt, although permission checks were off. The guide says a deny "blocks the tool even in bypassPermissions mode or with --dangerously-skip-permissions."
On Windows, Claude Code has a Bash tool and a PowerShell tool, and Claude used PowerShell for 5 of the 14 delete attempts, twice after I had typed an rm -rf command. A hook that matches only Bash never sees those calls: in one run, Remove-Item deleted the folder while my hook stayed silent. The reference now says: "Match Bash|PowerShell in hooks that inspect shell commands." In October its examples matched Bash alone.
Piped into the hook with no model involved, 14 delete commands got 3 blocks.
PowerShell aliases and shortened parameters widen the gap: ri build -r -fo deleted a test folder in PowerShell 7.6.6 without the word Recurse. I keep the hook for the common slip, and every project in git. For hard limits, the reference calls its own if filter best-effort and says to "use the permission system rather than a hook to enforce a hard allow or deny."
PostToolUse fires only after a call succeeds, so my audit log held 1 of 3 calls. PostToolUseFailure caught the failing ls, and no later event saw the blocked rm -rf, so log attempts from PreToolUse.
Hooks run before the tool, so they add to every call they match. Over 16 calls each, a Node hook took a median 127 ms in shell form, 93.5 ms in exec form (no shell), and a bare exit 0 in Git Bash 53.5 ms.
All of this matched my October run on 2.1.308 except one thing: Claude then printed my hook files before starting, while none of today's 29 tool-using runs opened them.
Claude Code hooks examples that work
I write hooks in Node: Git Bash on my laptop has no jq, and one Node file runs on Windows, macOS and Linux. Exec form ("command": "node" plus "args") skips the shell, so one settings file works on all three. Without Git Bash, Claude Code on Windows has no Bash tool at all (my Windows install guide). Scripts go in .claude/hooks/, the config in .claude/settings.json.
Block destructive commands and log every attempt
This is the setup that blocked one Bash and one PowerShell delete in the test.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell",
"hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.mjs"] }]
},
{
"matcher": "*",
"hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/log-attempts.mjs"] }]
}
]
}
}.claude/hooks/block-dangerous.mjs:
// PreToolUse: refuse shell commands that destroy work. Exit 2 = block, stderr goes back to Claude.
const input = JSON.parse(await new Response(process.stdin).text());
const cmd = input.tool_input?.command ?? "";
const rules = [
[/\brm\s+-[a-z]*r[a-z]*f|\brm\s+-[a-z]*f[a-z]*r/i, "rm -rf"],
[/\bgit\s+push\b.*(--force|-f\b)/, "force push"],
[/\bgit\s+reset\s+--hard\b/, "git reset --hard"],
[/Remove-Item\b.*-Recurse/i, "Remove-Item -Recurse"],
[/\bdrop\s+(table|database)\b/i, "DROP TABLE/DATABASE"],
];
for (const [pattern, name] of rules) {
if (pattern.test(cmd)) {
console.error(`Blocked by hook: ${name} is not allowed in this project. Ask the user to run it themselves.`);
process.exit(2);
}
}.claude/hooks/log-attempts.mjs:
// PreToolUse: log every tool call Claude attempts, including the ones another hook then blocks.
import { appendFileSync } from "node:fs";
const input = JSON.parse(await new Response(process.stdin).text());
const { tool_name, tool_input = {} } = input;
appendFileSync(`${process.env.CLAUDE_PROJECT_DIR}/.claude/agent-log.jsonl`, JSON.stringify({
time: new Date().toISOString(),
tool: tool_name,
what: tool_input.command ?? tool_input.file_path ?? null,
}) + "\n");Test a hook without Claude by piping in a sample event; both lines print the block message, then 2:
# macOS, Linux, Git Bash
echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | node .claude/hooks/block-dangerous.mjs; echo $?# Windows PowerShell or PowerShell 7
'{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | node .claude/hooks/block-dangerous.mjs; $LASTEXITCODEKeep Claude working until the tests pass (Stop hook)
{
"hooks": {
"Stop": [
{ "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-tests.mjs"] }] }
]
}
}.claude/hooks/stop-tests.mjs:
// Stop: don't let Claude finish while the test suite fails.
import { execSync } from "node:child_process";
const input = JSON.parse(await new Response(process.stdin).text());
if (input.stop_hook_active) process.exit(0); // already sent back once: let it stop
try {
execSync("npm test", { cwd: process.env.CLAUDE_PROJECT_DIR, stdio: "pipe" });
} catch (e) {
const output = `${e.stdout ?? ""}${e.stderr ?? ""}`.slice(-2000);
console.log(JSON.stringify({
decision: "block",
reason: `npm test fails. Fix it before you finish.\n${output}`,
}));
}In both test runs I asked only for a comment in a file; the hook's npm test failed on a bug I had planted, and Claude fixed it before finishing. The stop_hook_active check lets Claude stop on its second try, so a test it can't fix doesn't hold it forever.
Get a desktop notification (Stop and Notification)
One script covers both events: Stop when Claude finishes, Notification when it waits for you.
{
"hooks": {
"Stop": [
{ "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/notify.mjs"] }] }
],
"Notification": [
{ "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/notify.mjs"] }] }
]
}
}.claude/hooks/notify.mjs:
// Stop or Notification hook: a desktop notification, so you can look away while Claude works.
import { execFileSync } from "node:child_process";
const input = JSON.parse(await new Response(process.stdin).text());
const title = input.hook_event_name === "Stop" ? "Claude Code finished" : "Claude Code needs you";
const firstLine = (input.last_assistant_message ?? "").split("\n").find((l) => l.trim()) ?? "";
const body = (input.message ?? firstLine).slice(0, 150) || "Your turn.";
if (process.platform === "darwin") {
execFileSync("osascript", ["-e", "on run argv", "-e",
"display notification (item 2 of argv) with title (item 1 of argv)", "-e", "end run", title, body]);
} else if (process.platform === "linux") {
execFileSync("notify-send", [title, body]);
} else {
// Windows PowerShell 5.1 (powershell.exe): PowerShell 7 can't load the toast types.
const ps = `
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
$text = $xml.GetElementsByTagName("text")
$text.Item(0).AppendChild($xml.CreateTextNode($env:HOOK_TITLE)) > $null
$text.Item(1).AppendChild($xml.CreateTextNode($env:HOOK_BODY)) > $null
$app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($xml))`;
execFileSync("powershell.exe", ["-NoProfile", "-Command", ps],
{ env: { ...process.env, HOOK_TITLE: title, HOOK_BODY: body }, stdio: "ignore" });
}On Windows it has to be powershell.exe (5.1), because PowerShell 7 fails with "Unable to find type". The toast borrows Windows PowerShell's registered app ID, and the text travels in environment variables, so quotes in Claude's reply can't break the command.
Add context when a session starts
{
"hooks": {
"SessionStart": [
{ "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/session-context.mjs"] }] }
]
}
}.claude/hooks/session-context.mjs:
// SessionStart: put a fact into Claude's context before the first prompt.
await new Response(process.stdin).text();
const text = "The deploy freeze runs until Friday 18:00. Only hotfixes ship before then.";
console.log(JSON.stringify({
hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text },
}));Asked whether it could ship a feature release today, Claude said no in both runs and named the hook as its source. Swap in something live, such as the last CI result, phrased as a fact: the reference warns that text framed as system commands can trip Claude's prompt-injection defences.
Claude Code hooks vs skills
Claude chooses to load a skill when your request matches its description, while Claude Code runs a hook on every matching event. In my Claude Code skills test, a skill with a vague name and description loaded on only 5 of 15 matching requests; a hook has no such step to fail.
| Feature | Hook | Skill |
|---|---|---|
| Who decides it runs | Claude Code, on every matching event | Claude, from the name and description, or you with /skill-name |
| What it is | A command, URL, MCP tool, prompt or agent | Markdown instructions and optional scripts |
| Use it for | Rules that must always hold: blocks, formatting, logs | Procedures that need judgement: reviews, releases |
A skill can also declare hooks in its frontmatter, and those run only after the skill is invoked.
Why isn't my Claude Code hook firing?
Check these in order. I've hit the first two myself.
- The matcher misses the tool. Matchers are case-sensitive, Windows needs
Bash|PowerShell, and a baremcp__memory"matches no tool" (usemcp__memory__.*). - It's the wrong event.
PostToolUseskips failed and blocked calls, andPermissionRequestfires only when Claude Code is about to ask you, which is rare in bypass mode. - The script path is wrong. A hook that can't start is a non-blocking error, so the call runs anyway, unless you set
"onFailure": "block"(Claude Code 2.1.295 or later). - The hook exits 1. Only exit 2 blocks.
- Claude Code ignores your JSON.
permissionDecisionbelongs insidehookSpecificOutput, and anything your shell profile echoes first turns the JSON into plain text. A JSON validation message means a field broke the schema; build the output withJSON.stringifyorjq. - The folder isn't trusted. Interactive sessions hold back every settings-file hook, your own included, until you accept the workspace trust dialog.
- Hooks are switched off by
"disableAllHooks": trueor an organisation policy that allows only managed hooks.
To see what ran, start Claude Code with claude --debug-file hooks.log and search for Hooks:, which gives lines such as PreToolUse:Bash [...] finished with status 2 (98ms).
The hooks I run every day
My own agent repo has four:
- A
Stophook shows a Windows toast with a chime when a turn ran 60 seconds or more, with the first line of Claude's reply as the text. AUserPromptSubmithook records when the turn started. - A
PermissionRequesthook. Some of Claude Code's own checks still ask in bypass mode, for example before anrmon a variable that might be empty, so my hook gives me 10 seconds to click and then answers allow in bypass mode, deny otherwise. - A
PreToolUsehook on the Agent tool refuses any sub-agent call that reads an image unless it runs on Haiku. SessionStartandUserPromptSubmithooks add due reminders to Claude's context, each new one once.
The rest of that agent is in how to build a personal AI assistant with Claude Code. Hooks, skills and agents for a team's own rules are part of my AI agent consulting.
Next
Related
AI Agents · · 9 min read
Claude Code skills: how they work, and when Claude uses one by itself
How Claude Code skills work, where SKILL.md goes and why one won't trigger, with a 108-run test of skill names, descriptions and manual-only skills.
AI Agents · · 14 min read
Claude Code on Windows: install it, fix 'claude' is not recognized, and use it with no coding
Install Claude Code on Windows with one PowerShell command, fix 'claude' is not recognized with two PATH lines, sign in, and run two tasks with no coding.
Claude Code consultant: AI agents, MCP servers and RAG
Claude Code and AI agent consultant: I scope, build and test agents that work with your tools and data, using MCP servers, RAG, Claude Code skills and n8n.
Frequently asked questions
Do Claude Code hooks work with --dangerously-skip-permissions?
Yes. All 13 deletes my PreToolUse hook blocked ran with --dangerously-skip-permissions. A hook that exits 2 or returns permissionDecision "deny" blocks the call in every permission mode, and Anthropic's hooks guide says the same.
Do hooks run in headless mode with claude -p?
Yes. All 31 of my test runs used claude -p. In -p mode Claude Code treats the folder as trusted, so hooks committed in a repository's .claude/settings.json run without asking. Read them before you run claude -p on someone else's repo, or pass --settings '{"disableAllHooks": true}' for that run.
What does "PreToolUse:Bash hook error" mean?
Often that a hook blocked the call on purpose. Claude Code labels an exit-2 block as a hook error and puts your stderr after it. If the notice says "Failed with non-blocking status code", the hook crashed or exited with a code other than 0 or 2, and the call went ahead.
Does exit code 1 block a tool call?
No. Exit 1 is a non-blocking error, so the call goes ahead. Exit 2 blocks, and so does exit 0 with a JSON deny. Set onFailure to "block" if a hook that crashes or can't start should stop the call too.
How much do hooks slow Claude Code down?
On my Windows laptop a Node hook added a median 127 ms to each matching tool call when started through the shell, and 93.5 ms in exec form, over 16 calls each. Keep the matcher narrow so the hook runs only where it's needed.
How do I disable Claude Code hooks?
Set "disableAllHooks": true in a settings file, or pass --settings '{"disableAllHooks": true}' for one run. There is no switch for a single hook, so delete its entry instead. Hooks from managed settings keep running unless managed settings turn them off.
Can a Stop hook trap Claude in a loop?
Claude Code overrides a Stop hook after eight blocks in a row with no tool call in between, and CLAUDE_CODE_STOP_HOOK_BLOCK_CAP changes that number. Check the stop_hook_active field in the input as well: it is true when Claude is already continuing because of a Stop hook. In my runs it was false on the first stop and true on the second.
Do I need to restart Claude Code after changing a hook?
Usually not. Claude Code watches the settings files and picks up hook edits in the running session. If /hooks doesn't show the change after a few seconds, restart the session.
Want a second pair of eyes on this?
Book a 15-minute intro call. Bring the problem, and you leave with a concrete next step.