Guide · Hook · ★★★☆☆
Claude Code hooks, with two real examples
Run your own script every time Claude is about to use a tool, or right after. My two examples: a secret scanner that stops API keys from leaving my machine, and Prettier on every file Claude edits.
By Arthur Hsiao · Last updated · 7 min read
What a hook is. A command that Claude Code runs at a fixed moment, such as before a tool call (PreToolUse),
after one (PostToolUse) or when a session starts (SessionStart). Unlike an instruction in CLAUDE.md, a hook
always runs: Claude can't forget it or decide to skip it.
1Know where hooks go
~/.claude/settings.json: runs in every project. Both my hooks live here..claude/settings.jsonin a repo: only that project, and shared with anyone who clones it.
Type /hooks in Claude Code to see which hooks are active.
Claude Code sends every hook a JSON object on stdin: the tool name, its input and the working folder. A Node script reads it in one line:
const input = JSON.parse(fs.readFileSync(0, 'utf8')); // { tool_name, tool_input, cwd, ... }I write hooks in Node, not as one-line shell commands, because they work the same on Windows, Mac and Linux. A shell version needs jq, which Windows doesn't have.
2Example 1: stop secrets before they leave (PreToolUse)
I let Claude hand big reads to Gemini through MCP (setup guide). That means files leave my machine.
I wanted a check that a prompt, or any file it points at with @path, doesn't contain a key, a password or an email address.
This is the real block from my ~/.claude/settings.json (only the user folder is changed). The matcher is a regex on the tool name, so it only fires for Gemini tools:
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__gemini-cli__.*",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["C:/Users/<you>/.claude/hooks/gemini-secret-scan.js"],
"timeout": 30,
"onFailure": "block",
"statusMessage": "Scanning Gemini prompt for sensitive info..."
}
]
}
]
}onFailure: "block" means that if the script crashes, the call is stopped instead of going through unchecked.
3Check what Claude is about to send
The script checks every string in tool_input against a list of patterns:
const CONTENT_RULES = [
['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
['AWS access key', /\bAKIA[0-9A-Z]{16}\b/],
['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{20,})/],
['API key (sk-...)', /\bsk-(ant-)?[A-Za-z0-9_\-]{20,}/],
['email address', /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/],
// ...plus Google, Slack, JWT, passwords and connection strings
];4Answer with allow, ask or deny
If the script prints nothing, the call goes ahead. To stop and ask me first, it prints a decision:
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'ask', // or 'deny' to block outright
permissionDecisionReason: 'Possible sensitive info would be sent to Gemini:\n- ' + hits.join('\n- '),
},
}));The reason names the rule and where it matched, never the value itself. Otherwise the hook would leak the secret into the chat log.
A hook is just a script, so test it without Claude. Pipe it fake input and look at the output:
echo '{"tool_input":{"prompt":"summarise this, key AKIAABCDEFGHIJKLMNOP"},"cwd":"."}' \
| node ~/.claude/hooks/gemini-secret-scan.js
# {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask",
# "permissionDecisionReason":"Possible sensitive info would be sent to Gemini:\n- AWS access key in prompt"}}A clean prompt prints nothing and exits 0. Test both cases before you trust it.
5Example 2: format every file Claude edits (PostToolUse)
PostToolUse fires right after a tool finishes, so it can format the file Claude just wrote. No more "please run Prettier".
The hook calls Prettier for you, so it must run by hand first:
npx prettier --version
If your project has a .prettierrc, Prettier uses it. If not, it uses its defaults. Save this as ~/.claude/hooks/format-on-edit.js:
const fs = require('fs');
const { execFileSync } = require('child_process');
const input = JSON.parse(fs.readFileSync(0, 'utf8')); // { tool_input: { file_path }, cwd, ... }
const file = input.tool_input && input.tool_input.file_path;
if (!file || !fs.existsSync(file)) process.exit(0);
try {
execFileSync('npx', ['prettier', '--write', file], { cwd: input.cwd, stdio: 'ignore', shell: true });
} catch {
// prettier can't format this file type (.md is fine, .png is not): leave it alone
}6Register it on Edit and Write
Add it next to the first hook in settings.json:
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["C:/Users/<you>/.claude/hooks/format-on-edit.js"],
"timeout": 30
}
]
}
]
}Edit|Write means it only runs after Claude edits or creates a file, not after every read or command.
Claude sees the file change after the hook runs, so it reads the formatted version next time.
7Test it on a messy file
Make a file that needs formatting:
// app.js
const a=1;let b =2
function f( x ){return x+a}
if(x){console.log( f(b) )}Then run the hook on it:
echo '{"tool_input":{"file_path":"app.js"},"cwd":"."}' | node ~/.claude/hooks/format-on-edit.jsapp.js is now clean:
const a = 1;
let b = 2;
function f(x) {
return x + a;
}
if (x) {
console.log(f(b));
}A path that isn't a file, or a type Prettier can't format, exits quietly with code 0.
8Let Claude write the next one
You don't have to write a hook yourself. Describe it in plain words and Claude writes both the script and the settings block. These are the prompts I used for the two hooks above:
Add a PreToolUse hook in ~/.claude/settings.json for mcp__gemini-cli__ tools. It runs a Node script that scans the prompt and every @path file for keys, tokens, passwords and emails, and asks me before the call if it finds any. Report the rule and location only, never the matched value.
Add a PostToolUse hook in ~/.claude/settings.json with matcher Edit|Write. It runs a Node script that reads tool_input.file_path from stdin and runs npx prettier --write on that file. Ignore files Prettier can't format. Then test it on a messy file.
Then read the script yourself. A hook runs with your full permissions on every matching call.
Keep hooks fast and narrow. A hook on .* runs before every single tool call, and a slow one makes the whole session feel slow.
Match only the tools you care about, and set a timeout.
Next: package a whole workflow so Claude loads it only when needed, in writing Claude Code skills.
For a ready-made security check that runs on every edit, see security-guidance on my tools page.
Not sure which of the four to use? See skills vs subagents vs hooks vs slash commands.
A hook refuses a command with code. For the everyday yes-or-no prompts and the modes, see Claude Code permissions.