How to Use Claude Code Hooks for Safer Team Development

Learn how to configure Claude Code PreToolUse and PostToolUse hooks with practical settings.json examples. Block risky commands, automate code audits, protect secrets, and troubleshoot hook failures.

How to Use Claude Code Hooks for Safer Team Development

Claude Code hooks let teams run local or remote handlers around tool calls—most usefully PreToolUse (before a tool runs) and PostToolUse (after a successful tool call). This guide focuses on those two tool-level events: copy-paste settings.json examples, Exit 0 / 1 / 2 behavior, onFailure fail-closed settings, a Bash block case, and a redacted audit-log case. Official reference: Claude Code hooks docs (verified November 24, 2026). Pair with the Claude Code CLI install guide and the enterprise coding-agent security checklist when you roll hooks into a managed fleet.

Using the product from: Claude Code Hooks: Stop Risky Tool Calls Before They Run

What Are Claude Code Hooks?

Hooks are event handlers Claude Code runs at lifecycle points. When an event fires and a matcher matches, Claude Code sends JSON context to your handler (stdin for command hooks). Handlers can inspect the payload, take action, and optionally return a decision.

The Hooks system includes many events (SessionStart, UserPromptSubmit, Stop, PostToolBatch, and more). This guide focuses on two particularly useful tool-level events: PreToolUse and PostToolUse—not the entire event catalog.

Infographic: How PreToolUse and PostToolUse differ from permission deny and ask rules

PreToolUse vs PostToolUse

PreToolUse fires before a tool call executes and can block it. Use it to inspect tool name, arguments, and target paths, then deny destructive Bash or out-of-scope Write/Edit attempts.

PostToolUse fires after a tool call succeeds. Use it for audit logging and redaction checks. PostToolUse cannot block or undo a tool that already ran—exit code 2 on PostToolUse only surfaces stderr to Claude; the file change or shell command is already done.

EventWhenCan block?Best use
PreToolUseBefore tool executionYesAdmission control / deny dangerous calls
PostToolUseAfter successful tool callNo — tool already ranAudit metadata, secret redaction checks
Infographic: How to configure settings.json hooks with a realistic matcher

Hooks vs Permission Deny and Ask

Permission deny/ask/allow rules in settings (permissions docs) are declarative: they match tool patterns without custom code. Hooks run your scripts or HTTP handlers with the full tool JSON, so you can encode team policy that rules alone cannot express.

Use both: keep broad deny/ask rules for categories that must never be scripted away, and use PreToolUse hooks for dynamic checks (dangerous Bash patterns, path allowlists, ticket IDs).

Infographic: PreToolUse + PostToolUse architecture for tool-call control

How to Configure Hooks in settings.json

Place hooks under the top-level <code>hooks</code> object in project or managed settings. Matchers filter tool names (for example <code>Bash</code> or <code>Write|Edit</code>). The sample below is illustrative—validate keys against the current hooks schema and use absolute or <code>${‘{‘}CLAUDE_PROJECT_DIR{‘}’}</code> paths so CI and laptops resolve the same scripts.

<pre>{ “hooks”: { “PreToolUse”: [ { “matcher”: “Bash”, “hooks”: [ { “type”: “command”, “command”: “${CLAUDE_PROJECT_DIR}/.claude/hooks/check-bash.sh”, “timeout”: 10, “onFailure”: “block” } ] } ], “PostToolUse”: [ { “matcher”: “Write|Edit”, “hooks”: [ { “type”: “command”, “command”: “${CLAUDE_PROJECT_DIR}/.claude/hooks/log-metadata.sh” } ] } ] } }</pre>

Bash is checked before execution with <code>onFailure: “block”</code> so a missing or crashing script fails closed (requires Claude Code v2.1.295+ for command/http hooks). Write/Edit success is logged afterward for audit—not for rollback.

Claude Code Hook Exit Codes: Allow, Block, and Failure Behavior

Do not assume every non-zero exit blocks a tool. Use exit code 2 to block a PreToolUse action. Configure <code>onFailure: “block”</code> when hook failures or timeouts must fail closed.

ResultDefault behavior
Exit 0Success; continue, or apply JSON decision fields if printed
Exit 2Block on events that support blocking (e.g. PreToolUse)
Exit 1 / other non-0/2Usually a non-blocking error; action may still proceed
Timeout (command/http)Often no decision; PreToolUse may still run unless onFailure=block

PostToolUse cannot be your safety gate

If Claude already deleted a file, a PostToolUse logger that exits 2 cannot restore it. Put irreversible controls on PreToolUse (or permission deny rules), and treat PostToolUse as after-the-fact telemetry.

How to Block Dangerous Bash Commands

Example: a user asks Claude Code to run <code>rm -rf production/</code>. PreToolUse fires; your matcher selects Bash; the script reads stdin JSON (<code>tool_name</code>, <code>tool_input.command</code>) and denies the call.

<pre>{ “hooks”: { “PreToolUse”: [ { “matcher”: “Bash”, “hooks”: [ { “type”: “command”, “if”: “Bash(rm *)”, “command”: “${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh”, “args”: [] } ] } ] } }</pre>

<pre>#!/bin/bash # .claude/hooks/block-rm.sh COMMAND=$(jq -r ‘.tool_input.command // empty’) if echo “$COMMAND” | grep -q ‘rm -rf’; then jq -n ‘{ hookSpecificOutput: { hookEventName: “PreToolUse”, permissionDecision: “deny”, permissionDecisionReason: “Destructive command blocked by hook” } }’ exit 0 fi exit 0 </pre>

Expected result: the tool call is blocked and Claude sees the deny reason (via JSON decision or Exit 2 + stderr, depending on how you signal). Safer commands that do not match <code>rm -rf</code> exit 0 with no decision and continue through normal permission flow. Install <code>jq</code> for this sample pattern; full variants live in official hooks docs.

How to Create Secure Audit Logs

After a successful Write/Edit, PostToolUse can append redacted metadata—not file bodies or environment secrets. Example illustrative record (not a live production log):

<pre>{ “event”: “PostToolUse”, “tool”: “Write”, “file”: “src/payment.js”, “timestamp”: “2026-11-24T10:30:00Z”, “result”: “success” }</pre>

Never log API keys, tokens, <code>.env</code> contents, or full file text. Hash or drop argument fields that may contain secrets; keep the same trust boundary you use for CI logs.

Claude Code Hooks Performance, Timeouts, and Failure Handling

Tune <code>timeout</code> so slow network hooks do not stall sessions. Remember: a timed-out PreToolUse command hook does not block the tool by default—set <code>onFailure: “block”</code> if a stalled policy hook must fail closed.

When multiple matcher groups match, expect multiple handlers. Keep matchers explicit (<code>Bash</code>, <code>Write|Edit</code>) instead of matching everything. Verify script paths exist and are executable—wrong paths often surface as exit 127 non-blocking errors unless onFailure blocks.

How to Fix Hooks Not Working

Triage checklist: (1) event name spelled <code>PreToolUse</code>/<code>PostToolUse</code>; (2) matcher matches <code>tool_name</code>; (3) settings layer that wins is the one you edited (project vs user vs managed); (4) script path resolves; (5) watch transcript for hook error notices.

SymptomLikely causeFix
Hook never firesWrong event/matcher or settings file not loadedConfirm /status sources; tighten matcher to exact tool
Wrong tool blockedMatcher too broad (e.g. regex without ^$)Use exact names or anchored patterns
Policy seems on but tools still runExit 1 / timeout / missing script without onFailure=blockUse Exit 2 or JSON deny; set onFailure block
Secrets in logsPostToolUse dumps full stdin/stdoutLog redacted metadata only

How to Deploy Hooks Across a Team

Start local: add project hooks, run a gold dangerous command and a safe command, confirm block vs allow. Then promote the same JSON via managed settings so developers cannot widen matchers locally. Keep scripts in-repo under <code>.claude/hooks/</code> with code review.

Hooks complement—not replace—repository ACLs, branch protection, and sandboxing described in the enterprise security guide.

Research Methodology

This article synthesizes Claude Code hooks, exit-code, and onFailure documentation (verified November 24, 2026). Samples are illustrative; confirm schema and version requirements (including onFailure ≥ v2.1.295) before fleet enforcement.

Ship hooks as admission control plus audit

Use PreToolUse with Exit 2 / JSON deny and onFailure block for dangerous tools; use PostToolUse only for redacted telemetry. Keep copy-paste settings.json in reviewable project files before managed rollout.

FAQ

01

What are Claude Code hooks?

Lifecycle handlers that run when events fire. For tool safety, PreToolUse can block calls; PostToolUse observes successful calls.
02

How do I configure Claude Code hooks in settings.json?

Add a top-level hooks object with PreToolUse/PostToolUse arrays, each containing matcher groups and command/http handlers. See the JSON example in this guide and the official hooks reference.
03

Which exit code blocks a PreToolUse tool call?

Exit code 2 blocks on PreToolUse. Do not assume every non-zero exit blocks. Use onFailure: block so failures/timeouts fail closed.
04

Can PostToolUse stop a dangerous command?

No. PostToolUse runs after success; it cannot undo completed tools. Block with PreToolUse or permission deny rules.
05

Why is my Claude Code hook not working?

Usually a matcher/settings-layer mismatch, bad script path, or non-blocking exit/timeout. Check transcript hook errors and verify the loaded settings source.