Claude Code hooks are one of the most powerful features in the AI coding assistant — and one of the least used. A hook is a shell command (or an LLM prompt, a subagent, or an HTTP endpoint) that runs automatically at a specific point in Claude Code’s lifecycle: before a tool executes, after a file is written, when a session starts, when Claude finishes responding. Unlike instructions in your CLAUDE.md file, which Claude might forget halfway through a long session, hooks always execute. That makes them the right tool for formatting, safety guardrails, audit logging, and anything else that has to happen every single time. Every technical claim in this guide is verified against the official Claude Code hooks documentation (code.claude.com, checked 2026-10-05).
How hooks fit into the Claude Code lifecycle
Claude Code fires hook events at fixed points while it works. You don’t need to memorise all of them — the ones you’ll reach for most are these:
| Event | When it fires | Typical use |
|---|---|---|
SessionStart | When a session begins or resumes | Load context, check tooling |
UserPromptSubmit | When you submit a prompt, before Claude processes it | Inject context, block prompts |
PreToolUse | Before a tool call executes. Can block it | Safety guardrails, validation |
PermissionRequest | When a tool call is about to ask you for permission | Auto-approve known patterns |
PostToolUse | After a tool call succeeds | Lint, format, log |
Notification | When Claude Code sends a notification | Desktop alerts |
Stop | When Claude finishes responding | Quality gates, cleanup |
SessionEnd | When a session terminates | Save progress, cleanup |
PreCompact / PostCompact | Before/after context compaction | Preserve important details |
SubagentStop | When a subagent finishes | Verify subagent output |
FileChanged | When a watched file changes on disk | React to specific files |
ConfigChange | When a config file changes during a session | Audit configuration changes |
The full reference lists around 30 events, including newer ones like PostToolBatch, WorktreeCreate, MessageDisplay, PreModelSwitch, and MCP-related Elicitation events. Start with the table above; you can explore the rest once the basics feel natural.
Setting up your first hook
There are two ways to configure hooks. The easiest is typing /hooks in a Claude Code session — it opens an interactive menu where you browse configured hooks grouped by event. The explicit way is editing the settings JSON directly.
Where you put the hook decides who sees it and where it runs:
| Location | Scope | Shareable? |
|---|---|---|
~/.claude/settings.json | All your projects | No — local to your machine |
.claude/settings.json | Single project | Yes — commit it to the repo |
.claude/settings.local.json | Single project | No — gitignored, personal tweaks |
Plugin hooks/hooks.json | Whenever the plugin is enabled | Yes — bundled with the plugin |
| Skill or subagent frontmatter | The rest of the session (skill) or while the subagent runs | Yes |
Claude Code normally picks up settings edits automatically through its file watcher; if it doesn’t, restart the session. And if you ever need to silence everything for debugging, set "disableAllHooks": true in a settings file.
The five hook types
Each hook entry has a type field that decides how it runs. Most hooks you’ll write are "type": "command" — plain shell commands. But four other types exist:
command(default): runs a shell command. Your everyday automation.prompt: sends your prompt plus the hook’s input data to a Claude model for a single-turn evaluation. The model answers{"ok": true}or{"ok": false, "reason": "..."}. Use it when the decision needs judgment, not a fixed rule — for example, “does this plan address all edge cases?” You can pin a cheaper model with themodelfield. Default timeout: 30 seconds.agent: spawns a subagent that can read files, run commands, and reason for up to 50 tool turns (default 60-second timeout) before returning a decision. Use it when verification needs the actual state of the codebase, not just the hook’s input JSON. Note: agent hooks are experimental and may change.http: POSTs the event data to a URL and reads the same JSON response format back from the response body. Header values support$VAR_NAMEinterpolation, but only for variables listed inallowedEnvVars. Useful for a shared audit or policy service across a team. HTTP status codes alone can’t block actions — you still return the decision JSON in the body.mcp_tool: calls a tool on one of your configured MCP servers.
How hooks talk back to Claude Code
When an event fires, Claude Code pipes JSON into your hook script’s stdin. For a PreToolUse hook on a Bash command, the JSON includes fields like hook_event_name, tool_name, tool_input (whose command field holds the shell command), session_id, and cwd. Your script reads that, does its work, and answers through exit codes and stdout:
- Exit 0: no objection. One subtlety: for
PreToolUse, exit 0 does not approve the tool call — the normal permission flow still applies. - Exit 2: blocks the action. Write the reason to stderr — Claude receives it as feedback and can adjust its approach.
- Any other exit code: generally a non-blocking error. But if your stdout parses as valid JSON, Claude Code ignores the exit code and lets the JSON decide the outcome.
Exit codes only let you block or stay silent. For real control, exit 0 and print a JSON object to stdout instead. A PreToolUse hook that denies a call looks like this:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Do not edit .env files — they hold secrets."
}
}
permissionDecision accepts "allow" (skip the interactive permission prompt), "deny", and "ask" (show the prompt as normal), plus "defer" in non-interactive -p mode. PostToolUse and Stop hooks instead use a top-level "decision": "block". And here’s a gotcha the docs call out explicitly: to inject context into Claude’s session, put additionalContext inside hookSpecificOutput — at the top level it is silently ignored.
Two more things worth knowing: when several hooks match the same event, they all run in parallel and the most restrictive decision wins, in the order deny, defer, ask, allow. And hook timeouts vary by type — 10 minutes for command, 30 seconds for prompt, 60 seconds for agent, with a tight 1.5-second shared budget for SessionEnd hooks. You can override per hook with the timeout field in seconds.
7 practical Claude Code hooks examples you can copy
Each example goes in your .claude/settings.json (project) or ~/.claude/settings.json (global). After adding one, type /hooks in a session to confirm it registered.
1. Block edits to .env and other protected files
The classic guardrail. This PreToolUse hook intercepts Read, Edit, and Write calls targeting your secrets:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read|Edit|Write",
"hooks": [
{
"type": "command",
"command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/block-secrets.js"
}
]
}
]
}
}
// .claude/hooks/block-secrets.js
process.stdin.setEncoding("utf8");
let input = "";
process.stdin.on("data", (d) => (input += d));
process.stdin.on("end", () => {
const file = JSON.parse(input).tool_input?.file_path || "";
if (file.includes(".env") || file.includes("secrets")) {
console.error("Blocked: do not read or edit files containing secrets.");
process.exit(2);
}
process.exit(0);
});
$CLAUDE_PROJECT_DIR is a safe way to reference your repo root — the docs recommend it over relative paths, and chmod +x your script or the hook will fail to run. Claude gets the stderr message as feedback, so it can pivot to a safe alternative on its own.
2. Auto-format code after every edit
A PostToolUse hook with an Edit|Write matcher runs your formatter on exactly the file Claude just touched. No more “please run prettier” reminders:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path // empty'); [ -n \"$f\" ] && npx prettier --write \"$f\""
}
]
}
]
}
}
If jq isn’t installed, parse the stdin JSON with Python or Node instead — the docs call this out as one of the most common hook errors.
3. A safety net for destructive Bash commands
Block rm -rf and friends before they execute. This is the pattern the official docs use as their canonical “combine results” example:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "cmd=$(jq -r '.tool_input.command // empty'); case \"$cmd\" in *rm\\ -rf*|*mkfs*|*dd\\ if=*) echo \"Destructive command blocked: $cmd\" >&2; exit 2;; esac"
}
]
}
]
}
}
Want to log every command instead of blocking? Register a second PreToolUse hook on Bash that appends to a log file and exits 0. Both run in parallel, and the deny still wins if either fires.
4. Re-inject context after compaction
When Claude’s context window fills up, compaction summarises the conversation — and can drop details you care about. A SessionStart hook with the compact matcher fires after every compaction, and any plain text your command writes to stdout is added to Claude’s context:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo 'Conventions reminder: use Laravel Pint formatting, never edit migrations after merge, tests run with ./vendor/bin/pest.'"
}
]
}
]
}
}
Swap the echo for anything dynamic — git log --oneline -5 to show recent commits is the docs’ own suggestion. (The other SessionStart matchers — startup, resume, clear, fork — let you vary the context by how the session began.)
5. Desktop notifications when Claude needs you
The Notification event fires when Claude is waiting for your input or permission, so you can stop babysitting the terminal. The matcher selects which notification types to answer — permission_prompt and idle_prompt are the useful ones:
{
"hooks": {
"Notification": [
{
"matcher": "permission_prompt|idle_prompt",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Needs your input'"
}
]
}
]
}
}
That’s the Linux version — you need libnotify-bin installed (Debian/Ubuntu), and it won’t work in headless SSH sessions with no notification daemon. On macOS use osascript -e 'display notification ...', on Windows a PowerShell command. Leave the matcher empty to fire on every notification type.
6. Auto-approve plan mode exit
PermissionRequest hooks fire when Claude Code is about to show you a permission dialog. This one auto-approves ExitPlanMode — the tool Claude calls when it finishes presenting a plan — so you’re not clicking through every time:
{
"hooks": {
"PermissionRequest": [
{
"matcher": "ExitPlanMode",
"hooks": [
{
"type": "command",
"command": "printf '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"
}
]
}
]
}
}
The docs warn loudly here: keep the matcher narrow. Matching .* or leaving it empty would auto-approve every permission prompt, including file writes and shell commands. Also note that "allow" can’t override real deny rules — hooks in settings files can tighten restrictions but never loosen them past what your permission rules allow.
7. The Stop-hook quality gate: don’t stop until tests pass
A Stop hook fires whenever Claude finishes responding — and if you block it, Claude keeps working. That’s the famous “Ralph Wiggum” pattern: wire your test suite into the Stop event so the session can’t end with broken code:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "bash $CLAUDE_PROJECT_DIR/.claude/hooks/stop-gate.sh"
}
]
}
]
}
}
#!/usr/bin/env bash
# If this hook already continued the session, don't loop forever.
active=$(jq -r '.stop_hook_active // false')
[ "$active" = "true" ] && exit 0
npm test >/dev/null 2>&1 || {
echo "Tests are failing. Run the suite, fix the failures, then stop." >&2
exit 2
}
Note that Stop takes no matcher — it always fires on every occurrence. And Claude Code has a safety valve: after a Stop hook blocks eight consecutive times with no tool call in between, it overrides the hook. That’s what the stop_hook_active check is for; if your workflow legitimately needs more iterations, raise the cap with CLAUDE_CODE_STOP_HOOK_BLOCK_CAP.
Matchers and the if field: making hooks precise
A matcher is a case-sensitive regex (pipe alternation works, so "Edit|Write" covers both tools) matched against the tool name. Without one, the hook fires on every occurrence of the event — expensive and noisy. Some events, including Stop, PostToolBatch, CwdChanged, and UserPromptSubmit, don’t support matchers at all.
For tool events (PreToolUse, PostToolUse, and friends) there’s also an if field that uses permission-rule syntax to filter by tool name and arguments together — for example "if": "Bash(git *)" runs the hook only for git commands, not every Bash call. The matcher narrows which hook group fires; if stops the hook process from spawning at all when it doesn’t match. Use both, and never rely on if for a hard allow/deny — the docs say it’s best-effort; the permission system is the enforcement point.
Troubleshooting hooks
/hooksshows nothing: validate your JSON — trailing commas and comments are not allowed. Confirm the file is in the right place (.claude/settings.jsonfor project hooks,~/.claude/settings.jsonfor global ones). The file watcher usually picks changes up; restart the session if it hasn’t.- JSON output has no effect: two usual suspects. First, something else wrote to stdout before your JSON (a shell profile
echois the classic) — Claude Code only parses stdout as JSON if it starts with{. Second, a field at the wrong level:permissionDecisionbelongs insidehookSpecificOutput, not at the top level. Misplaced fields are ignored silently; run withclaude --debugto see them flagged. - Hook blocks too many times in a row: the Stop-hook block cap (eight consecutive blocks) or the session-end timeout. Add the
stop_hook_activeearly-exit, and keepSessionEndhooks under their 1.5-second budget.
Hooks vs CLAUDE.md vs skills: when to use which
This is the question people actually get stuck on, so here’s the rule of thumb that holds up in practice:
- Use hooks when the action must happen deterministically: formatting, secret-blocking, audit logs, notifications, quality gates. If forgetting it would be a bug, make it a hook.
- Use CLAUDE.md for project context and conventions Claude should know — things like architecture notes, preferred libraries, and coding style. It’s advisory; hooks are enforcement.
- Use skills for reusable task recipes Claude chooses to run — multi-step procedures it should follow when a situation arises.
- Use prompt/agent hooks for the in-between: decisions that need judgment (prompt) or actual codebase inspection (agent) but must still happen automatically.
A word on security
Hooks run with the same machine reach as Claude Code itself — they can read, write, and execute anything you can. Treat installing someone else’s hooks the way you’d treat installing an npm package: trusted source or skip. A few concrete rules:
- Keep matchers narrow. Auto-approving
.*is the equivalent of running everything as root. PreToolUsehooks fire before permission checks in every permission mode — includingbypassPermissionsand--dangerously-skip-permissions. A hook that returns"deny"blocks the tool even then, which makes hooks a genuine policy enforcement point for teams.- Hook feedback is treated like a human instruction, not a system notification. A compromised hook could steer the agent mid-session — another reason to audit scripts before you install them.
Further Reading & References
- Automate actions with hooks — official Claude Code docs (the reference this guide was verified against)
- Claude Code Hooks: A Practical Guide to Workflow Automation — DataCamp
- Claude Code hook configs and hook-type table — kevinreber/claude-code-configs
- 3 Claude Code Hooks That Save Hours — Bash Safety Net, Focus Alert Chime, Auto-Research Loop — gist



