Commands
Claude
Intermediate
Hooks in Claude Code
Run custom scripts before or after Claude uses tools for validation and automation
30 of 66
What are hooks?
Hooks are scripts that run automatically when Claude Code performs specific actions. They can validate, log, or transform tool calls.
Hook types
| Hook | Runs when |
|---|---|
PreToolUse | Before Claude calls a tool (can block it) |
PostToolUse | After a tool call completes |
Notification | When Claude sends a notification |
Stop | When Claude finishes a turn |
Configuration
Add hooks to .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "python3 .claude/hooks/validate.py"
}]
}
]
}
}
Example: block writes to protected files
import sys, json
input_data = json.load(sys.stdin)
file_path = input_data.get("tool_input", {}).get("file_path", "")
protected = [".env", "secrets.json", "credentials.yml"]
if any(file_path.endswith(p) for p in protected):
print(json.dumps({"decision": "block", "reason": "Protected file"}))
else:
print(json.dumps({"decision": "approve"}))
Use cases
- Block writes to sensitive files
- Auto-format code after edits
- Log all tool calls for audit
- Run linters after file changes