Lesson 19Automation
Hooks System
Lifecycle events
What are Hooks
Hooks are shell commands that automatically execute on certain events in Claude Code.
Use cases
- • Auto-format after Edit
- • Bash command validation
- • Slack notifications
- • Action logging
Limitations
- • Execute synchronously
- • 60 second timeout
- • Can block operations
Hook Events
SessionStartWhen Claude Code session starts
SessionEndWhen session ends
PreToolUseBefore tool is called
PostToolUseAfter tool is called
UserPromptSubmitWhen user sends a message
NotificationOn notifications from Claude
StopWhen Claude stops
Example: Auto-formatting
Automatic file formatting after editing:
// .claude/hooks/format-on-edit.json
{
"hooks": {
"PostToolUse": [
{
"name": "auto-format",
"match": {
"tool": "Edit",
"path": "**/*.{ts,tsx,js,jsx}"
},
"command": ["npx", "prettier", "--write", "{{path}}"]
}
]
}
}💡{{path}} is replaced with the path to the edited file
Example: Blocking Dangerous Commands
PreToolUse can block operations by returning exit code 1:
// Блокировка опасных команд
{
"hooks": {
"PreToolUse": [
{
"name": "block-dangerous-commands",
"match": {
"tool": "Bash"
},
"command": ["bash", "-c", "
if echo '{{command}}' | grep -qE 'rm -rf|drop database'; then
echo 'BLOCKED: Dangerous command detected' >&2
exit 1
fi
"]
}
]
}
}Exit code 0
Operation continues
Exit code 1
Operation is blocked
Hook Configuration
Hooks are configured in .claude/hooks/*.json files:
.claude/hooks/ ├── format.json # Auto-formatting hooks ├── security.json # Security validation hooks ├── notify.json # Notification hooks └── logging.json # Logging hooks
nameHook name for loggingmatchTrigger conditions (tool, path)commandCommand to executeHook Best Practices
- 1.Keep hooks fast — they block the main thread
- 2.Use match for precise triggering
- 3.Log hook errors for debugging
- 4.Test hooks locally before committing
This lesson is part of a structured LLM course.
My Learning Path