🧭 How toAIIntermediate✨ AI-assisted

Claude Code Hooks: Automating Guardrails Your Team Actually Needs

WittyTech··2 min read
#claude-code#hooks#guardrails

You can write "always run the formatter" in CLAUDE.md, and Claude will follow it most of the time. For guardrails, most of the time isn't enough. Hooks run automatically, so the rule is applied on every occasion.

What hooks are

Hooks are shell commands that Claude Code runs at specific points while it works. You configure them in settings files. Because Claude Code runs them itself, they don't depend on the model remembering an instruction.

Commonly used events include:

  • PreToolUse: runs before a tool is used and can block it.
  • PostToolUse: runs after a tool completes successfully.
  • UserPromptSubmit: runs when a prompt is submitted.
  • Stop: runs when Claude finishes its response.
  • SessionStart: runs when a session begins.

Each hook receives details about the event as JSON on standard input, including the tool name and its input.

Step 1: Format files after every edit

In .claude/settings.json:

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

Every file Claude creates or edits is formatted automatically.

Step 2: Block commands you never want to run

A PreToolUse hook on the Bash tool can inspect each command and reject dangerous ones, such as force-pushing to the main branch or deleting directories outside the project. Exiting with code 2 blocks the call, and whatever the script writes to standard error is passed back to Claude so it can take a different approach.

Step 3: Run checks when Claude finishes

A Stop hook can run the test suite or a linter when Claude completes a response, so problems appear straight away rather than during code review.

Step 4: Share the configuration

Project settings in .claude/settings.json can be committed to the repository, so the whole team gets the same hooks. Personal preferences belong in local settings that aren't committed.

Things to watch

  • Hooks run with your permissions. Review hook scripts as carefully as any other code, especially in repositories you didn't write.
  • Keep them quick. A slow hook after every edit makes sessions frustrating. Put slower checks in a Stop hook.
  • Make failures visible. A hook that fails silently gives false confidence. Trigger each hook on purpose to confirm it works.
  • Don't block too much. If a hook keeps stopping legitimate work, people will turn it off.

Start with one formatting hook and one blocking hook, and add others when a real problem calls for them.

← More in AI