Claude Code
authorKRIATIZ
03 · Extensions / lesson 4 of 4

Hooks: automatic checks

20 minAdvanced6 steps

The agent may skip an instruction in CLAUDE.md. A hook always runs: it is a command Claude Code executes on a given event. That makes formatting, guardrails and alerts reliable.

data and requestsproblem
Lesson stepsstep 1 of 6
  1. Skipped
  2. PreToolUse
  3. Block
  4. PostToolUse
  5. Alerts
  6. Summary
step 1 / 6problem

The agent may forget a rule

"Format after changes" in CLAUDE.md is sometimes skipped, especially in long sessions.

Key point

What must always happen belongs in a hook.

← → steps · space pause · R restart · ⌘K search
You will learn 5
Lesson notes

Events

EventWhen it firesExample
PreToolUsebefore a tool callblock a dangerous command
PostToolUseafter a tool callformat the changed file
UserPromptSubmitwhen you send a promptadd context, validate the prompt
Stopwhen the agent finishes a replynotify that the task is done
Notificationwhen the agent waits for youa message that permission is needed
SessionStartat session startload fresh context

Example: auto-format after edits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "npx prettier --write \"$CLAUDE_PROJECT_DIR\"/src" }]
      }
    ]
  }
}

Hooks live in the same settings.json files as permissions. The /hooks command helps you view and configure them in a session.

Guardrails: blocking commands

A PreToolUse hook receives the tool call as JSON on standard input. The script can inspect it and, if it is dangerous, exit with code 2: the call is blocked and the stderr message is shown to the agent as the reason.

# .claude/hooks/block-secrets.sh
input=$(cat)
if echo "$input" | grep -q '\.env'; then
  echo "Access to .env is forbidden" >&2
  exit 2
fi

Hook ideas

  • Formatting and linting after every file change.
  • Forbidding edits to generated files or migrations.
  • Running fast tests when the agent finishes.
  • A Telegram or Slack message when the agent waits for permission.
  • A log of every agent command for audit.

Be careful

  • A hook runs with your permissions. Review scripts, especially other people’s.
  • A slow hook slows every agent step. Keep them fast.
  • After changing hooks, test them on a simple task.

10 ready-made recipes are in the article "Claude Code Hooks".

Today's task

Add a PostToolUse hook with your project’s formatter and a Notification hook with a sound or system notification.

Need hooks for your team?

I will set up hooks for formatting, secret protection, tests and Telegram or Slack alerts.

Let’s talk
Vladyslav Koshelyev
Vladyslav Koshelyev

Developer at KRIATIZ. I build chatbots, websites and automation for businesses. Author of the course.

About the author · Telegram