|
| 1 | +--- |
| 2 | +sidebar_position: 5 |
| 3 | +--- |
| 4 | + |
| 5 | +# 🪝 Hooks |
| 6 | + |
| 7 | +**Event-driven automation for Claude Code workflows** |
| 8 | + |
| 9 | +Hooks are powerful automation components that execute shell commands in response to specific Claude Code events. They enable you to create automated workflows, notifications, and integrations that react to your development activities. |
| 10 | + |
| 11 | +## What are Hooks? |
| 12 | + |
| 13 | +Hooks are event-driven scripts that automatically execute when certain actions occur in Claude Code. They follow the official Claude Code hooks specification and support all hook events including tool usage, session management, and notifications. |
| 14 | + |
| 15 | +**Key Features:** |
| 16 | +- 🔄 **Event-Driven**: Automatically respond to Claude Code events |
| 17 | +- 🛠️ **Shell Integration**: Execute any shell command or script |
| 18 | +- 📊 **Environment Variables**: Access context about the triggering event |
| 19 | +- 🎯 **Pattern Matching**: Target specific tools or file types |
| 20 | +- 🔧 **Cross-Platform**: Works on macOS, Linux, and Windows |
| 21 | +- 📱 **Notifications**: Integrate with external services like Telegram, Slack, etc. |
| 22 | + |
| 23 | +## Hook Events |
| 24 | + |
| 25 | +### PreToolUse |
| 26 | +Executes **before** Claude Code processes a tool call: |
| 27 | + |
| 28 | +```json |
| 29 | +{ |
| 30 | + "PreToolUse": [ |
| 31 | + { |
| 32 | + "matcher": "Edit|Write", |
| 33 | + "hooks": [ |
| 34 | + { |
| 35 | + "type": "command", |
| 36 | + "command": "echo 'About to modify file: $CLAUDE_TOOL_FILE_PATH'" |
| 37 | + } |
| 38 | + ] |
| 39 | + } |
| 40 | + ] |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +### PostToolUse |
| 45 | +Executes **after** a tool completes successfully: |
| 46 | + |
| 47 | +```json |
| 48 | +{ |
| 49 | + "PostToolUse": [ |
| 50 | + { |
| 51 | + "matcher": "Edit", |
| 52 | + "hooks": [ |
| 53 | + { |
| 54 | + "type": "command", |
| 55 | + "command": "git add \"$CLAUDE_TOOL_FILE_PATH\"" |
| 56 | + } |
| 57 | + ] |
| 58 | + } |
| 59 | + ] |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Other Events |
| 64 | +- **Stop**: Main Claude Code agent finished responding |
| 65 | +- **SubagentStop**: Subagent (Task tool) finished responding |
| 66 | +- **Notification**: Claude Code sends notifications |
| 67 | +- **UserPromptSubmit**: User submits a prompt |
| 68 | +- **SessionStart**: New session or resume |
| 69 | +- **PreCompact**: Before context compaction |
| 70 | + |
| 71 | +## Available Hook Categories |
| 72 | + |
| 73 | +### 🔧 Development Tools |
| 74 | +Essential development workflow automation: |
| 75 | + |
| 76 | +- **`command-logger`** - Log all Claude Code tool usage for audit trails |
| 77 | +- **`file-backup`** - Automatically backup files before editing |
| 78 | +- **`change-tracker`** - Track all file modifications with timestamps |
| 79 | +- **`smart-formatting`** - Auto-format code using Prettier, Black, gofmt, etc. |
| 80 | +- **`lint-on-save`** - Run linting tools after file modifications |
| 81 | + |
| 82 | +### 🔄 Git Workflow |
| 83 | +Git integration and version control automation: |
| 84 | + |
| 85 | +- **`auto-git-add`** - Automatically stage modified files |
| 86 | +- **`smart-commit`** - Generate intelligent commit messages based on changes |
| 87 | + |
| 88 | +### 🧪 Testing |
| 89 | +Automated testing integration: |
| 90 | + |
| 91 | +- **`test-runner`** - Run relevant tests after code changes |
| 92 | + |
| 93 | +### ⚡ Automation |
| 94 | +General purpose automation and notifications: |
| 95 | + |
| 96 | +- **`build-on-change`** - Trigger build processes when files change |
| 97 | +- **`simple-notifications`** - Desktop notifications for completed operations |
| 98 | +- **`dependency-checker`** - Monitor and audit package dependencies |
| 99 | +- **`telegram-notifications`** - Send Telegram messages when work completes |
| 100 | +- **`telegram-detailed-notifications`** - Detailed session tracking via Telegram |
| 101 | +- **`telegram-error-notifications`** - Monitor long operations and issues |
| 102 | + |
| 103 | +### 🔒 Security |
| 104 | +Security monitoring and file protection: |
| 105 | + |
| 106 | +- **`file-protection`** - Prevent modification of critical system files |
| 107 | +- **`security-scanner`** - Scan code for vulnerabilities and secrets |
| 108 | + |
| 109 | +### 📊 Performance |
| 110 | +Performance monitoring and optimization: |
| 111 | + |
| 112 | +- **`performance-monitor`** - Track CPU, memory usage, and execution times |
| 113 | + |
| 114 | +## Installation Options |
| 115 | + |
| 116 | +Like settings, hooks support the full Claude Code configuration hierarchy: |
| 117 | + |
| 118 | +### 🏠 User Hooks (`~/.claude/settings.json`) |
| 119 | +- **Scope**: Global - applies to all projects |
| 120 | +- **Use case**: Personal automation preferences |
| 121 | + |
| 122 | +### 📁 Project Hooks (`.claude/settings.json`) |
| 123 | +- **Scope**: Project-specific |
| 124 | +- **Use case**: Team-shared automation, project requirements |
| 125 | + |
| 126 | +### ⚙️ Local Hooks (`.claude/settings.local.json`) |
| 127 | +- **Scope**: Project-specific, personal |
| 128 | +- **Use case**: Personal automation, experimentation |
| 129 | + |
| 130 | +### 🏢 Enterprise Hooks (Platform-specific) |
| 131 | +- **Scope**: System-wide automation policies |
| 132 | +- **Use case**: Organization-wide monitoring and compliance |
| 133 | + |
| 134 | +## Installation Methods |
| 135 | + |
| 136 | +### Using CLI (Recommended) |
| 137 | +```bash |
| 138 | +# Install with interactive location selection |
| 139 | +npx claude-code-templates@latest --hook=git-workflow/auto-git-add |
| 140 | + |
| 141 | +# Install multiple hooks |
| 142 | +npx claude-code-templates@latest --hook=development-tools/file-backup,automation/simple-notifications |
| 143 | + |
| 144 | +# Skip location prompt (defaults to local settings) |
| 145 | +npx claude-code-templates@latest --hook=testing/test-runner --yes |
| 146 | +``` |
| 147 | + |
| 148 | +### Installation Flow |
| 149 | +When installing hooks, you'll choose the installation location: |
| 150 | + |
| 151 | +1. **🏠 User settings** - Global automation |
| 152 | +2. **📁 Project settings** - Shared team automation |
| 153 | +3. **⚙️ Local settings** - Personal automation (default) |
| 154 | +4. **🏢 Enterprise settings** - System-wide automation (requires admin) |
| 155 | + |
| 156 | +## Usage Examples |
| 157 | + |
| 158 | +### Basic File Operations |
| 159 | +```bash |
| 160 | +# Backup files before editing |
| 161 | +npx claude-code-templates@latest --hook=development-tools/file-backup |
| 162 | + |
| 163 | +# Track all file changes |
| 164 | +npx claude-code-templates@latest --hook=development-tools/change-tracker |
| 165 | + |
| 166 | +# Auto-format code after editing |
| 167 | +npx claude-code-templates@latest --hook=development-tools/smart-formatting |
| 168 | +``` |
| 169 | + |
| 170 | +### Git Integration |
| 171 | +```bash |
| 172 | +# Automatically stage changes |
| 173 | +npx claude-code-templates@latest --hook=git-workflow/auto-git-add |
| 174 | + |
| 175 | +# Generate smart commits |
| 176 | +npx claude-code-templates@latest --hook=git-workflow/smart-commit |
| 177 | +``` |
| 178 | + |
| 179 | +### Automation & Notifications |
| 180 | +```bash |
| 181 | +# Get desktop notifications |
| 182 | +npx claude-code-templates@latest --hook=automation/simple-notifications |
| 183 | + |
| 184 | +# Telegram integration (requires bot setup) |
| 185 | +npx claude-code-templates@latest --hook=automation/telegram-notifications |
| 186 | +``` |
| 187 | + |
| 188 | +### Security & Performance |
| 189 | +```bash |
| 190 | +# Protect sensitive files |
| 191 | +npx claude-code-templates@latest --hook=security/file-protection |
| 192 | + |
| 193 | +# Monitor performance |
| 194 | +npx claude-code-templates@latest --hook=performance/performance-monitor |
| 195 | +``` |
| 196 | + |
| 197 | +## Environment Variables |
| 198 | + |
| 199 | +Hooks have access to context about the triggering event: |
| 200 | + |
| 201 | +- **`$CLAUDE_TOOL_NAME`** - Name of the tool being executed |
| 202 | +- **`$CLAUDE_TOOL_FILE_PATH`** - File path for file operations |
| 203 | +- **`$CLAUDE_PROJECT_DIR`** - Project root directory |
| 204 | + |
| 205 | +### Example Usage |
| 206 | +```bash |
| 207 | +# Log tool usage with context |
| 208 | +echo "[$(date)] $CLAUDE_TOOL_NAME executed on $CLAUDE_TOOL_FILE_PATH" |
| 209 | + |
| 210 | +# Conditional logic based on file type |
| 211 | +if [[ "$CLAUDE_TOOL_FILE_PATH" == *.js ]]; then |
| 212 | + npx prettier --write "$CLAUDE_TOOL_FILE_PATH" |
| 213 | +fi |
| 214 | +``` |
| 215 | + |
| 216 | +## Tool Matchers |
| 217 | + |
| 218 | +Control which tools trigger your hooks: |
| 219 | + |
| 220 | +### Common Matchers |
| 221 | +- **`*`** - Match all tools |
| 222 | +- **`Edit`** - File editing operations |
| 223 | +- **`Write`** - File creation operations |
| 224 | +- **`Bash`** - Shell commands |
| 225 | +- **`Read`** - File reading operations |
| 226 | + |
| 227 | +### Pattern Matching |
| 228 | +```json |
| 229 | +{ |
| 230 | + "matcher": "Edit|Write|MultiEdit", // Multiple tools |
| 231 | + "matcher": "Notebook.*", // Regex patterns |
| 232 | + "matcher": "*" // All tools |
| 233 | +} |
| 234 | +``` |
| 235 | + |
| 236 | +## Hook Structure |
| 237 | + |
| 238 | +Hooks follow the official Claude Code specification: |
| 239 | + |
| 240 | +```json |
| 241 | +{ |
| 242 | + "description": "What this hook does", |
| 243 | + "hooks": { |
| 244 | + "PostToolUse": [ |
| 245 | + { |
| 246 | + "matcher": "Edit", |
| 247 | + "hooks": [ |
| 248 | + { |
| 249 | + "type": "command", |
| 250 | + "command": "your-shell-command-here" |
| 251 | + } |
| 252 | + ] |
| 253 | + } |
| 254 | + ] |
| 255 | + } |
| 256 | +} |
| 257 | +``` |
| 258 | + |
| 259 | +## Advanced Examples |
| 260 | + |
| 261 | +### Telegram Notifications Setup |
| 262 | + |
| 263 | +1. **Create Telegram Bot**: |
| 264 | + - Message [@BotFather](https://t.me/BotFather) |
| 265 | + - Create new bot with `/newbot` |
| 266 | + - Save the bot token |
| 267 | + |
| 268 | +2. **Get Chat ID**: |
| 269 | + - Message your bot |
| 270 | + - Visit: `https://api.telegram.org/bot<TOKEN>/getUpdates` |
| 271 | + - Copy your chat ID from the response |
| 272 | + |
| 273 | +3. **Set Environment Variables**: |
| 274 | + ```bash |
| 275 | + export TELEGRAM_BOT_TOKEN="your-bot-token" |
| 276 | + export TELEGRAM_CHAT_ID="your-chat-id" |
| 277 | + ``` |
| 278 | + |
| 279 | +4. **Install Hook**: |
| 280 | + ```bash |
| 281 | + npx claude-code-templates@latest --hook=automation/telegram-notifications |
| 282 | + ``` |
| 283 | + |
| 284 | +### Custom File Processing |
| 285 | +```json |
| 286 | +{ |
| 287 | + "description": "Process TypeScript files after editing", |
| 288 | + "hooks": { |
| 289 | + "PostToolUse": [ |
| 290 | + { |
| 291 | + "matcher": "Edit", |
| 292 | + "hooks": [ |
| 293 | + { |
| 294 | + "type": "command", |
| 295 | + "command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.ts ]]; then npx tsc --noEmit \"$CLAUDE_TOOL_FILE_PATH\" && echo '✅ TypeScript check passed'; fi" |
| 296 | + } |
| 297 | + ] |
| 298 | + } |
| 299 | + ] |
| 300 | + } |
| 301 | +} |
| 302 | +``` |
| 303 | + |
| 304 | +## Best Practices |
| 305 | + |
| 306 | +### Hook Design |
| 307 | +- **Keep Commands Simple**: Use short, focused commands |
| 308 | +- **Handle Errors Gracefully**: Include `2>/dev/null || true` for optional operations |
| 309 | +- **Check Prerequisites**: Verify tools exist before using them |
| 310 | +- **Use Absolute Paths**: Avoid relative path issues |
| 311 | + |
| 312 | +### Performance Considerations |
| 313 | +- **Minimize Hook Execution Time**: Hooks should complete quickly |
| 314 | +- **Avoid Blocking Operations**: Don't use commands that wait for user input |
| 315 | +- **Test Thoroughly**: Ensure hooks work across different scenarios |
| 316 | +- **Monitor Resource Usage**: Watch for memory/CPU impact |
| 317 | + |
| 318 | +### Security Guidelines |
| 319 | +- **Validate Inputs**: Never execute unvalidated user input |
| 320 | +- **Limit Scope**: Use specific matchers rather than `*` when possible |
| 321 | +- **Protect Credentials**: Use environment variables for sensitive data |
| 322 | +- **Review Commands**: Audit hook commands regularly |
| 323 | + |
| 324 | +## Troubleshooting |
| 325 | + |
| 326 | +### Hook Not Executing? |
| 327 | +- Verify hook is installed in the correct settings file |
| 328 | +- Check Claude Code version supports hooks |
| 329 | +- Ensure environment variables are properly set |
| 330 | +- Test with simple commands first |
| 331 | + |
| 332 | +### Permission Errors? |
| 333 | +- Check file permissions on script files |
| 334 | +- Verify Claude Code has necessary permissions |
| 335 | +- For enterprise hooks, ensure admin privileges |
| 336 | +- Review system security policies |
| 337 | + |
| 338 | +### Command Failures? |
| 339 | +- Test commands manually in terminal |
| 340 | +- Check command availability with `which command-name` |
| 341 | +- Review error output (remove `2>/dev/null` temporarily) |
| 342 | +- Verify file paths and environment variables |
| 343 | + |
| 344 | +## Creating Custom Hooks |
| 345 | + |
| 346 | +Want to create your own hook? Follow these guidelines: |
| 347 | + |
| 348 | +1. **Define Clear Purpose**: Each hook should solve one specific problem |
| 349 | +2. **Use Official Structure**: Follow Claude Code hooks specification |
| 350 | +3. **Handle Edge Cases**: Account for missing files, permissions, etc. |
| 351 | +4. **Include Error Handling**: Use `|| true` for non-critical operations |
| 352 | +5. **Document Thoroughly**: Explain what the hook does and how to use it |
| 353 | +6. **Test Extensively**: Verify across different platforms and scenarios |
| 354 | + |
| 355 | +### Example Custom Hook |
| 356 | +```json |
| 357 | +{ |
| 358 | + "description": "Automatically deploy to staging after successful tests", |
| 359 | + "hooks": { |
| 360 | + "PostToolUse": [ |
| 361 | + { |
| 362 | + "matcher": "Edit", |
| 363 | + "hooks": [ |
| 364 | + { |
| 365 | + "type": "command", |
| 366 | + "command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.js && -f package.json ]]; then npm test && npm run deploy:staging; fi" |
| 367 | + } |
| 368 | + ] |
| 369 | + } |
| 370 | + ] |
| 371 | + } |
| 372 | +} |
| 373 | +``` |
| 374 | + |
| 375 | +--- |
| 376 | + |
| 377 | +**Next Steps:** |
| 378 | +- [Browse All Hooks](https://aitmpl.com) - View available hooks in the web interface |
| 379 | +- [Automation Hooks Guide →](../project-setup/automation-hooks) - Deep dive into automation workflows |
| 380 | +- [Contributing Guide →](../contributing) - Add your own hooks to the collection |
| 381 | +- [Telegram Setup Guide →](https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/hooks/automation/TELEGRAM_SETUP.md) - Detailed Telegram integration guide |
0 commit comments