Claude Code hooks tutorial (2026): auto-format, auto-check and block dangerous commands with PreToolUse and PostToolUse
Table of Contents
- Why use hooks?
- Claude Code hook events and the basic structure
- Which settings level to use
- A hook has three layers
- Three tested hooks
- Test 1: PostToolUse runs prettier or black after every edit
- Test 2: PreToolUse blocks rm -rf and git push --force
- Test 3: SessionStart and UserPromptSubmit inject project rules
- Six common mistakes
- How we use it
Claude Code hooks are commands you put in settings.json that Claude Code runs automatically at fixed points in a session. The three you will use most: PostToolUse runs prettier or black right after Claude edits a file, PreToolUse checks a command before it runs and blocks it when your script exits 2, and SessionStart and UserPromptSubmit put project rules into Claude's context.
Everything marked "tested" below we ran on November 8, 2026, on a Windows 10 machine (Git Bash, Claude Code 2.1.285). The rest follows the official Claude Code hooks documentation, and we say so where it applies. The docs describe a newer release than 2.1.285 (they mention 2.1.309), so items marked as following the docs were not each verified on 2.1.285; check claude --version against the docs for your own setup. The tests ran in a fresh empty folder with claude -p --setting-sources project, which loads only that folder's settings, so no real project was touched. If you haven't installed Claude Code yet, start with our hands-on Claude Code tutorial.
Why use hooks?
Claude Code hooks are for things that must happen every time, where you don't want to rely on Claude remembering. You can write "run prettier after editing" in CLAUDE.md and Claude will usually do it, but nothing guarantees it. The official docs define hooks as user-defined shell commands that run at specific points in Claude Code's lifecycle, so that certain actions always happen instead of being left to the model.
That gives a clean split: rules and explanations go in CLAUDE.md, actions that must happen go in a hook. Formatting, blocking dangerous commands, logging every command and checking a post before it goes out are all good hook jobs.
Claude Code hook events and the basic structure
Claude Code has more than 30 hook events. These eight cover most of what you need at the start; PreToolUse, UserPromptSubmit and Stop can block an action, PostToolUse cannot:
| Event | When it fires | Can it block? |
|---|---|---|
SessionStart |
When a session begins or resumes | No; stdout goes into context |
UserPromptSubmit |
After you submit a prompt, before Claude processes it | Yes; a blocked prompt never reaches Claude |
PreToolUse |
Before a tool call executes | Yes; blocks that tool call |
PermissionRequest |
When a tool call needs a permission decision | Decides through JSON, ignores exit 2 |
PostToolUse |
After a tool call succeeds | No; the tool already ran |
Notification |
When Claude Code sends a notification | No |
Stop |
When Claude finishes responding | Yes; Claude keeps working |
SessionEnd |
When a session ends | No |
The "can it block" column comes from the official exit code 2 table.
Which settings level to use
Claude Code hooks live in the hooks object of a settings.json file at the user, project or local level; the level decides who gets them, and hooks from all three levels merge:
| Location | Scope | Shareable |
|---|---|---|
~/.claude/settings.json |
All your projects | No, local to your machine |
.claude/settings.json |
One project | Yes, can be committed |
.claude/settings.local.json |
One project | No, just for you |
Managed organization settings, plugins, and skill or subagent frontmatter can carry hooks too; this post doesn't cover them.
A hook has three layers
Every Claude Code hook nests three levels: the event (such as PreToolUse), a matcher (such as "only the Bash tool"), and a handler (the command to run). When the event fires, Claude Code sends JSON to your command on stdin with fields like session_id, cwd and hook_event_name, plus tool_name and tool_input on tool events. Your command answers with its exit code:
- exit 0: no objection. On
PreToolUsethis is not an approval; the call still goes through the normal permission flow. - exit 2: block. Whatever you wrote to stderr is the reason, fed back to Claude or shown to you depending on the event.
- any other code: on most events, a non-blocking error, and the action goes ahead.
Three tested hooks
The three most common uses of Claude Code hooks are formatting after edits, blocking dangerous commands and injecting project rules, and we tested all three on Claude Code 2.1.285. All three sit in one .claude/settings.json, and the scripts are written in Node because this Windows machine doesn't have jq, which the official examples use.
Test 1: PostToolUse runs prettier or black after every edit
A PostToolUse hook with an Edit|Write matcher runs every time Claude finishes an Edit or Write. The settings:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/format.js\"", "timeout": 60 }
]
}
]
}
}
format.js reads tool_input.file_path from stdin, runs prettier on .js, .ts and similar files, and black on .py:
const { execSync } = require("child_process");
let raw = "";
process.stdin.on("data", (c) => (raw += c));
process.stdin.on("end", () => {
const file = JSON.parse(raw).tool_input?.file_path || "";
let cmd = "";
if (/\.(js|ts|jsx|tsx|json|css|md)$/.test(file)) cmd = `npx --yes prettier@3 --write "${file}"`;
else if (/\.py$/.test(file)) cmd = `black -q "${file}"`;
if (!cmd) process.exit(0);
try {
execSync(cmd, { stdio: ["ignore", "ignore", "pipe"] });
process.exit(0);
} catch (e) {
process.stderr.write(`Format failed: ${file}\n${e.stderr || e.message}`);
process.exit(2); // exit 2 on PostToolUse: the file is already changed, so hand the error back to Claude
}
});
For the test we asked Claude for single quotes, no semicolons, and add(a,b,c=0) without spaces. Claude's Edit did exactly that, and after the hook ran the files read:
const bye = (name) => {
return "bye " + name;
};
def add(a, b, c=0):
return a + b + c
A successful hook shows nothing in the conversation, as the official docs describe. What was interesting is that Claude noticed anyway. It reported that a hook, probably a formatter, had changed both files after its edits, tried restoring its version once, saw it reformatted again, and stopped to explain instead of looping. In this run, when the format hook and the prompt disagreed, the hook's formatting is what stayed.
Test 2: PreToolUse blocks rm -rf and git push --force
A PreToolUse hook with a Bash matcher can inspect every shell command before it runs and block it by exiting 2. The settings:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard.js\"" }
]
}
]
}
}
guard.js:
let raw = "";
process.stdin.on("data", (c) => (raw += c));
process.stdin.on("end", () => {
const cmd = JSON.parse(raw).tool_input?.command || "";
const rules = [
[/\brm\s+-[a-zA-Z]*r[a-zA-Z]*f|\brm\s+-[a-zA-Z]*f[a-zA-Z]*r/, "rm -rf"],
[/\bgit\s+push\b.*(--force\b|--force-with-lease\b|\s-f\b)/, "git push --force"],
];
for (const [re, name] of rules) {
if (re.test(cmd)) {
process.stderr.write(`Blocked: ${name} is not allowed in this project. Ask the user to run it in their own terminal.\n`);
process.exit(2);
}
}
process.exit(0);
});
Before wiring it up, we followed the official advice and piped sample JSON in with echo: rm -rf build and git push -f returned 2, ls -la returned 0. Then we asked Claude to run rm -rf build and git push --force origin master. The tool results Claude received (tested; our script printed its message in Chinese, translated here):
PreToolUse:Bash hook error: [node "$CLAUDE_PROJECT_DIR/.claude/hooks/guard.js"]: Blocked: rm -rf is not allowed in this project. Ask the user to run it in their own terminal.
PreToolUse:Bash hook error: [node "$CLAUDE_PROJECT_DIR/.claude/hooks/guard.js"]: Blocked: git push --force is not allowed in this project. Ask the user to run it in their own terminal.
The build folder was still there, and Claude reported that the hook blocked both commands before they ran. The official docs add that a deny from a hook holds even in bypassPermissions mode.
To be honest about the limits: string matching doesn't catch every spelling. When we piped in rm -r -f build, guard.js returned 0 and let it through. A hook is good at catching the usual slips. A permission deny rule, such as Bash(rm *) under permissions.deny, adds another layer, but the official docs say such a rule also stops only the form Claude usually writes, not /bin/rm -rf build/ or bash -c 'rm -rf build/', so it is not a security boundary. For limits that don't depend on the command text, the docs point to sandboxing.
Test 3: SessionStart and UserPromptSubmit inject project rules
On exit 0, stdout from SessionStart and UserPromptSubmit goes into Claude's context, which makes them the place for "what's true about this project right now." The settings:
{
"hooks": {
"SessionStart": [
{
"matcher": "startup",
"hooks": [
{ "type": "command", "command": "echo 'Project rule: this repo uses pnpm, not npm. Run pnpm test before committing.'" }
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/ctx.js\"" }
]
}
]
}
}
ctx.js reads the current branch on every prompt and passes it in through the JSON additionalContext field:
const { execSync } = require("child_process");
const branch = execSync("git branch --show-current").toString().trim();
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext: `The current branch is ${branch}. This repo does not deploy to production before Friday.`,
},
}));
We told Claude not to use any tools and to answer which package manager the repo uses and whether there are deploy restrictions. It answered pnpm, and said there is one, no production deploys before Friday, citing the UserPromptSubmit hook (tested; our run used the same text in Chinese). The official docs recommend phrasing injected text as plain statements ("This repo uses pnpm") rather than system-style commands, which Claude may treat as a prompt injection.
Six common mistakes
A misconfigured Claude Code hook rarely errors out; it just quietly does nothing. We reproduced four of these six.
1. Wrong matcher case (tested). The official docs state that matchers are case-sensitive. We changed "Bash" to "bash" and asked Claude to run rm -rf build again. The hook never fired, build was deleted, and the debug log had no PreToolUse entry at all. Also, per the official docs, events like UserPromptSubmit and Stop don't support matchers, and a matcher on them is silently ignored.
2. Script not executable, or Windows paths (official docs plus tested). On macOS and Linux, run chmod +x on hook scripts first. For "command not found," the docs recommend absolute paths or $CLAUDE_PROJECT_DIR, wrapped in double quotes in shell form. On Windows, hooks run in Git Bash by default and in PowerShell only when Git Bash is missing. In our test, Windows passed file_path as a backslash path; the official protect-files example converts backslashes to forward slashes before matching for the same reason.
3. Exiting 1 to block (tested). This is the dangerous one. We changed guard.js from exit(2) to exit(1). The debug log recorded status code 1, but the command ran, build was deleted, and Claude saw no message. The official docs warn about this directly: exit 1 is the usual Unix failure code, but in a hook it is a non-blocking error. To block, always exit 2.
4. JSON fields at the wrong level (tested). additionalContext and permissionDecision (the latter per the official docs) both belong inside hookSpecificOutput. We moved additionalContext to the top level, and Claude answered that it didn't know of any deploy restriction, with no error in the conversation. Only the debug log said Hook JSON output had unrecognized keys (ignored): additionalContext. Also, output that doesn't start with { is read as plain text, which is what an unconditional echo in your shell profile does to a hook.
5. Misreading settings levels (official docs). Hooks merge across levels: user, project and local hooks all run, and none replaces another. disableAllHooks, on the other hand, follows settings precedence, so a project's false overrides a true in your user settings. One more thing to watch: in an interactive session, hooks wait until you trust the folder, but with claude -p the folder is always treated as trusted, so hooks in a cloned repository run right away. Read an unfamiliar repo's .claude/ settings before running -p on it.
6. Slow hooks (tested plus official docs). Test 1's debug log shows Slow PostToolUse hooks: 7769ms for Edit; the first npx --yes prettier@3 has to download the package. Timed separately, npx --yes prettier@3 took about 2.6 to 2.8 seconds per run, while prettier installed in the project and run with node directly took about 0.3 seconds. The documented default timeouts are 10 minutes for command hooks and 30 seconds for UserPromptSubmit, and a PreToolUse hook that times out does not block the call, so keep guard hooks fast. To block on a timeout or failure, the docs offer "onFailure": "block", which needs Claude Code 2.1.295 or later; our 2.1.285 doesn't have it yet.
When you can't tell whether a hook ran, type /hooks to check it's listed under the right event, or start with claude --debug and read the actual exit codes and output in the debug log.
How we use it
Claude Code hook matchers can target MCP tools: MCP tools are named mcp__server__tool, so once you've connected an MCP server you can run your own check right before Claude calls a specific tool. For connecting servers, see last week's guide to connecting MCP servers to Claude Code.
We tried a pre-publish check with our own MindThread MCP (tested): the matcher was mcp__mindthread__publish|mcp__mindthread__schedule_text, and the script exited 2 when the text contained a phrase meaning "guaranteed profit." When Claude called publish, it got back a block message saying the post contained a banned phrase and should be rewritten, and the request stopped before it reached the server. We ran this without an API key, so nothing could have been posted anyway.
Hooks govern what Claude does. If you also write your own MCP server or system prompt, system prompts and tool descriptions can go to our open-source UltraProbe for a static check: it matches the text you paste, calls no model and does not scan the MCP server itself.
FAQ
Which settings file do Claude Code hooks go in?
It depends on who should get them. Hooks for you in every project go in ~/.claude/settings.json. Hooks the whole team should get go in the project's .claude/settings.json, committed to the repository. Hooks only for you in one project go in .claude/settings.local.json. Hooks from all three levels merge and run together rather than replacing each other. Edits are normally picked up without a restart; type /hooks to confirm Claude Code loaded them.
Does exit 0 from a PreToolUse hook mean the call is allowed?
No. The official docs say exit 0 means no decision: the tool call still goes through the normal permission flow, so you are prompted where you normally would be. To block, exit 2 and write the reason to stderr. To skip the permission prompt, exit 0 and print JSON with permissionDecision set to allow, and deny rules from your settings still apply. In the other direction, a deny from a hook holds even in bypassPermissions mode.
Do Claude Code hooks work on Windows?
Yes. According to the official docs, hook commands on Windows run in Git Bash by default and fall back to PowerShell when Git Bash isn't installed; you can also set "shell": "powershell" on a single hook. We tested on Windows 10 under Git Bash with hook scripts written in Node instead of jq, and all three hooks ran. One thing to handle: on Windows, tool_input.file_path arrives as a backslash path, so normalize it before matching paths.
How are hooks different from CLAUDE.md, and when should I use each?
CLAUDE.md is guidance Claude reads and usually follows, with no guarantee it acts on it every time. A hook is a command Claude Code always runs at a fixed point, with no model deciding. The official docs recommend CLAUDE.md for project conventions that never change, and hooks for actions that must happen every time (formatting, blocking, logging) or for dynamic information a script has to fetch, such as the current branch or CI results.