It's confusing when Claude follows your CLAUDE.md rule one day and skips it the next. We'll explain what hooks are and when one beats a rule or a skill, then give you working hooks to copy, check and switch off.
๐ฏ Quick Answer
Claude Code hooks are commands that Claude Code runs for you at set moments: before Claude runs a shell command, after it edits a file, when it finishes or needs your approval. A rule in CLAUDE.md is something Claude follows most of the time. A hook runs every time, because Claude Code fires it, whatever the model decides.
Hooks are the fix for chores you're tired of repeating and mistakes you can't afford: format every file Claude touches, ping you when it's waiting, refuse rm -rf and edits to .env. Each is a few lines of JSON in a settings file.
What are Claude Code hooks, and why not just tell Claude in CLAUDE.md?
A hook is your own command, run by Claude Code at a set moment in Claude's work, such as a tool call or the end of a reply. (In programming generally, a hook is any spot where a program runs your code when something happens.) The difference from an instruction is who runs it:
- CLAUDE.md, prompts and skills are context. Claude reads them and usually follows them; Anthropic's docs call CLAUDE.md "context, not enforced configuration."
- Hooks are run by Claude Code itself. Claude can't forget them or talk itself out of them.
Every hook has three parts:
- An event: the moment it fires, such as
PreToolUse(before a tool runs) orStop(when Claude finishes a reply). - A matcher: an optional filter, such as
BashorEdit|Write, so the hook only fires for the tools you care about. - A handler: what runs. Usually a shell command, which receives the event's details as JSON and answers with an exit code.
Exit 0 means carry on. Exit 2 means stop: if the event can be blocked, Claude Code cancels the action, and for a tool call, Claude sees the message your script printed to stderr and can change course.
The rule of thumb: if it must happen every time, make it a hook. If it's advice Claude should weigh, leave it in CLAUDE.md.
Set up your first hook: a notification when Claude finishes or needs you
You add a hook by pasting a block of JSON into a settings file, then checking it with /hooks. All you need is Claude Code, which comes with Claude's paid plans (see pricing). Our install guide sets it up; if you're new, start with the beginner guide.
1. Pick the settings file
| File | Hooks apply to | Shared with your team? |
|---|---|---|
| ~/.claude/settings.json | Every project on your machine | No |
| .claude/settings.json | This project | Yes, commit it |
| .claude/settings.local.json | This project, just you | No |
2. Add the hook
Open ~/.claude/settings.json (create it if it doesn't exist) and add the block below. It sets up two pings on macOS: Stop fires the moment Claude finishes a reply, and Notification with the permission_prompt matcher fires when Claude is waiting for your approval and you haven't typed for about six seconds in the terminal.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude has finished\" with title \"Claude Code\"'"
}
]
}
],
"Notification": [
{
"matcher": "permission_prompt",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs your approval\" with title \"Claude Code\"'"
}
]
}
]
}
}If the file already has a hooks section, add these two events inside it. A ping after every reply too chatty? Swap the Stop block for a second Notification matcher, idle_prompt, which fires once Claude has been done for about 60 seconds and you haven't typed.
On Linux, use notify-send 'Claude Code' 'Claude has finished' as the command, with a matching message for the approval hook. For Windows, Anthropic's hooks guide has a PowerShell version.
3. Check that it works
Type /hooks in Claude Code. It lists your hooks by event; yours should be under Stop and Notification. Then ask Claude something, switch windows, and wait for the banner.
No banner on a Mac? osascript notifications come from Script Editor, which needs permission. Run osascript -e 'display notification "test"' once in Terminal, then allow Script Editor in System Settings > Notifications.
Rather not edit JSON? Ask Claude to "add a hook to my user settings that shows a Mac notification when you finish," then check it with /hooks.
Claude Code hooks examples worth copying
Pick the job:
| Job | Event | Matcher | Put it in |
|---|---|---|---|
| Ping when Claude finishes | Stop | none | User settings |
| Ping when Claude needs approval | Notification | permission_prompt | User settings |
| Format every file Claude edits | PostToolUse | Edit|Write | Project settings |
| Block risky shell commands | PreToolUse | Bash | Project settings |
| Keep Claude's file tools out of .env and package-lock.json | PreToolUse | Edit|Write | Project settings |
| Remind Claude of key rules after compaction | SessionStart | compact | Project settings |
| Keep Claude working until tests pass | Stop | none | Project settings |
If you add several, merge them under one "hooks" key in each file; hooks from different files add together. Examples that read JSON need jq: brew install jq on a Mac, sudo apt-get install jq on Debian or Ubuntu.
Format every file Claude edits
This runs Prettier on each file right after Claude writes or edits it. Add it to .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write --ignore-unknown \"$(jq -r '.tool_input.file_path')\""
}
]
}
]
}
}Swap in your own formatter if you don't use Prettier. When it works, the chat shows nothing; the file is just formatted.
Block risky commands and protected files
Save these two scripts in your project's .claude/hooks/ folder: one for shell commands, one for file edits.
.claude/hooks/block-risky.sh:
#!/bin/bash
# Stops a few destructive shell commands before Claude runs them.
command=$(jq -r '.tool_input.command // empty')
risky='rm -rf|rm -fr|git reset --hard|git push.*(--force| -f)|drop table'
if printf '%s' "$command" | grep -Eiq "$risky"; then
echo "Blocked by a project hook: this command is on the never-run list. Tell the user what you wanted to run and why." >&2
exit 2
fi
exit 0.claude/hooks/protect-files.sh:
#!/bin/bash
# Stops Claude's Edit and Write tools from changing secrets and package-lock.json.
file=$(jq -r '.tool_input.file_path // empty')
case "$file" in
*.env|*.env.*|*package-lock.json|*/.git/*)
echo "Blocked by a project hook: $file is protected. Ask the user before changing it." >&2
exit 2 ;;
esac
exit 0Make them executable with chmod +x .claude/hooks/*.sh, then register both in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-risky.sh" }
]
},
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
]
}
]
}
}Test a script without Claude by piping in sample JSON. This prints the block message, then 2:
echo '{"tool_input":{"command":"git push origin main --force"}}' | .claude/hooks/block-risky.sh; echo $?A blocked command never runs; Claude reads your message as the reason, so write it as an instruction. The block holds in every permission mode, including --dangerously-skip-permissions. A mod you install can still let the command through, unless you log in with a Team or Enterprise plan or your organization manages your settings.
Match the tool to the block:
- A fixed command you never want, such as any
git push: a deny rule needs no script. Add"permissions": { "deny": ["Bash(git push *)"] }to your settings. - A pattern or a check, such as
--forceanywhere in a push: use a hook. - A hard boundary: rules and hooks both judge the text Claude writes, and a command can always be written another way (
rm -r -f). The file hook also misses shell commands that write files. For limits that don't depend on wording, use sandboxing.
Give Claude its key rules back after compaction
When a long session is compacted (summarized to free space), details can get lost. A SessionStart hook with the compact matcher puts a reminder back each time:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo 'Reminder: this project uses npm and Prettier. Run npm test before saying a task is done.'"
}
]
}
]
}
}Swap the echo for git log --oneline -5 to hand Claude your latest commits. Context Claude needs from the start of every session belongs in CLAUDE.md.
Keep Claude working until the tests pass
A Stop hook can send Claude back to work: when this script exits with 2, Claude reads the message and keeps going. Save it as .claude/hooks/tests-must-pass.sh, put your test command in place of npm test, and make it executable with chmod +x:
#!/bin/bash
# .claude/hooks/tests-must-pass.sh: don't finish while tests fail
if ! npm test >/dev/null 2>&1; then
echo "Tests are failing. Fix them before you finish." >&2
exit 2
fi
exit 0{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/tests-must-pass.sh"
}
]
}
]
}
}It runs after every reply, so it suits tests that take seconds. If Claude stops running tools, Claude Code overrides the hook after eight blocks in a row, so the session can't stall. But any tool call resets that count, so failing tests can keep Claude going and using your plan; to cap it, add the stop_hook_active check from the troubleshooting section below.
For a one-off, skip the hook: type /goal all tests pass and Claude keeps working until a model judges the condition met. /goal is a built-in Stop hook that lasts for one session.
Which hook events and types does Claude Code have?
Anthropic's hooks reference lists 33 events. These seven cover every example here:
| Event | Fires | Can it block? | Use it to |
|---|---|---|---|
| SessionStart | When a session starts, resumes or is compacted | No | Add context or load the environment |
| UserPromptSubmit | When you send a prompt, before Claude sees it | Yes | Add context or reject a prompt |
| PreToolUse | Before any tool call | Yes | Block or approve commands and edits |
| PermissionRequest | When Claude Code is about to ask your permission | Yes, with a JSON decision | Auto-approve or deny specific prompts |
| PostToolUse | After a tool call succeeds | No, the tool already ran | Format, lint or log |
| Notification | When Claude Code sends a notification | No | Desktop or Slack alerts |
| Stop | When Claude finishes a reply | Yes | Pings and test gates |
The other 26 cover narrower moments:
- Sessions and prompts:
Setup,SessionEnd,UserPromptExpansion - Tool calls:
PermissionDenied,PostToolUseFailure,PostToolBatch - Replies and errors:
StopFailure,MessageDisplay - Subagents, tasks and agent teams:
SubagentStart,SubagentStop,TaskCreated,TaskCompleted,TeammateIdle - Context and settings:
InstructionsLoaded,PreCompact,PostCompact,ConfigChange - Files and folders:
CwdChanged,DirectoryAdded,FileChanged,WorktreeCreate,WorktreeRemove - Models:
PreModelSwitch,PostModelSwitch - MCP input requests:
Elicitation,ElicitationResult
A hook's handler can be one of five types:
| Type | What runs | Use it when |
|---|---|---|
| command | A shell command or script on your machine | You want a fixed rule or a side effect. This is the default |
| http | A POST of the event's JSON to a URL | A shared service, such as a team audit log, handles the logic |
| mcp_tool | A tool on one of your MCP servers | The logic already lives in an MCP server |
| prompt | One question to a Claude model, which answers yes or no with a reason | The decision needs judgement rather than a rule |
| agent | A subagent that can read files and run tools before it answers | The check depends on the actual state of the code |
Anthropic marks agent hooks experimental and recommends command hooks for production work. Prompt and agent hooks send a request to a Claude model each time they run; command hooks run locally. New to MCP? See our MCP servers guide.
Two other things share the name: Agent SDK hooks are Python or TypeScript functions in an app you build with the Claude Agent SDK, and mod hooks are JavaScript or TypeScript functions inside a Claude Code plugin. If you use Claude Code itself, you want the settings-file hooks above.
Hook or skill: which do you need?
A skill teaches Claude how to do something, and Claude uses it when it judges it relevant or when you type its /name. A hook acts at a set moment, without Claude deciding anything.
| If you want | Use |
|---|---|
| Claude to know your conventions in every session | CLAUDE.md |
| Claude to follow a procedure, such as writing release notes, when it's needed | A skill |
| Something to happen at a set moment, every time | A hook |
| Claude never to use a command or file | A permission deny rule, plus a hook for patterns |
A skill can also carry its own hooks, which switch on once the skill is used and stay on for the session. Our Claude Skills tutorial shows how to build one.
Why isn't my Claude Code hook working?
Start with /hooks. Whether your hook is listed tells you where to look. In a new folder, accept the workspace trust prompt first: in an interactive session, Claude Code holds back hooks until you do.
Not listed:
- The JSON is invalid or in the wrong file. Settings files don't allow trailing commas or comments.
- Claude Code missed the edit. Changes are normally picked up automatically; if not, restart the session.
Listed, but never fires:
- The matcher doesn't match. Matchers are case-sensitive tool names:
Edit|Write, notedit. - It's a notification that hasn't come due. In the terminal,
permission_promptandidle_promptonly fire when you seem to be away.
Fires, but errors or doesn't block:
- Pipe sample JSON into the script, as above, and check the exit code.
- For "command not found", make the script executable and reference it as
"$CLAUDE_PROJECT_DIR"/.claude/hooks/..., and installjqif the error names it. - A hook that should block must exit 2. Exit code 1 lets the action go ahead.
- If a
Stophook won't let Claude stop, have it exit 0 when its input showsstop_hook_activeastrue, which means it has already sent Claude back once.
To see what a hook did, press Ctrl+O for the transcript view, or start Claude Code with claude --debug and read the log in ~/.claude/debug/.
How to turn hooks off
- All hooks: set
"disableAllHooks": truein a settings file. A project file can switch them back on, and hooks your organization sets can only be switched off in its managed settings. - For one run: start with
claude --settings '{"disableAllHooks": true}'. Do this before runningclaude -pon a repository you didn't write: non-interactive runs skip the trust prompt and run the repository's hooks. - One hook: there's no switch. Delete its entry.
Start with the notification hook, then add a project hook whenever "usually" isn't good enough. For more, see our Claude Code tips, or Codex vs Claude Code if you're still choosing.
Frequently Asked Questions
Do Claude Code hooks cost extra, and which plan do I need?
Hooks are a Claude Code feature that you set up in your own settings files, so what matters is which plan includes Claude Code. Claude's Free plan doesn't. Pro, the cheapest individual plan that does, costs $20 a month or $17 a month billed annually, according to Anthropic's pricing page. Max, Ultra, Team and Enterprise include it too, as does an Anthropic Console account. Command hooks run on your own machine, while prompt and agent hooks send a request to a Claude model each time they run.
Can I use Claude Code hooks if I don't code?
Yes. Describe the hook you want in plain words and ask Claude Code to add it to your settings, then type /hooks to check that it's there. The examples in this article can be pasted in, though some need a setup step first, such as installing jq, making a script executable or allowing Mac notifications. Hooks also run in the Claude desktop app and the IDE extensions, not just the terminal.
Can I write Claude Code hooks in Python?
Yes. A command hook can run any program, so point its command at python3 and your script. The script reads the event as JSON from standard input, for example with json.load(sys.stdin), and to block an action it prints a reason to standard error and exits with code 2. Anthropic's claude-code repository on GitHub includes a Python example that checks Bash commands.
What's the difference between Claude Code hooks and Agent SDK hooks?
Claude Code hooks live in settings files and run a command, a URL, an MCP tool or a model check. Agent SDK hooks are Python or TypeScript functions you register in code for an agent you build with the Claude Agent SDK. Both use the same event names, such as PreToolUse, and the same JSON decisions, and an SDK app can also load the hooks in your settings files.
Are Claude Code hooks safe?
They're as safe as the commands in them. A command hook runs with your full user permissions, so it can read, change or delete anything your account can. Read every hook before you add it, including hooks that come with a plugin or a repository you cloned.
Where can I find ready-made Claude Code hooks?
Plugins are the closest thing to a hooks library. A plugin can bundle hooks with skills and MCP servers: type /plugin in Claude Code to browse Anthropic's official marketplace, and a plugin's details list the hooks it adds before you install it. Anthropic's security-guidance plugin, for example, is built on hooks: it checks each edit and reviews the changes when Claude stops. Install it with /plugin install security-guidance@claude-plugins-official.
Advertiser disclosure: some links on this website are affiliate links, meaning No Code MBA may make a commission if you click through and purchase.