cd /news/ai-agents/claude-code-hooks-a-practical-guide-… · home › topics › ai-agents › article
[ARTICLE · art-141362] src=gethrbr.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Claude Code hooks: a practical guide with examples

Anthropic's Claude Code hooks, documented in the hooks guide and reference as of Claude Code 2.1.280 on September 23, 2026, run commands deterministically at more than thirty session events, and a PreToolUse hook can block a tool call outright by exiting with code 2. Hooks are configured under a `hooks` key in settings files such as `.claude/settings.json`, where matchers like `Edit|Write` pair with commands, and their location determines scope from a single project to an entire organization via managed policy settings. Unlike advisory `CLAUDE.md` instructions, hooks always run, which is why teams convert ignored rules into hooks.

by read6 min views13 publishedSep 23, 2026
Claude Code hooks: a practical guide with examples
Image: Gethrbr (auto-discovered)

Blog

Published: September 23, 2026

Claude Code hooks are commands that run at fixed points in a session: before a tool runs, after a file is edited, when a prompt is submitted, when Claude stops. Unlike a line in CLAUDE.md, a hook is not advice. It always runs, and a PreToolUse hook can block the action outright by exiting with code 2.

Checked against the hooks guide and reference on 2026-09-23 (Claude Code 2.1.280). The event list has grown to more than thirty; the handful below are the ones most teams use.

What are Claude Code hooks? #

Anthropic's best practices put it in one line: unlike CLAUDE.md instructions, which are advisory, hooks are deterministic and guarantee the action happens. A rule asks the model. A hook does not ask anyone. That is why the answer to “Claude keeps ignoring my rule” is so often “make it a hook”, and why the causes behind the ignoring, covered in why Claude ignores CLAUDE.md, do not apply to one.

Which hook events should you know? #

Event Fires Typical use
PreToolUse Before a tool call runs. Can block it Refuse dangerous commands, protect files
PostToolUse After a tool call succeeds Format or lint the file that was just edited
UserPromptSubmit When you submit a prompt, before Claude sees it Add context to the prompt, such as branch state
SessionStart When a session begins, resumes, clears or compacts Load context the session should start with
Stop When Claude finishes responding Run the tests and refuse to stop until they pass
PreCompact / PostCompact Around context compaction Re-inject what must survive a summary
SessionEnd When the session terminates Write logs, clean up
Notification When Claude Code sends a notification Desktop alert when Claude is waiting for you

How do you configure a hook? #

Hooks live in a settings file under a hooks key. Each event takes matchers (a tool name or a regex such as Edit|Write) and the commands to run. This formats every file Claude edits:

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

Where the block goes decides who it applies to:

Location Scope Shared
~/.claude/settings.json All your projects No
.claude/settings.json This project Yes, commit it
.claude/settings.local.json This project No, gitignored
Managed policy settings The whole organization Admin controlled
Plugin, skill or subagent While that is enabled or running Yes, ships with it

Run /hooks inside Claude Code to see everything configured, grouped by event.

How do you block a command with a PreToolUse hook? #

The hook receives the tool call as JSON on stdin. Exit 0 lets it through. Exit 2 blocks it, and what you write to stderr goes back to Claude as the reason, so it can change course. This is the pattern from Anthropic's guide, protecting files:

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

for pattern in ".env" "package-lock.json" ".git/"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done
exit 0

Register it on PreToolUse with the matcher Edit|Write, make it executable, and ask Claude to edit .env to test it. For structured control, exit 0 and print JSON with permissionDecision set to deny, ask or allow. When several hooks answer, the most restrictive wins.

Which commands are worth blocking? #

The ones your agents actually run, not the ones that sound scariest. A guard written from imagination can sit for months without matching anything. The costly commands are often ordinary: rm -r on a source directory, git checkout -- <paths> or git reset --hard throwing away uncommitted work. Read your agents' command history before you decide which guard comes first.

Start a new guard in log-only mode for a week, count what it would have blocked, then switch it to blocking. A guard that fires on legitimate work gets disabled by the second person it annoys.

Can a hook add context for Claude? #

Yes. On UserPromptSubmit, return JSON with hookSpecificOutput.additionalContext and the text is added to Claude's context for that prompt. The guide's example adds the branch and a deploy freeze. Put the field inside hookSpecificOutput; at the top level it is silently ignored. SessionStart with the compact matcher is the documented way to re-inject what must survive a compaction.

This is the part of hooks that is easiest to overdo. Every line a hook injects is in the prompt, with the same cost and the same context rot as a line in CLAUDE.md. Inject what applies to this prompt, not everything that might.

How do you debug a hook that is not running? #

Press Ctrl+O for the transcript view. A successful hook shows nothing; a block shows its reason; a failing hook shows a hook error notice. For the full picture, start with claude --debug-file /tmp/claude.log and tail the log, or run /debug mid-session. The usual culprits: the script is not executable, jq is missing, the matcher does not match the tool name, or a project setting set disableAllHooks.

Where Harbor fits #

Harbor is itself delivered through hooks. harbor init installs hooks in Claude Code, Codex and Cursor, and they serve each session the team's approved facts that apply to the repo and the task, so the agent starts with the decision from last month's review instead of rediscovering it. What a session learns is written back through review, not straight into the next prompt.

Harbor's guardrails follow the log-first advice above. Each one watches for a destructive command and records every match; nothing is refused until your team promotes a guard to block, after seeing what it would have caught. harbor off s the whole thing for one repo, and harbor doctor checks that the hooks are installed and reaching the agents you think they reach.

Questions #

What are hooks in Claude Code?

Hooks are commands Claude Code runs at fixed points in a session, such as before a tool call, after a file edit, or when Claude stops. Unlike CLAUDE.md instructions, they always run.

How do I block a command in Claude Code?

Add a PreToolUse hook with a matcher such as Bash or Edit|Write. The script reads the tool call as JSON on stdin and exits with code 2 to block it; what it writes to stderr is passed back to Claude as the reason.

Where are Claude Code hooks configured?

In a settings file under a hooks key: ~/.claude/settings.json for all your projects, .claude/settings.json to share with the team, .claude/settings.local.json for yourself, or managed settings for the organization. Run /hooks to see them all.

Can a hook add context to Claude?

Yes. A UserPromptSubmit hook can return JSON with hookSpecificOutput.additionalContext, and that text is added to Claude’s context for the prompt. A SessionStart hook with the compact matcher can re-inject context after compaction.

Why is my Claude Code hook not running?

Common causes are a script that is not executable, a missing jq, a matcher that does not match the tool name, or disableAllHooks set in a settings file. Run Claude Code with --debug-file and read the log to see which hooks matched.

── more in #ai-agents 4 stories · sorted by recency
── more on @anthropic 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/claude-code-hooks-a-…] indexed:0 read:6min 2026-09-23 · —