DEV Community

Roei
Roei

Posted on Originally published at gethrbr.com AI-assisted

Claude Code hooks: a practical guide with examples

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-10-05 (Claude Code 2.1.289). The event list has grown to 33; the handful below are the ones most teams use. Three things changed in the fortnight before that date: sessions now start in auto mode, mods arrived and can overrule a hook, and Cursor runs Claude Code's hooks too. Each has a section below.

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"
          }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

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. Since 2.1.286 it opens on one list grouped by event, each hook labelled with where it comes from; select one to see the full command and the file that defines it. The menu is read-only, so to change a hook you edit that file.

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
# .claude/hooks/protect-files.sh
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
Enter fullscreen mode Exit fullscreen mode

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.

A hook and your permission rules stack. A hook that exits 2 blocks the call even when an allow rule would let it through, and a deny rule still blocks a call the hook allowed. Since 2.1.288, if Claude Code cannot match a PreToolUse hook or cannot serialize the tool's input for it, the call is blocked rather than waved through. That fix is narrow: a guard that exits 1, or times out, still lets the call run, so a guard should exit 2 on anything it does not understand.

Do hooks still run in auto mode?

Yes, and they matter more there. Since 2.1.284, published 2026-09-28, interactive sessions start in auto mode when no permission mode is configured, on every plan and provider. Most tool calls are then approved by a classifier instead of by you. PreToolUse hooks still run before that: a hook that denies, or exits 2, blocks the call, and a hook that returns ask forces a prompt the classifier cannot approve on its own.

Auto mode adds one event of its own. PermissionDenied fires when the classifier refuses a call, which is the place to log what it stopped. And a PostToolUse hook can return classifierContext, a note the classifier reads before it judges the next action, since it never sees tool results themselves. Details are in the permission modes docs.

Mods vs hooks: can a mod overrule a hook?

Yes. Mods arrived in 2.1.287 on 2026-10-01. A mod is a plugin whose handlers are JavaScript or TypeScript functions running inside Claude Code rather than shell commands, so it can draw panes, add commands and step into a tool call. The mods docs now call the hooks on this page "settings hooks" to tell them apart.

The part that matters for a guard: per the permissions docs, a mod that handles tool.check answers after your rules and your PreToolUse hooks, and its answer can replace theirs.

Your control Can an installed mod approve past it?
A PreToolUse hook that blocks Yes, unless the hook is in managed settings
An ask rule Yes
The auto mode classifier Yes. A call the mod approves is not checked
A deny rule Not on a machine with managed settings or a Team or Enterprise sign-in, by default. Anywhere else, yes

So a guard the whole team relies on belongs in managed settings, and a mod deserves the review you would give any dependency that runs with your permissions. If a shell script does the job, a settings hook is still the simpler choice.

Do Codex and Cursor have hooks too?

Both do, and both borrowed Claude Code's shape, so one guard script can serve all three.

Cursor OpenAI Codex
Where .cursor/hooks.json, ~/.cursor/hooks.json, and enterprise paths .codex/hooks.json or [hooks] in .codex/config.toml, and the same under ~/.codex
Reads Claude Code's hooks Yes, by default, from .claude/settings.json, .claude/settings.local.json and ~/.claude/settings.json No
Blocking Exit 2, or Claude Code's permissionDecision JSON. Any other non-zero exit lets the action through Exit 2, or permissionDecision: "deny". Matching hooks start at once, so one cannot stop another
Before a hook runs Nothing extra You review and trust each hook in /hooks; a changed hook is skipped until trusted again. Project hooks load only in trusted projects

Cursor maps the names for you: Bash becomes Shell, Edit becomes Write, and UserPromptSubmit becomes beforeSubmitPrompt. It does not map Notification or PermissionRequest. Codex calls a file edit apply_patch, so an Edit|Write matcher needs that name added there. Because Cursor fails open on a crash, write a guard to exit 2 when it cannot parse its own input. Sources: Cursor third-party hooks, Codex hooks.

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 run on these same hooks, in Claude Code, Codex and Cursor, and since 2026-10-04 they cover MCP tool calls as well as shell commands, so the GitHub MCP server's merge_pull_request can be stopped the way gh pr merge is. The ready-made ones are off, and record nothing, until your team turns one on. A guardrail you write starts in observe, the log-only week above, and one you add from the library blocks from the start. Either can be switched, and Claude Code tells each developer when one is turned on. harbor off pauses the whole thing for one repo, and harbor doctor checks that the hooks are installed and reaching the agents you think they reach.

See what is installed where. Agents and MCP lists every hook event Harbor uses per agent, and the quickstart takes about ten minutes.

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.

Do hooks run in Claude Code auto mode?

Yes. PreToolUse hooks run before the auto mode classifier: a hook that denies or exits 2 blocks the call, and one that returns ask forces a prompt the classifier cannot approve on its own. Since 2.1.284, sessions start in auto mode when no permission mode is configured.

Does Cursor run Claude Code hooks?

Yes, by default. Cursor loads hooks from .claude/settings.json, .claude/settings.local.json and ~/.claude/settings.json, maps Bash to Shell and Edit to Write, and honours exit code 2 and Claude Code's permissionDecision JSON. Codex does not read them; it uses .codex/hooks.json.


Disclosure: I work on Harbor, which published this note.

Top comments (0)