Coderefercoderefer
CoursesWebinarsBlogAbout
Coderefercoderefer

Discover. Learn. Automate. Grow.

Learn

  • Courses
  • Webinars
  • Blog
  • Search

Company

  • About
  • Contact
  • FAQ

Legal

  • Privacy Policy
  • Terms of Service
  • Refund Policy
© 2026 Coderefer. All rights reserved.
HomeBlogClaude Code Hooks Tutorial: PreToolUse and PostToolUse Examples You Can Copy
ai-toolsNovember 29, 20267 min read

Claude Code Hooks Tutorial: PreToolUse and PostToolUse Examples You Can Copy

Copy-paste PreToolUse and PostToolUse hook configs for Claude Code: block rm -rf, protect .env files, auto-format on save, and feed test failures back to Claude.

V

Vamsi Tallapudi

Manager, Architect Technology at Cognizant

Claude Code Hooks Tutorial: PreToolUse and PostToolUse Examples You Can Copy

Claude Code hooks are shell commands the CLI runs automatically at fixed points in its lifecycle, like before a tool call or after one finishes. Instead of hoping Claude remembers "always run the formatter" or "never touch the .env file," you write a script once and the harness runs it every single time. No prompting, no luck involved.

I've spent the last couple weeks rebuilding my hook setup from scratch after Anthropic reshuffled the docs (the old hooks reference page now redirects to code.claude.com/docs/en/hooks), and most of the blog posts floating around still show outdated JSON shapes. This post uses the current syntax as of Claude Code 2.1.330, with five hooks you can paste straight into .claude/settings.json today.

What are PreToolUse and PostToolUse hooks?

PreToolUse fires right before Claude executes a tool call, and it's the only point where you can actually stop the action. PostToolUse fires after a tool call succeeds, so it's for reacting, not blocking: the edit already happened, the command already ran.

That distinction matters more than people realize. I see people try to "block" a bad edit with a PostToolUse hook and wonder why the file still changed. By the time PostToolUse fires, it's too late to undo it — you can only tell Claude about the problem and let it fix things in the next turn.

Both hooks live under the same hooks key in your settings file, keyed by event name, then filtered by a matcher that targets specific tools:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "echo checking..." }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "echo done" }]
      }
    ]
  }
}

Claude Code passes event data as JSON on stdin: tool_name, tool_input, and for PostToolUse, tool_output too. Your script reads that, does its thing, and reports back through stdout/stderr and the exit code.

Where do hooks live, and which file should I use?

Three main spots, each with a different blast radius:

  • ~/.claude/settings.json: applies to every project on your machine, never shared
  • .claude/settings.json: scoped to one repo, safe to commit so teammates get the same guardrails
  • .claude/settings.local.json: scoped to one repo, gitignored, for your personal overrides

For a team rule like "never let Claude edit package-lock.json," put it in .claude/settings.json and commit it. For your own desktop notification preference, use the global file. Run /hooks inside Claude Code any time to see every hook currently active, grouped by event. It's the fastest way to confirm your JSON actually loaded.

PreToolUse example 1: block destructive bash commands

This is the one everybody wants first. Save it as .claude/hooks/block-dangerous.sh:

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

if echo "$COMMAND" | grep -qE 'rm -rf|drop table|git push --force'; then
  echo "Blocked: this command looks destructive. Ask the user first." >&2
  exit 2
fi

exit 0

Make it executable with chmod +x .claude/hooks/block-dangerous.sh, then register it:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous.sh" }
        ]
      }
    ]
  }
}

Exit code 2 is the whole trick here. Anything you write to stderr becomes Claude's feedback, so it understands why the command got rejected and can propose something safer instead of just retrying blindly.

PreToolUse example 2: protect specific files from edits

Want to stop Claude from touching .env, package-lock.json, or anything under .git/? Same pattern, different check:

#!/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 with a matcher on Edit|Write. One catch worth knowing: this only stops the Edit and Write tools. Claude can still rewrite .env through a Bash command like echo "KEY=x" > .env, so if you need a hard guarantee, pair this with an Edit deny rule under permissions.deny or sandbox restrictions too. Hooks are deterministic, but they're deterministic about exactly what you matched, nothing more.

PostToolUse example 1: auto-format after every edit

This is the one I actually use the most, honestly. No more "run prettier" reminders in CLAUDE.md that Claude forgets half the time.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
          }
        ]
      }
    ]
  }
}

When it works you see nothing in the chat, which threw me off the first time. I kept thinking the hook had silently failed. Check the file on disk instead, or run claude --debug if you want to watch hooks fire in real time.

PostToolUse example 2: feed test failures back to Claude

This is the one that changed how I work. A PostToolUse hook can't block an edit that already happened, but it can return decision: "block" with a reason, and Claude treats that as something to fix right now instead of moving on.

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

if [[ "$FILE_PATH" == *.test.ts ]]; then
  OUTPUT=$(npx vitest run "$FILE_PATH" 2>&1)
  if [ $? -ne 0 ]; then
    jq -n --arg out "$OUTPUT" '{decision: "block", reason: $out}'
    exit 0
  fi
fi

exit 0
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-affected-test.sh" }
        ]
      }
    ]
  }
}

I wouldn't run a full test suite this way — it's too slow and you'll be waiting after every single edit. Scope it to the file Claude just touched, like above, and let a Stop hook run the full suite once at the end of the turn if you want that extra layer.

PreToolUse vs PostToolUse: quick comparison

PreToolUsePostToolUse
FiresBefore the tool runsAfter the tool succeeds
Can block the action?Yes (exit 2 or permissionDecision: "deny")No, the action already happened
Typical useDeny dangerous commands, protect files, auto-approve known-safe callsFormat, lint, run tests, log, feed errors back
Exit 2 behaviorTool call cancelled, stderr becomes Claude's feedbackTurn ends by default, reason shown as a warning unless continueOnBlock: true
Matcher targetTool name (Bash, Edit|Write, mcp__.*)Same, tool name

What exit codes do what?

This trips people up constantly, so here's the short version:

  • Exit 0: no objection. The normal permission flow still applies on PreToolUse; exit 0 does not auto-approve anything by itself.
  • Exit 2: block the action (on events that support blocking) and send your stderr message to Claude as the reason.
  • Any other code: treated as a non-blocking error on most events. The action proceeds unless you set "onFailure": "block" on that hook.

For anything fancier than allow-or-deny, skip exit codes and print JSON to stdout instead, like the decision: "block" object in the test-feedback example above. Pick one approach per hook. Mixing exit 2 with JSON output gets confusing fast, and the exit code wins.

Matchers: more than just tool names

A bare string like "Bash" matches exactly. Pipe or comma gives you alternatives: "Edit|Write" and "Edit, Write" work the same way. Once your matcher has characters outside letters, digits, |, ,, and spaces, Claude Code treats it as a JavaScript regex, which is how "mcp__.*__write.*" lets you catch every write-ish MCP tool across every server in one line.

Speaking of MCP: tool names from MCP servers follow mcp__<server>__<tool>, so a hook on mcp__github__.* only fires for GitHub MCP tools, not your filesystem server or anything else.

FAQ

Watch

Claude Code Hooks: Explained & Demoed

If you're setting permissions alongside hooks, read how a .claude/settings.local.json leak exposed real project data before you commit anything. Hooks and permissions both live in files people accidentally push. And if you want hooks that only apply while a specific skill is active instead of globally, check the skill.md guide for how skill frontmatter hooks scope themselves automatically. For the bigger picture on what shipped around the same release window, the 2.1.221 focus view post is a good next read.

Start with one hook, not five. Pick whichever rule you keep repeating to Claude in plain English — "don't touch .env," "always format," "run the test for the file you just changed" — and turn that one into a script first. The rest will follow once you see it actually hold.

ai-tools claude-code automation 2026

Comments

    Get AI tricks that save you hours every week

    New AI tools, automation workflows, and course drops — straight to your inbox. Join 2,400+ builders.

    Read Next

    Claude Code Sabotage Study: The 25% Gap Was a Timer Artifact
    ai-tools

    Claude Code Sabotage Study: The 25% Gap Was a Timer Artifact

    A preliminary study found Claude Code's quality dropped 25% under "no human reviews this" framing, then the gap vanished to zero once the session timer went from 20 to 60 minutes.

    November 29, 20267 min read
    How to Check a GGUF Model for Malware Before You Run It
    ai-tools

    How to Check a GGUF Model for Malware Before You Run It

    A researcher found 5 GGUF models on Hugging Face hiding a Windows RAT and poisoned chat templates, with 2,428 downloads. Here's how to scan any GGUF file first.

    November 29, 20267 min read
    Is Claude Sabotaging ML Research? What Opus 5.5 Really Restricts
    ai-tools

    Is Claude Sabotaging ML Research? What Opus 5.5 Really Restricts

    Claude isn't trained to sabotage ML research. Here's what Opus 5.5 actually restricts, the 63% early-stop rate Anthropic admitted to, and how to tell a fallback from a bug.

    November 28, 20267 min read
    View all posts →