← Back to Guides · AUTOMATION
20 Claude Code Hooks Examples That Actually Ship in Production (2026)
Short answer: the highest-ROI Claude Code hooks are the ones that either save you a manual step every single turn (auto-format on PostToolUse) or stop an unrecoverable mistake before it happens (PreToolUse exit-code-2 blocks on rm -rf, sudo, force-push, and .env edits). Below are 20 ranked by that ROI, plus the pattern most 2026 lists skip: "async": true hooks, which let you log, scan, or track cost in the background without adding latency to every tool call, since they don't hold up the turn waiting for an exit code.
Two of our earlier posts already cover this ground from different angles — 15 Claude Code Hooks With Copy-Paste Configs catalogs six categories including idle notifications and usage tracking, and Hooks: Advisory vs Deterministic explains why a hook beats a CLAUDE.md rule for anything safety-critical. This one is narrower: it ranks by real ROI instead of listing alphabetically by event, and it's the only one of the three that covers async hooks and gives the full per-event JSON schema for tool_input so you can write your own instead of only copy-pasting ours.
Why most "best hooks" lists repeat the same 5 configs
Open five "Claude Code hooks examples" posts and you'll see the same rm -rf guard and the same Prettier-on-save snippet, reordered. That's not laziness — those two really are the highest-value hooks for most repos. But it means the lists stop being useful past config #5, right where the harder questions start: which hooks are worth the latency they add to every tool call, which ones should run in the background instead, and what the actual JSON shape on stdin looks like if you want to write a hook none of these posts covered. That's the gap this post fills.
ROI tier 1: the one hook you should add today
1. Auto-format on PostToolUse
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs -r npx prettier --write --ignore-unknown" }
]
}
]
}
}
This is the single highest-ROI hook in any Claude Code setup because it fires on every file edit, forever, and removes an entire category of back-and-forth ("can you run prettier on that") from every session. If you add exactly one hook from this post, add this one.
2. Import sorting alongside formatting
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.ts|*.tsx|*.js|*.jsx) npx organize-imports-cli \"$f\" 2>/dev/null;; esac" }
]
}
]
}
}
Cheap to run, and like #1, it's invisible once it's wired in — you stop noticing import order in diffs at all.
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 fires when a sibling test file already exists, so it stays fast instead of running the whole suite on every edit.
ROI tier 2: safety gates that prevent unrecoverable mistakes
These are lower-frequency than tier 1 — most turns never trip them — but each one prevents something you can't git revert your way out of. All four rely on PreToolUse exiting status 2, the only exit code that stops the tool call before it runs (see the mechanics section below).
4. Block rm -rf on root, home, or wildcard paths
{
"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 unscoped sudo
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.command' | grep -qE '^\\s*sudo\\b' && { echo 'Blocked: sudo requires manual run' >&2; exit 2; } || exit 0" }
]
}
]
}
}
A solo founder's repo rarely needs an agent running sudo unattended — this forces you to run anything privileged yourself, by hand, after reading what it does.
6. Block force-push to main/master
{
"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" }
]
}
]
}
}
7. Block edits to committed .env files
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.env|*.env.*) git ls-files --error-unmatch \"$f\" >/dev/null 2>&1 && { echo 'Blocked: .env file is tracked in git' >&2; exit 2; } || exit 0;; *) exit 0;; esac" }
]
}
]
}
}
Checks git ls-files rather than just the filename, so it only blocks when the .env file is actually tracked — a gitignored local .env is fine to edit, a committed one is the mistake.
8. Secret-pattern scan before any commit
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '^git commit' && git diff --cached | grep -qE '(sk-[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)' && { echo 'Blocked: possible secret in staged diff' >&2; exit 2; } || exit 0" }
]
}
]
}
}
Scans the actual staged diff, not the working tree, so it catches secrets right before the commit that would ship them — the point at which blocking still costs nothing.
ROI tier 3: async hooks for logging and cost tracking (2026)
Every hook above runs synchronously — Claude Code waits for the process to exit before the tool call or the turn continues. That's correct for a gate, but wasteful for a hook that only logs or records something. Set "async": true on a hook entry and Claude Code fires it without blocking: the tool call proceeds immediately, and the hook's own exit code is no longer able to block anything (an async hook can't gate — only log, notify, or record). Use it for anything where "eventually written" is fine and "the turn waited 400ms for a jq + curl round trip" is not.
9. Async usage/cost log per tool call
{
"hooks": {
"PostToolUse": [
{
"matcher": ".*",
"async": true,
"hooks": [
{ "type": "command", "command": "jq -c '{ts: now, tool: .tool_name}' >> ~/.claude/usage.jsonl" }
]
}
]
}
}
10. Async bash command history with timestamps
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"async": true,
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.command' | xargs -I{} echo \"$(date -u +%FT%TZ) {}\" >> ~/.claude/bash-history.log" }
]
}
]
}
}
11. Async Slack ping on long-running commands
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"async": true,
"hooks": [
{ "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE 'npm run build|docker build|terraform apply' && curl -s -X POST -H 'Content-type: application/json' --data '{\"text\":\"Claude Code is starting a long-running command\"}' \"$SLACK_WEBHOOK_URL\" >/dev/null"
}
]
}
]
}
}
Fires the webhook off-thread — the build or deploy starts immediately rather than waiting on the Slack API to respond. Note the tradeoff: this entry also can't use exit 2 to block the build, since async hooks give up blocking rights by design. If you need both a heads-up notification and the ability to block, split it into two hook entries — one synchronous PreToolUse gate and one async: true logger — rather than trying to get both from one.
ROI tier 4: PR and session guardrails
12. 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" }
]
}
]
}
}
13. Block gh pr create without a filled-in body
{
"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" }
]
}
]
}
}
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. 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\"'" }
]
}
]
}
}
16. Session-end diff summary
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{ "type": "command", "command": "git diff --stat HEAD >> ~/.claude/session-summaries.log 2>/dev/null" }
]
}
]
}
}
17. Block reading SSH keys or PEM files into the transcript
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Read",
"hooks": [
{ "type": "command", "command": "f=$(jq -r '.tool_input.command // .tool_input.file_path // \"\"'); echo \"$f\" | grep -qE '\\.pem$|id_rsa$|id_ed25519$' && { echo 'Blocked: refuses to read private key material' >&2; exit 2; } || exit 0" }
]
}
]
}
}
18. Lint-on-save with a hard 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" }
]
}
]
}
}
19. Block npm install of a package not already in package.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '^npm (install|i) [a-zA-Z@]' && { echo 'Blocked: confirm new dependency with the user first' >&2; exit 2; } || exit 0" }
]
}
]
}
}
Catches an agent reaching for a new dependency mid-task without a human sign-off — npm install with no package name (a plain install from package.json) still passes through.
20. Async heads-up when context usage crosses a threshold
{
"hooks": {
"PostToolUse": [
{
"matcher": ".*",
"async": true,
"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\" >> ~/.claude/alerts.log; exit 0" }
]
}
]
}
}
The tool_input schema per event, so you can write your own
Every PreToolUse/PostToolUse hook above is grepping or jq-parsing one shape of JSON on stdin. The fields that actually show up:
| Event | Key fields on stdin | Can block with exit 2? |
|---|---|---|
PreToolUse | tool_name, tool_input (e.g. .command for Bash, .file_path/.content for Write, .file_path/.old_string/.new_string for Edit) | Yes — the only event that can |
PostToolUse | tool_name, tool_input, plus the tool's tool_response/result | No — action already happened; exit 2 just stops the turn and surfaces stderr |
Notification | Session metadata only, no tool_input | No |
Stop | Session metadata only | No |
SessionEnd | Session metadata only | No |
If you're writing a new hook that isn't on this list, start by piping stdin to tee /tmp/hook-debug.json once, inspecting the real shape for your Claude Code version, and only then writing the grep/jq logic — the fields above are stable but exact nesting has shifted across releases, and trusting a blog post's schema over your own install is the safer habit either way.
Windows/WSL caveat: which hooks need Unix tools
Every command above assumes jq, grep -E, and a POSIX shell. On native Windows, .claude/settings.json hook commands still run through whatever shell Claude Code invokes, but jq/grep/xargs aren't installed by default — install them via winget install jqlang.jq and use Git Bash or WSL as the shell, or rewrite the parsing in PowerShell (ConvertFrom-Json instead of jq, Select-String instead of grep -E). The notification hooks (#15) also need a platform swap: osascript is macOS-only — use notify-send on Linux or powershell -Command "[System.Windows.Forms.MessageBox]::Show(...)" / a toast library on Windows. If your team is split across OSes, test every hook on each platform before relying on it as a safety gate — a hook that silently fails to run (wrong shell, missing binary) blocks nothing, and PreToolUse won't warn you that the gate itself never fired.
Full copy-paste hooks.json for a solo SaaS repo
A reasonable starting set — tier 1 formatting, the four tier-2 safety gates, and async logging, without every lower-ROI entry above:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs -r npx prettier --write --ignore-unknown" }
]
},
{
"matcher": ".*",
"async": true,
"hooks": [
{ "type": "command", "command": "jq -c '{ts: now, tool: .tool_name}' >> ~/.claude/usage.jsonl" }
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.command' | grep -qE 'rm\\s+-rf\\s+(/|\\*|~)|^\\s*sudo\\b' && { echo 'Blocked: destructive or privileged command' >&2; exit 2; } || exit 0" }
]
},
{
"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" }
]
},
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.env|*.env.*) git ls-files --error-unmatch \"$f\" >/dev/null 2>&1 && { echo 'Blocked: .env file is tracked in git' >&2; exit 2; } || exit 0;; *) exit 0;; esac" }
]
}
]
}
}
How AgenticKit's 34 agents ship with pre-wired hooks
Writing and testing 20 of these by hand, then re-testing them on Windows and macOS, is most of a weekend. AgenticKit's security-auditor and devops-engineer agents come with the tier-2 safety gates and the tier-4 commit guardrails pre-wired into the hooks it installs, and the hooks builder tool generates the JSON for any config above, including the async: true variants — pick the event, matcher, and sync/async, and it outputs the snippet to paste into .claude/settings.json.
FAQ
What's the single highest-ROI Claude Code hook? Auto-format on PostToolUse (#1 above) — it fires on every edit, costs almost nothing to run, and removes a whole category of manual cleanup from every session. The safety gates (tier 2) matter more per-incident, but they fire far less often.
What does "async": true actually change? The hook runs without Claude Code waiting for it to exit, so it can't delay the tool call or the turn — and it gives up the ability to block with exit 2, since by the time it would exit, the action it might have blocked has already happened. Use it for logging, metrics, and notifications; never for a safety gate.
Can an async hook still see the full tool_input? Yes — the stdin payload is identical whether the hook is sync or async. The only difference is whether Claude Code blocks on its exit code.
Why do my hooks work on macOS but silently do nothing on Windows? Most hook one-liners here assume jq, grep -E, and xargs are on PATH. Native Windows doesn't ship any of them. Install jq and run hooks through Git Bash or WSL, or rewrite the logic in PowerShell — see the Windows/WSL section above.
Should every rule in my CLAUDE.md become a hook? No — reserve hooks for the handful of actions where "the model usually gets it right" isn't good enough: deleting files, privileged commands, pushing to a protected branch, committing secrets. Most conventions still belong in CLAUDE.md or a skill; see Claude Code Hooks in Production: Advisory vs Deterministic for where that line sits.
Is there a shorter version organized by what I'm trying to automate, not by ROI rank? Yes — the hooks cookbook groups 12 hooks into four jobs (formatting, safety, notifications, CI) with one merged settings.json template at the end, if you'd rather jump straight to a category than read a ranked list.
How is this different from your other two hooks posts? The 7-hook post covers the destructive-command and secrets categories in more depth. The 15-hook post adds idle notifications and usage tracking and leads with exit-code mechanics. This one ranks all of it by ROI, adds async hooks and the four tier-2 safety gates (sudo, tracked .env edits, staged-diff secret scanning, SSH-key reads) that neither of the other two covers, and gives the full tool_input schema table so you can write hooks beyond this list.
Related Tools & Agents
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 →