15 Claude Code Hooks That Actually Prevent Mistakes (With Copy-Paste Configs)

By Rakshit Yadav (@yadavrakshit60)•Oct 2026•12 min read

Short answer: Claude Code hooks are shell commands wired to lifecycle events (PreToolUse, PostToolUse, Notification, Stop, SessionEnd, and others) in .claude/settings.json, and a PreToolUse hook can hard-block an action by exiting with status 2. Below are 15 copy-paste configs across six categories — formatting, bash safety, idle notifications, cost tracking, and PR/commit guardrails — plus the exact mechanics of how exit-code blocking works, since most guides to this topic gloss over the part that actually matters: what happens on exit 0 vs. exit 1 vs. exit 2, and which hook events even support blocking.

If you only need the destructive-command and secrets-leak guards, our earlier post has 7 of those with more detail on each. This one is the fuller catalog — it adds the categories that post skips: idle/attention hooks, usage tracking, and commit/PR guardrails — and leads with the exit-code mechanics first, since that's what determines whether any of these 15 actually do what you think they do. For the conceptual question these configs are actually answering — why a CLAUDE.md rule isn't enough on its own — see Claude Code Hooks in Production: The Advisory vs Deterministic Rule Nobody Explains.

What a hook actually is: four handler types

A hook entry in .claude/settings.json has three parts: an event (when it fires), a matcher (a regex filtered against the tool name, for tool-scoped events), and one or more commands to run. The four handler types you'll use across these 15 hooks:

  • PreToolUse — fires before a tool call executes, receives the tool name and its input as JSON on stdin. The only event where exit 2 blocks the action outright.
  • PostToolUse — fires after a tool call completes, receives the input and the result. Good for formatting, linting, and logging; can't prevent the action since it already happened.
  • Notification / Stop — fire on session-level events (Claude is waiting on you, or a turn ends). No tool input to inspect; used for alerts, not gates.
  • SessionEnd — fires once, when the session closes. Used for summaries and cleanup, not per-action checks.

All the JSON below merges into the top-level hooks key of .claude/settings.json. If you already have hooks configured, merge arrays per event rather than overwriting.

Hooks 1-3: auto-format, lint-on-save, auto-test

These three run on PostToolUse after Edit or Write — the file already changed, so the job is to clean it up or verify it, not stop it.

1. Auto-format on save

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs -r npx prettier --write --ignore-unknown" }
        ]
      }
    ]
  }
}

Runs Prettier on exactly the file that was just touched, instead of a pre-commit pass over the whole repo.

2. Lint-on-save with a block on new errors

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.ts|*.tsx) npx eslint \"$f\" --max-warnings=0 || { echo 'Lint failed on '$f >&2; exit 2; };; esac" }
        ]
      }
    ]
  }
}

This one exits 2 on a PostToolUse hook — which doesn't undo the edit (it already happened) but does block the turn from silently continuing, surfacing the lint error back to Claude as the reason so it fixes it before moving on.

3. Auto-run the nearest test file

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "f=$(jq -r '.tool_input.file_path'); t=\"${f%.*}.test.${f##*.}\"; [ -f \"$t\" ] && npx vitest run \"$t\" --reporter=dot" }
        ]
      }
    ]
  }
}

Only runs if a sibling *.test.* file exists for the edited file, so it stays fast and skips files with no tests yet.

Hooks 4-6: bash safety guards

PreToolUse on Bash is the only spot where exit 2 actually prevents something from running — these three are hard gates, not warnings.

4. Block destructive deletes

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.command' | grep -qE 'rm\\s+-rf\\s+(/|\\*|~)' && { echo 'Blocked: destructive rm pattern' >&2; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

5. Block force-push to main

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE 'push .*--force.*\\b(main|master)\\b|push .*\\b(main|master)\\b.*--force' && { echo 'Blocked: force-push to protected branch' >&2; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

6. Block commands that read .env-shaped secrets into the conversation

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.command' | grep -qE 'cat .*\\.env|cat .*\\.pem|cat .*id_rsa' && { echo 'Blocked: command would print secret file contents' >&2; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

Different failure mode than committing a secret (covered in the earlier post) — this one stops the secret from ever landing in the transcript in the first place, which matters if that transcript gets shared or logged.

Hooks 7-9: idle and attention notifications

These fire on session-level events rather than tool calls, so there's no tool_input to inspect — the point is to get your attention, not to gate anything.

7. Desktop notification when Claude is waiting on you

{
  "hooks": {
    "Notification": [
      {
        "hooks": [
          { "type": "command", "command": "osascript -e 'display notification \"Claude is waiting for input\" with title \"Claude Code\"'" }
        ]
      }
    ]
  }
}

macOS-only (osascript); swap for notify-send on Linux or a powershell toast on Windows.

8. Sound alert when a turn finishes

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff 2>/dev/null &" }
        ]
      }
    ]
  }
}

Useful if you tab away mid-task and don't want to poll the terminal — the & keeps the hook from blocking the turn from actually ending.

9. Heads-up before a long-running command

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE 'npm run build|docker build|terraform apply' && osascript -e 'display notification \"Long-running command starting\" with title \"Claude Code\"'; exit 0" }
        ]
      }
    ]
  }
}

Fires the notification and always exits 0 — it's informational, not a gate, so a build or deploy command still runs.

Hooks 10-12: cost and usage tracking

None of these block anything; they log, so you can see where turns or tokens are going without re-reading the transcript.

10. Log every bash command with a timestamp

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.command' | xargs -I{} echo \"$(date -u +%FT%TZ) {}\" >> ~/.claude/bash-history.log" }
        ]
      }
    ]
  }
}

11. Count tool calls per session, warn past a threshold

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": ".*",
        "hooks": [
          { "type": "command", "command": "f=/tmp/claude-tool-count-$$; n=$(( $(cat \"$f\" 2>/dev/null || echo 0) + 1 )); echo \"$n\" > \"$f\"; [ \"$n\" -gt 150 ] && echo \"Heads up: $n tool calls this session\" >&2; exit 0" }
        ]
      }
    ]
  }
}

A rough proxy for runaway loops or an unexpectedly expensive turn — not exact token accounting, but cheap and fast to check.

12. Session-end summary of files touched

{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          { "type": "command", "command": "git diff --stat HEAD >> ~/.claude/session-summaries.log 2>/dev/null" }
        ]
      }
    ]
  }
}

Gives you a running log of what each session actually changed, independent of commit messages.

Hooks 13-15: PR and commit guardrails

13. Block commits when tests are red

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '^git commit' && { npm test --silent || { echo 'Blocked: test suite is failing' >&2; exit 2; }; } || exit 0" }
        ]
      }
    ]
  }
}

Every git commit runs the full suite first; a red suite blocks the commit instead of landing it and finding out later.

14. Require Conventional Commits format

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); if echo \"$cmd\" | grep -qE \"^git commit\"; then msg=$(echo \"$cmd\" | grep -oE \"-m ['\\\"].*['\\\"]\"); echo \"$msg\" | grep -qE \"(feat|fix|chore|docs|refactor|test)(\\(.+\\))?:\" || { echo 'Blocked: commit message must follow Conventional Commits' >&2; exit 2; }; fi; exit 0" }
        ]
      }
    ]
  }
}

15. Block gh pr create without a filled-in description

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '^gh pr create' && ! echo \"$cmd\" | grep -qE -- '--body|--body-file' && { echo 'Blocked: gh pr create needs --body or --body-file' >&2; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

Stops a PR from going out with the CLI's default empty-body placeholder, which is easy to miss when you're moving fast.

Exit code 2: how PreToolUse blocking really works

This is the mechanic every one of the hard-gate hooks above (4, 5, 6, 13, 14, 15) depends on, and it's worth being precise about:

  1. For PreToolUse, Claude Code runs every matching hook command before the tool call executes, piping {"tool_name": "...", "tool_input": {...}} as JSON to the hook's stdin.
  2. If the hook exits 0, the tool call proceeds — nothing changes, even if the hook printed to stdout or stderr.
  3. If the hook exits 2, Claude Code blocks the tool call, does not execute it, and feeds the hook's stderr (not stdout) back into the conversation as the reason the action was blocked — so the model sees it and can propose a different action.
  4. Any other non-zero exit code (1, 127, etc.) is treated as a hook error, not an intentional block — Claude Code surfaces that the hook itself failed, which is a different signal than "this action is disallowed." Always exit explicitly with 0 or 2, not whatever a command happens to return.
  5. For events that don't gate an action — PostToolUse, Notification, Stop, SessionEnd — exit 2 doesn't undo anything that already happened; it mainly stops the turn from proceeding cleanly and surfaces the message, which is still useful (hook 2 uses this) but isn't the same guarantee as a PreToolUse block.

That distinction is why hooks 4-6 and 13-15 are all written as PreToolUse on Bash: it's the one place where "block it" means the command never ran at all, not "ran, but now Claude knows you're upset about it."

AgenticKit ships these pre-configured

Writing and testing 15 of these by hand is most of a Saturday. AgenticKit's security-auditor and devops-engineer agents come with hook templates for the destructive-command, secrets, and commit-guardrail categories pre-wired, and the hooks builder tool generates the JSON for any of the 15 above — pick the event and matcher, get the snippet, paste it into .claude/settings.json. If you're also running Cursor alongside Claude Code, note its hook file is .cursor/hooks.json with a different event vocabulary (beforeShellExecution, afterFileEdit) — the builder generates that format too.

FAQ

Which events can actually block an action, not just warn? Only PreToolUse, by exiting status 2 before the tool call runs. Every other event (PostToolUse, Notification, Stop, SessionEnd) fires after the fact or outside a tool call, so it can log, alert, or nudge, but it can't prevent the underlying action.

What's the difference between exit 1 and exit 2? Exit 2 is the dedicated "block this" signal Claude Code looks for on PreToolUse. Exit 1 (or any other non-zero code) is read as the hook script itself erroring out — a bug in your hook, not an intentional rejection — so don't use set -e carelessly in a hook script if a non-blocking failure could trip it.

Do these hooks slow down every tool call? Every matching PreToolUse or PostToolUse hook adds its own runtime to that tool call, since Claude Code waits for the hook process to exit before continuing. Keep hook commands fast (a grep or a jq parse, not a full test suite) unless you're deliberately gating something slow, like hook 13, and scope matcher narrowly so hooks don't run on calls they don't apply to.

Can a hook see the exact bash command or file contents before it runs? Yes, for PreToolUse — the hook receives tool_input as JSON on stdin, which includes the full command string for Bash calls or the file path and new content for Edit/Write calls. That's what every grep-based hook above is parsing.

Should I write hooks for every rule in my CLAUDE.md? No — a hook is for the handful of actions where "the model usually gets it right" isn't an acceptable bar: deleting files, pushing to a protected branch, committing secrets, shipping a PR with no description. Most conventions belong in a CLAUDE.md or skill instead; see our CLAUDE.md examples post for where that line sits.

Is there a longer, ranked version of this list? Yes — 20 Claude Code Hooks Examples That Actually Ship in Production ranks hooks by ROI instead of category, adds four safety gates this post doesn't cover (sudo, tracked .env edits, staged-diff secret scanning, SSH-key reads), and covers async: true hooks for logging without adding latency to every tool call. If you'd rather jump straight to a recipe by job instead of reading the full event-mechanics breakdown, see the hooks cookbook, which groups 12 hooks into formatting, safety, notification, and CI categories with one merged settings.json template.

Are Claude Code hooks the same format as Cursor hooks? No. Both run a shell command on a lifecycle event, but the config file, event names, and matcher syntax differ — Claude Code uses .claude/settings.json with PreToolUse/PostToolUse/etc.; Cursor uses .cursor/hooks.json with beforeShellExecution/afterFileEdit/etc. Port the intent between the two, not the literal JSON.

When should I reach for an MCP server instead of a hook? When the task needs live data or an action from outside the session — a Stripe subscription lookup, a current database schema — not a deterministic reaction to something that just happened locally. See Claude Code Hooks vs MCP Servers for the full decision table.

Related Tools & Agents

🛠️ Free Tool: hooks-builder🤖 Agent: security-auditor🤖 Agent: devops-engineer🤖 Agent: code-reviewer⚡ Command: /audit⚡ Command: /shipSkill: security-basicsSkill: project-conventions

Build your hooks.json visually

Pick an event and a preset, then download a hooks file instead of hand-writing the JSON.

Open the hooks builder →