
Claude Code Hooks: Auto-Format, Security Guards, and Test Triggers on Every Tool Call
Claude Code's Hooks system lets you run scripts automatically before or after every tool call — code writes, bash commands, file edits. Configure them once, and every interaction gets automatic quality enforcement. What Hooks Can Do Before bash execution → Block dangerous commands ( rm -rf / , DROP DATABASE ) After file writes → Auto-format with Prettier/Ruff/gofmt After file writes → Scan for leaked API keys After source changes → Run related unit tests automatically Hook Configuration Add hooks to .claude/settings.json (project-level) or ~/.claude/settings.json (global): { "hooks" : { "PreToolUse" : [ { "matcher" : "Bash" , "hooks" : [{ "type" : "command" , "command" : "python .claude/hooks/guard.py" }] } ], "PostToolUse" : [ { "matcher" : "Write|Edit" , "hooks" : [{ "type" : "command" , "command" : "python .claude/hooks/format.py" , "timeout" : 30 }] } ] } } Exit Code Protocol For PreToolUse hooks: Exit Code Meaning 0 Allow — tool executes normally 2 Block — tool execution is cancel
Continue reading on Dev.to
Opens in a new tab




