15 Best Claude Code Hook Examples (Copy-Paste Ready) in 2026
Real Claude Code hooks from production repos: auto-format on save, bash safety guards, auto-test after edit, and cost tracking. Copy-paste examples.
Book a Free Strategy Call
Skip the read: talk to the ManasFlow team in 30 min.
Free strategy call. We map your AI engineering team, you keep the notes.
The most useful Claude Code hook examples: auto-format on save (PostToolUse running Prettier or Black), block dangerous bash (PreToolUse that exits non-zero on rm -rf and force-push), auto-test after edit, a wildcard tool-call logger, and an auto secret scan that stops API keys before they hit disk. Every entry below is a paste-ready JSON block for .claude/settings.json, and all 15 are free.
Why hooks matter: Claude Code changed shape in 2025. By 2026 most serious teams use it as an orchestration runtime whose reliability depends on the hooks wrapping it. Hooks are the deterministic layer underneath a probabilistic agent: shell commands that fire on specific lifecycle events, gate dangerous behavior, and bolt the model into your real workflow. The "hook examples" on the open web are usually either trivial (one echo line) or unsafe (no exit-code gating, no cost ceiling). What teams actually need is production-tested patterns: matchers tuned to real tool calls, commands that exit cleanly, and JSON that drops in without a rewrite.
This guide collects the 15 best Claude Code hook examples for 2026. Each entry shows the hook event, what triggers it, what it does, the exact JSON to paste, and the trade-offs you should know before shipping it to your team. If you want a deeper map of the hook system itself, read our companion guide on the best Claude Code hooks. If you want hooks built and operated for you, that is what our Claude Code agency team does.
Best Claude Code hooks: a brief overview
- Auto-format on save: Best for code consistency: runs Prettier or Black after every Edit.
- Block dangerous bash: Best for safety: exits non-zero on rm -rf, sudo, force-push.
- Long-task notifier: Best for async work: macOS notification when Claude is idle for input.
- Auto-test after edit: Best for TDD: runs the matching test file the moment a source file changes.
- Tool-call logger: Best for observability: writes every PostToolUse event to JSONL.
- Auto-commit on Stop: Best for solo builders: snapshots a WIP commit at the end of each turn.
- Lint-on-save: Best for catching errors early: runs ESLint or Ruff after each Edit.
- Auto secret scan: Best for security: blocks Edits that introduce sk-, AKIA, or BEGIN PRIVATE KEY.
- Cost tracker: Best for budget control: appends per-session token spend to a CSV on Stop.
- Auto-link issue IDs: Best for ticket hygiene: rewrites commit messages to include the branch issue ID.
- PR description generator: Best for review velocity: drafts a PR body from the session transcript.
- Custom statusline: Best for context: shows model, branch, cost, and token usage in the CLI footer.
- Sub-agent ROI tracker: Best for parallel teams: logs duration + tokens of every SubagentStop.
- Slack ping on completion: Best for handoffs: posts to a channel when a long task ends.
- Auto-add to TODO file: Best for memory: captures every "TODO:" comment Claude writes into a backlog.
1. Auto-format on save, best for code consistency
The single highest-ROI hook in any Claude Code setup. The moment Claude edits or writes a file, Prettier (JS/TS), Black (Python), or gofmt (Go) reformats it in place. You stop seeing diff noise from inconsistent spacing, and the model learns the project's style implicitly because every file it reads is already formatted.
Hook event
- PostToolUse: fires after the tool succeeds, before the next model turn.
Key features
- Triggers only on Edit and Write (not Read or Bash).
- Reads the modified file path from $CLAUDE_TOOL_INPUT_file_path.
- Exits 0 silently on success; non-zero output appears in transcript.
Best for
- Teams with mixed contributors and a strict formatter config.
- Monorepos where each package has its own formatter.
- Anyone tired of post-commit "format" PRs.
Pricing
- Free. Uses your existing formatter binary.
Pros
- Zero diff noise across PRs.
- Works with any language-specific formatter swap.
- No latency cost; runs in milliseconds.
Cons
- Silent failures if the formatter binary is missing.
- Can mask real syntax errors if || true swallows them; drop it in CI.
Free weekly brief
Steal our production automations
The exact n8n flows, Claude Code setups, and prompts we ship for clients, broken down step by step. No spam, unsubscribe anytime.
2. Block dangerous bash, best for safety
The hook that earns its keep the first time someone tries rm -rf / in a Claude session. A PreToolUse hook on Bash inspects $CLAUDE_TOOL_INPUT_command and exits non-zero on a blocklist of patterns. Claude sees the non-zero exit and refuses to execute. No prompt injection bypasses this: it runs in your shell, not the model's context.
Hook event
- PreToolUse: fires before the tool executes, can veto it.
Key features
- Pattern matches on rm -rf, sudo, git push --force, chmod 777, curl ... | sh.
- Exit code 2 cancels the tool call and feeds reason back to Claude.
- Configurable allowlist per-project via env var.
Best for
- Any team running Claude with --dangerously-skip-permissions.
- CI runners and sandboxed agents.
- Solo devs who do not want to babysit every Bash call.
Pricing
- Free.
Pros
- Deterministic: runs every time, no model judgment involved.
- Patterns are auditable in git.
- Cheap to extend with new blocklist entries.
Cons
- False positives on legitimate rm -rf node_modules; keep an allowlist.
- Grep-based matching can be fooled by creative quoting; for high-stakes envs, parse properly.
3. Long-task notifier, best for async work
Claude Code emits a Notification event when it is waiting on user input or has been idle for a stretch. Wire that to osascript (macOS), notify-send (Linux), or a Pushover/ntfy webhook and you can walk away from a long agent run and get pinged the moment it stalls.
Hook event
- Notification: fires when Claude needs attention.
Key features
- Triggers on idle, permission requests, and Plan-mode prompts.
- Receives $CLAUDE_NOTIFICATION_message with context.
- Cross-platform with a one-line adapter.
Best for
- Long-running refactors and multi-hour migrations.
- Remote work where you switch contexts often.
- Teams running Claude on a remote VM with web access.
Pricing
- Free.
Pros
- Reclaims hours of context-switch overhead.
- Works with any notification backend.
- No tokens consumed.
Cons
- macOS-specific without an adapter.
- Easy to over-notify; tune which Notification messages matter.
4. Auto-test after edit, best for TDD
Tight feedback loops are what make agentic coding viable. After every Edit or Write to src/foo.ts, run the matching tests/foo.test.ts. The test output is fed back to Claude as the next signal, so it self-corrects without you intervening.
Hook event
- PostToolUse: fires after Edit/Write completes.
Key features
- Maps src/x.ts to tests/x.test.ts via a small shell snippet.
- Streams test output back through stdout.
- Optional: only triggers if the edited file is under src/.
Best for
- TDD-heavy codebases.
- Library packages with deterministic unit tests.
- Anyone using Vitest, Jest, or Pytest.
Pricing
- Free.
Pros
- Catches regressions inside the same turn.
- Lets Claude fix its own breakage automatically.
- Encourages real test discipline.
Cons
- Slow if your test suite is heavy; scope it to the matching file.
- Flaky tests will derail otherwise-good sessions.
5. Tool-call logger, best for observability
You cannot improve what you do not measure. A wildcard PostToolUse hook that appends {tool, input, ts} to a JSONL file gives you the raw material to answer: which tools does Claude actually use? Where does it loop? Which sub-agents are worth their tokens?
Hook event
- PostToolUse with "matcher": "*": fires after every tool call.
Key features
- Append-only JSONL, cheap to parse later with jq.
- Captures tool name, file path, command, and timestamp.
- Zero impact on session latency.
Best for
- Platform teams running Claude across many engineers.
- Anyone debugging "why did Claude do that?"
- Building usage dashboards downstream.
Pricing
- Free.
Pros
- Gives you honest analytics on agent behavior.
- Pairs well with Claude Code skills usage tracking.
- Replayable for incident review.
Cons
- File grows fast; rotate it weekly.
- Sensitive paths/commands end up in the log; protect the file.
6. Auto-commit on Stop, best for solo builders
Claude finished a turn. Before you forget, snapshot the state. A Stop hook that runs git add -A && git commit -m "wip: claude turn" gives you a reflexive checkpoint. If the next turn goes sideways, git reset returns you to known-good.
Hook event
- Stop: fires when the agent stops (turn complete or user interrupt).
Key features
- Commits everything in the working tree.
- Skips silently if there is nothing to commit.
- Tag commits with [skip ci] to avoid burning CI minutes.
Best for
- Solo developers iterating fast.
- Branch-per-feature workflows.
- Anyone who has ever lost work to an over-eager refactor.
Pricing
- Free.
Pros
- Frictionless rollback.
- Visible history of what Claude actually did.
- Pairs well with git rebase -i to squash later.
Cons
- Pollutes history if you forget to squash before merge.
- --no-verify bypasses pre-commit hooks; only use on personal branches.
7. Lint-on-save, best for catching errors early
Formatting handles style; linting handles bugs. A PostToolUse hook running ESLint, Ruff, or cargo clippy on the edited file surfaces unused vars, missing awaits, and type mismatches the moment Claude writes them. The non-zero exit feeds back into the next turn.
Hook event
- PostToolUse on Edit/Write.
Key features
- Runs language-appropriate linter per file extension.
- Outputs errors via stdout so Claude sees them.
- Optional --fix to auto-correct mechanical issues.
Best for
- TypeScript and Python codebases.
- Teams with strict lint rules in CI.
- Anyone tired of "missing await" bugs.
Pricing
- Free.
Pros
- Catches bugs Claude would otherwise ship.
- Auto-fix reduces back-and-forth.
- Works alongside the formatter hook.
Cons
- Strict configs can flood the transcript.
- Slow linters (full-program TypeScript) should be moved to CI instead.
8. Auto secret scan, best for security
Models leak secrets sometimes: pasted env vars, accidentally inlined API keys, JWTs that should have been env-loaded. A PreToolUse hook on Edit/Write that scans the new content for high-confidence secret patterns can hard-block the write before the file ever touches disk.
Hook event
- PreToolUse on Edit/Write: vetoes the tool call.
Key features
- Patterns for sk-, AKIA, ghp_, BEGIN PRIVATE KEY, JWT structure.
Ready to transform your business?
Let’s turn your next automation opportunity into a system that works.
Book a Free Strategy Call