Claude Code hooks: how they work and 8 practical examples
What Claude Code hooks are, where to configure them, what they receive and how they block — with copy-paste examples for formatting, guard rails, notifications and tests.
CLAUDE.md asks Claude to do things;
hooks make sure they happen. A hook is a shell command that Claude Code
runs automatically at a fixed moment — before a tool runs, after a file is edited, when
the agent finishes. Format every file it touches, block rm -rf, get a ping
on your phone when it needs you. Here is how hooks work and eight examples you can copy.
1. What are Claude Code hooks
A hook ties a command to an event in the agent's life. Unlike an instruction in a prompt, it does not depend on the model remembering it: the command runs every time, deterministically, with your user's permissions. That makes hooks the right tool for anything that must happen — formatting, checks, guard rails, notifications.
The events you will use most:
| Event | When it fires | Typical use |
|---|---|---|
PreToolUse | before a tool runs | block or allow commands, protect files |
PostToolUse | after a tool succeeds | format, lint, type-check the edited file |
UserPromptSubmit | when you send a prompt | add context, reject prompts with secrets |
Notification | when Claude needs permission or has waited for input | desktop or phone notification |
Stop | when the agent finishes its turn | run tests, notify, insist on more work |
SessionStart | when a session starts or resumes | load the current git state, open issues |
There are many more — around thirty, from SubagentStop and
PreCompact to FileChanged and SessionEnd. The hooks
reference in the Claude Code docs lists them all.
2. Where hooks live and how they are written
Hooks go into a settings file, in a hooks section:
~/.claude/settings.json— for all your projects;.claude/settings.json— for the project, committed and shared with the team;.claude/settings.local.json— for the project, just for you.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh" }
]
}
]
}
}
The matcher picks tools by name. Plain names are matched exactly, and
several can be joined with |: Bash, Edit|Write.
Anything with other characters is read as a regular expression, such as
mcp__github__.*. Leave it out (or use *) to match every
tool. Events that have nothing to do with tools, like
Stop, need no matcher. Type /hooks in Claude Code to see what
is configured.
Keep anything longer than a one-liner in a script under .claude/hooks/ and
make it executable. $CLAUDE_PROJECT_DIR points at the project root, so the
path works whatever directory the agent has cd'd into.
3. What a hook receives and how it answers
The hook gets a JSON object on stdin: the session id, the working
directory, the event name and, for tool events, tool_name and
tool_input. For a shell command it looks roughly like this:
{
"hook_event_name": "PreToolUse",
"cwd": "/home/you/projects/app",
"tool_name": "Bash",
"tool_input": { "command": "npm test" }
}
The hook answers with its exit code:
0— fine, carry on;2— block: inPreToolUsethe tool does not run, and whatever the hook wrote to stderr goes to Claude as the reason, so it can adjust;- anything else — an error that is shown to you, but the work continues.
For finer control a hook can exit 0 and print JSON instead — for example a
PreToolUse hook can answer allow, deny or
ask, or even rewrite the command before it runs. You need jq for most of the examples below.
4. 8 practical Claude Code hook examples
1. Format every file Claude edits (PostToolUse, matcher
Edit|Write) — .claude/hooks/format.sh:
#!/bin/sh
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
*.ts|*.tsx|*.js|*.css) npx prettier --write "$f" ;;
*.py) ruff format "$f" ;;
*.go) gofmt -w "$f" ;;
esac
exit 0
Formatting just the touched file keeps diffs small — running a formatter over the whole project after each edit would reformat files nobody asked to change.
2. Block dangerous shell commands (PreToolUse, matcher
Bash):
#!/bin/sh
cmd=$(jq -r '.tool_input.command // empty')
if echo "$cmd" | grep -Eq 'rm -rf (/|~)|git push (-f|--force)|git reset --hard'; then
echo "Blocked by hook: '$cmd' is not allowed in this project." >&2
exit 2
fi
exit 0
Treat this as a safety net, not a sandbox: a determined agent can phrase a command in a way no regular expression catches. For real isolation, run it on a separate machine.
3. Protect secrets and lock files (PreToolUse, matcher
Edit|Write|Read):
#!/bin/sh
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
*.env|*.env.*|*/secrets/*|*package-lock.json)
echo "Blocked by hook: $f is off limits." >&2
exit 2 ;;
esac
exit 0
4. Type-check after edits and let Claude fix the errors
(PostToolUse, matcher Edit|Write):
#!/bin/sh
out=$(npx tsc --noEmit 2>&1) || { echo "$out" | head -30 >&2; exit 2; }
exit 0
Exit code 2 in PostToolUse cannot undo the edit, but it feeds the errors
back to Claude, which usually fixes them in the next step.
5. Desktop notification when Claude needs you
(Notification):
# macOS
osascript -e 'display notification "Claude Code needs your input" with title "Claude Code"'
# Linux
notify-send "Claude Code" "Claude Code needs your input"
6. Phone notification when Claude finishes (Stop), with
the free ntfy service and its phone app:
curl -s -d "Claude finished in $(basename "$PWD")" ntfy.sh/your-long-random-topic
Anyone who knows a topic name on the public ntfy server can read it, so pick a long
random one and do not put code or file contents in the message. Use the same line in a
Notification hook to hear about permission prompts too.
7. Start every session with the current state
(SessionStart):
#!/bin/sh
echo "Current branch: $(git branch --show-current)"
echo "Uncommitted changes:"
git status --short | head -20
For SessionStart and UserPromptSubmit, what the hook prints
is added to Claude's context — a cheap way to save the first “let me look around”
steps.
8. Do not stop until the tests pass (Stop):
#!/bin/sh
input=$(cat)
# Already continuing because of this hook? Let it stop, or it loops forever.
[ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0
out=$(npm test 2>&1) || { echo "Tests fail, fix them before finishing:" >&2; echo "$out" | tail -30 >&2; exit 2; }
exit 0
Exit code 2 in a Stop hook sends Claude back to work with your message.
stop_hook_active is true when Claude is already continuing
because of a Stop hook — checking it lets a test that cannot be fixed end the turn
instead of going round in circles on your tokens. Claude Code also stops on its own
after eight continuations in a row, but that is eight full turns.
5. Hook security: what to watch out for
- Hooks run with your full user permissions, without asking. A hook
in a cloned repository's
.claude/settings.jsonis code from that repository. In an interactive session Claude Code holds hooks back until you accept the workspace trust dialog for the folder — read.claude/before you accept it in a project you do not know. - Scripts skip that check. With
claude -pthere is no trust dialog and the folder counts as trusted, so a repository's hooks run straight away. Before scripting over someone else's code, review its settings or run with--settings '{"disableAllHooks": true}'. - Quote variables (
"$f", not$f); file names with spaces or odd characters come straight from the model. Skip paths with..in them. - Keep hooks fast. They run on every matching event. A command
hook may run up to 10 minutes by default — far too long to wait after every edit —
so set a shorter
timeout(in seconds) on anything that could hang.
6. Hook not running? Troubleshooting
- Check
/hooks— it lists every configured hook and the file it came from. If yours is missing, the JSON is in the wrong file or does not parse. - Folder not trusted: in an interactive session no hooks run until you accept the workspace trust dialog.
- Matcher case: tool names are case-sensitive —
Bash, notbash. - Not executable:
chmod +x .claude/hooks/*.sh. - Run it by hand with a sample input:
echo '{"tool_input":{"command":"rm -rf /"}}' | .claude/hooks/guard.sh; echo $? - Debug log:
claude --debug-file ./debug.txtwrites which hooks ran and what they returned to a file. (claude --debugdoes not print to the terminal; it writes to~/.claude/debug/.) disableAllHooksset totruein any settings file turns them all off.
7. Hooks and approvals from your phone
A PreToolUse hook can do more than say yes or no on its own — it can wait
for a person. That is exactly how coden works: it runs
Claude Code on your computer and adds one PreToolUse hook that sees every
tool call, lets the harmless ones through and holds the rest until you decide on your
phone. You get a notification when
the Agent wants to run a command, with Allow and Deny right in it, and another one when
it finishes.
Your own hooks keep working alongside: coden starts the ordinary Claude Code in your
project, so formatting, type checks and Stop hooks from .claude/settings.json
still run. The one thing it does not let a project do is switch its approval hook off.
If what you were building with examples 5 and 6 is really “let me steer the agent when
I am away from the desk”, try coden instead — see
ways to use Claude Code from
your phone.
Do you see it differently? Write to support@coden-app.com.