Claude Code Hooks: Complete Automation Guide
2026-03-23 · SKILL TOP
Tags: Claude Code, Hooks, Automation, Developer Tools, Workflow
Claude Code hooks represent one of the most powerful yet underutilized features in Anthropic's agentic coding tool. While many developers rely on Claude Code for generating code and answering questions, Claude Code hooks enable you to automate repetitive tasks, enforce coding standards, and create custom workflows that run automatically at key points in your development session. This comprehensive guide will show you how to leverage Claude Code hooks to transform how you work with AI-assisted development.
By the end of this tutorial, you will understand how to configure hooks that automatically load project context, validate changes before they are made, integrate with external services, and streamline your entire development workflow.
What Are Claude Code Hooks?
Claude Code hooks are event-driven automation triggers that execute custom commands or prompts at specific points during your Claude Code session. Think of Claude Code hooks as Git hooks for your AI assistant: they run automatically when certain events occur, allowing you to customize and extend Claude's behavior without manual intervention.
Why Hooks Matter for Developer Productivity
Claude Code hooks solve these problems by automating routine tasks and enforcing consistency across your workflow. Once configured, Claude Code hooks work silently in the background, letting you focus on actual development rather than meta-work.
Why Hooks Matter for Developer Productivity
Manual configuration and repetitive instructions consume valuable development time. Without using Claude Code hooks, you might find yourself:
-
Repeating project-specific instructions in every new session
-
Manually checking git status before making changes
-
Remembering to run tests after code modifications
-
Copying and pasting the same prompts for code reviews
-
Repeating project-specific instructions in every new session
-
Manually checking git status before making changes
-
Remembering to run tests after code modifications
-
Copying and pasting the same prompts for code reviews
Without hooks in Claude Code, these manual tasks interrupt your flow and waste valuable development time.
Key Benefits
Each Claude Code hook addresses specific productivity challenges:
- Automatic context loading: Project-specific information appears instantly
- Consistent workflows: Enforce coding standards and validation steps automatically
- Reduced cognitive load: Fewer manual steps to remember and execute
- Team standardization: Share hook configurations across your development team
- Integration capabilities: Connect Claude Code to external tools and services
Understanding Hook Types
Claude Code hooks support several event types, each triggering at different points in the session lifecycle. Understanding when each Claude Code hook fires is essential for building effective automation.
SessionStart Hooks
SessionStart hooks execute immediately when you launch Claude Code, before any interaction occurs. These are ideal for:
- Loading project-specific context
- Setting up environment variables
- Displaying project status information
- Initializing scheduled tasks
SessionEnd Hooks
SessionEnd hooks run when you close your Claude Code session. Use them for:
- Cleaning up temporary files
- Logging session activity
- Saving state or context
- Sending completion notifications
PreToolUse Hooks
PreToolUse hooks execute immediately before Claude uses a tool (like Bash, Read, Write, Edit). They are perfect for:
- Validating file write operations for safety
- Checking git status before destructive operations
- Screening commands for potential risks
- Enforcing coding standards before changes
PostToolUse Hooks
PostToolUse hooks run after Claude completes a tool operation. They excel at:
- Reviewing code changes for quality
- Running tests automatically after edits
- Checking for security issues
- Providing immediate feedback on changes
Setting Up Your First Hook
Before creating Claude Code hooks, you need to understand the plugin structure where hooks are stored. Claude Code plugins provide a organized way to package custom functionality.
Plugin Structure
Each plugin follows a standard directory structure:
.claude/plugins/your-plugin/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest
├── agents/ # Custom agents
├── commands/ # Slash commands
├── skills/ # Reusable skills
└── hooks/ # Hook definitions
├── session-start.md
├── session-end.md
├── pre-tool-use.md
└── post-tool-use.md
Creating a Basic Plugin
The foundation of Claude Code hooks is a properly structured plugin. First, create the plugin directory structure:
mkdir -p .claude/plugins/my-hooks/.claude-plugin mkdir -p .claude/plugins/my-hooks/hooksbash
Next, create the plugin manifest at .claude/plugins/my-hooks/.claude-plugin/plugin.json:
{ "name": "my-hooks", "version": "1.0.0", "description": "Custom automation hooks for my workflow", "author": "Your Name", "license": "MIT", "hooks": [ "hooks/session-start.md", "hooks/pre-tool-use.md", "hooks/post-tool-use.md" ] }json
Creating a SessionStart Hook
Create your first hook file at .claude/plugins/my-hooks/hooks/session-start.md:
--- event: SessionStart --- \# Display Project Context When a new session starts, automatically show current project information. ## Information to Display - Current git branch - Recent commits (last 3) - Modified files - Project type detection ## Execution Use Bash tool to run: ```bash echo "## Current Context" echo "Branch: $(git branch --show-current 2>/dev/null || echo 'Not a git repo')" echo "Last commit: $(git log -1 --oneline 2>/dev/null || echo 'No commits')" echo "" echo "## Modified Files" git status --short 2>/dev/null || echo "No changes detected"markdown
This **Claude Code hook** runs automatically every time you start Claude Code, giving you immediate context about your project state.
### Verifying Hook Installation
Restart Claude Code to load your plugin. You should see the project context displayed immediately upon startup. If your **Claude Code hooks** do not execute:
1. Verify the plugin manifest path is correct
2. Check that the hook file has the correct event frontmatter
3. Ensure Claude Code has permission to access the files
4. Review Claude Code's startup logs for errors
## Practical Hook Examples
Now that you understand the basics of **Claude Code hooks**, let's explore practical hook patterns that solve real development problems. These **Claude Code hook** examples demonstrate common automation scenarios.
### Auto-Environment Setup
Automatically load project-specific context and configuration based on the current directory.
```markdown
---
event: SessionStart
---
\# Auto-Load Project Context
Detect project type and load appropriate context automatically.
## Project Detection Rules
Check for these indicators in order:
1. **Next.js**: presence of `next.config.js` or `next.config.ts`
2. **React**: `package.json` contains `react` dependency
3. **Node.js**: `package.json` exists
4. **Python**: `requirements.txt` or `pyproject.toml` exists
5. **Go**: `go.mod` exists
## Execution Steps
1. Read `package.json` or equivalent config file
2. Identify project type and framework
3. Read project-specific CLAUDE.md if it exists
4. Display relevant information:
- Framework name and version
- Available scripts
- Project structure highlights
5. Load any project-specific hooks from `.claude/` directory
## Example Output Format
Project Detected: Next.js 16
- Framework: Next.js with App Router
- Styling: Tailwind CSS detected
- Available scripts: dev, build, start, lint
- Test command: npm run test
Pre-Commit Validation Hook
Automatically run tests and quality checks before committing changes.
--- event: PreToolUse --- \# Pre-Commit Safety Check Validate git commit operations to prevent broken code from being committed. ## Matcher Match these tool patterns: - `Bash(git commit *)` - `Bash(git push *)` ## Validation Steps Before allowing commit/push, verify: 1. **Tests Pass**: Run test suite if available - Check for `npm test`, `pytest`, `go test` - Fail if tests fail 2. **Build Status**: Verify project builds - Run `npm run build` for Node.js - Run `go build` for Go projects - Fail if build fails 3. **No Secrets**: Check for common secrets - Scan for API keys, tokens - Check for `.env` files staged for commit - Warn if sensitive patterns detected 4. **Branch Status**: Verify branch state - Check if on main/master branch - Warn if committing directly to main ## Execution For matched operations, run validation commands and: - Approve if all checks pass - Deny with explanation if any check failsmarkdown
This Claude Code hook prevents broken code from entering your repository and enforces quality standards automatically.
Session Logging Hook
Track your Claude Code interactions for debugging and analysis.
--- event: SessionEnd --- \# Session Summary Logging Create a summary of the session for future reference. ## Information to Collect 1. **Duration**: Session start and end time 2. **Files Modified**: List of files edited or created 3. **Commands Run**: Bash commands executed 4. **Tasks Completed**: Major work accomplished ## Output Location Save to: `.claude/logs/session-{timestamp}.md` ## Format ```markdown \# Claude Code Session Summary **Date**: {current_date} **Duration**: {session_duration} ## Files Modified {list of modified files} ## Commands Executed {list of bash commands} ## Work Completed {summary of major tasks}markdown
Privacy Note
Do not log actual conversation content or code snippets. Focus on metadata and file references only.
### Notification Hook for Long-Running Tasks
Send notifications when long operations complete.
```markdown
---
event: PostToolUse
---
\# Long-Running Task Notifications
Send notifications when time-consuming operations complete.
## Matcher
Match tools with execution time > 30 seconds:
- `Bash(npm test)`
- `Bash(npm run build)`
- `Bash(pytest)`
- Any Bash command with `run_in_background: true`
## Notification Channels
1. **Desktop Notification**: Use system notification
2. **Slack**: Send to configured webhook
3. **Discord**: Post to webhook URL
## Configuration
Read notification settings from environment:
- `NOTIFICATION_WEBHOOK_URL`: Webhook endpoint
- `NOTIFICATION_ENABLED`: Set to "true" to enable
## Message Format
Claude Code Task Complete
Command: {command} Duration: {duration} Status: {success/failed}
Project: {project_name} Branch: {git_branch}
## Execution
Only send notifications if:
- Task ran longer than threshold
- Webhook URL is configured
- NOTIFICATION_ENABLED is true
Advanced Hook Patterns
As you become comfortable with basic Claude Code hooks, you can implement more sophisticated automation patterns. Advanced Claude Code hooks enable complex workflows that adapt to your development environment.
Conditional Hooks Based on Project Type
Create hooks that behave differently depending on your project's technology stack.
--- event: SessionStart --- \# Project-Type-Specific Setup Load different context and automation based on project detection. ## Detection Logic Run detection in order: 1. Check for framework-specific files 2. Read package.json or equivalent 3. Identify primary language and framework 4. Load appropriate hook configuration ## Conditional Actions ### If Next.js Detected - Load Next.js specific CLAUDE.md instructions - Show App Router vs Pages Router status - List available Next.js CLI commands - Display middleware configuration ### If Django Detected - Load Django-specific conventions - Show installed apps - List management commands - Display settings module location ### If Generic Node.js - Show npm scripts - Display dependency count - Check for TypeScript configurationmarkdown
Hook Chaining and Dependencies
Create hooks that trigger other hooks or depend on previous execution.
--- event: SessionStart --- \# Hook Chain: Project Setup This hook triggers a sequence of dependent actions. ## Execution Order 1. **Primary Hook**: Load project context 2. **Secondary Hook**: Check for uncommitted changes 3. **Tertiary Hook**: Run status check if changes exist 4. **Final Hook**: Offer to create stash if working tree dirty ## Dependency Management Each hook should: - Check for successful completion of previous hook - Store state in temporary files if needed - Provide clear error messages if dependencies fail ## State Storage Use `.claude/temp/` for temporary state: - `project-type.txt`: Detected project type - `git-status.json`: Cached git status - `last-commands.txt`: Recent bash historymarkdown
Team-Shared Hook Configurations
Share hooks across your team for consistent workflows.
--- event: SessionStart --- \# Team Standard Hooks Loader Load team-standard hooks from shared configuration. ## Hook Sources Check in order: 1. **Project-local**: `.claude/hooks/` 2. **Team-shared**: `.claude-team/hooks/` (if git repo) 3. **Global**: `~/.claude/global-hooks/` ## Merge Strategy - Hooks from later sources override earlier ones - Same hook names: most specific wins - Different hook names: all are loaded ## Team Configuration File Create `.claude-team/config.json`: ```json { "hooks": { "pre-commit": "mandatory", "pre-push": "recommended", "session-start": "optional" }, "enforcement": "warn" }markdown
Enforcement Levels
- mandatory: Hook must succeed or operation blocked
- recommended: Hook runs but failures only warn
- optional: Hook runs silently, no enforcement
## CI/CD Integration
**Claude Code hooks** become even more powerful when integrated with your continuous integration and deployment pipelines. For teams implementing remote AI control systems, **Claude Code hooks** can work alongside tools like [Claude Dispatch](/blog/claude-dispatch-remote-ai-control) for comprehensive automation.
### Pipeline-Specific Hook Configurations
Different environments may require different hook behaviors.
```markdown
---
event: SessionStart
---
\# CI/CD Environment Detection
Configure hooks based on detected environment.
## Environment Detection
Check environment variables in order:
1. `CI`: Set by most CI providers
2. `GITHUB_ACTIONS`: GitHub Actions
3. `GITLAB_CI`: GitLab CI
4. `JENKINS_HOME`: Jenkins
5. `LOCAL_DEVELOPMENT`: Default if none detected
## Environment-Specific Behavior
### Local Development
- Enable all hooks
- Run tests on file changes
- Show detailed notifications
- Allow destructive operations
### CI Environment
- Disable interactive hooks
- Skip session-start hooks
- Enable only validation hooks
- Log all actions for debugging
### Production Deployments
- Run pre-deployment checks
- Enable rollback capability
- Send deployment notifications
- Require approval for destructive changes
## Execution
Before running any hook:
1. Check current environment
2. Load environment-specific config
3. Filter hooks based on environment
4. Execute only applicable hooks
Automated Code Review Workflow
Create a comprehensive code review automation using hooks.
--- event: PostToolUse --- \# Automated Code Review Perform automated code review after file modifications. ## Matcher Match file modification operations: - `Write(*.ts)` - `Write(*.js)` - `Write(*.py)` - `Write(*.go)` - `Edit(*.ts)` - `Edit(*.js)` - `Edit(*.py)` - `Edit(*.go)` ## Review Checks 1. **Security Scan** - Check for hardcoded secrets - Identify SQL injection risks - Find unsafe eval/exec usage - Detect authentication issues 2. **Code Quality** - Check for TODO/FIXME comments - Identify overly complex functions - Find duplicated code patterns - Check naming conventions 3. **Testing Coverage** - Identify new untested functions - Check for missing test files - Suggest test cases for changed code 4. **Documentation** - Check for undocumented APIs - Find missing JSDoc/docstrings - Identify complex code needing comments ## Output Format ```markdown ## Code Review Results ### Security {security_findings} ### Quality {quality_findings} ### Testing {testing_recommendations} ### Documentation {documentation_gaps}markdown
Integration
This hook integrates with:
- Pre-commit hook (block issues before commit)
- CI pipeline (run full suite in CI)
- Pull request automation (comment on PRs)
## Best Practices and Troubleshooting
Following established patterns will help you create reliable, maintainable **Claude Code hooks**. When building **Claude Code hooks** for production use, keep these best practices in mind.
### Hook Development Best Practices
**Start Simple**
Begin with basic **Claude Code hooks** that print information. Verify they execute correctly before adding complex logic.
**Use Explicit Matchers**
Be specific about which tools and patterns your hooks match. Overly broad matchers can cause unexpected behavior.
```markdown
\# Good: Specific matcher
matcher: "Write(*.ts)"
\# Risky: Overly broad matcher
matcher: "Write"
Handle Errors Gracefully
Hooks should never crash your session. Use defensive programming:
## Error Handling Always wrap operations in error handling: - Try/catch for script execution - Default values for missing data - Clear error messages for failures - Graceful degradation when dependencies missingmarkdown
Document Your Hooks
Add comments explaining what each hook does and why it exists. Future-you will thank you.
Test Incrementally
Add one hook at a time and verify it works before adding more. This makes debugging much easier.
Performance Considerations
Claude Code hooks run during your session, so performance matters.
Keep SessionStart Hooks Fast
SessionStart hooks block your first interaction. Keep them under 2 seconds:
- Avoid network calls in SessionStart
- Cache results when possible
- Use background execution for slow operations
Limit PostToolUse Frequency
PostToolUse hooks run after every matched tool use. Avoid:
- Expensive operations on every edit
- Network calls for trivial changes
- Complex analysis on every file write
Use Appropriate Timeouts
Set timeouts for hook execution to prevent hangs:
--- event: SessionStart timeout: 10 ---markdown
Security Best Practices
Hooks can access and modify your files, so security is critical.
Validate File Paths
Always validate file paths before operations:
## Path Validation Before any file operation: 1. Check path is within allowed directories 2. Reject absolute paths outside project 3. Block path traversal attempts (../) 4. Verify file extensions are expectedmarkdown
Scan for Secrets
When hook processes files, check for sensitive data:
- API keys and tokens
- Passwords and credentials
- Certificate files
- Configuration with secrets
Principle of Least Privilege
Configure hooks with minimum necessary permissions:
- Read-only hooks for analysis
- Write hooks only for specific paths
- No network access unless required
Common Issues and Solutions
| Problem | Solution |
|---|---|
| Hook not executing | Verify plugin manifest path and restart Claude Code |
| Hook executes too often | Narrow the matcher pattern to be more specific |
| SessionStart slows startup | Move slow operations to background or cache results |
| Hook causes crashes | Add error handling and validation to all operations |
| Multiple hooks conflict | Use unique hook names and document interactions |
| Team hooks not loading | Check file permissions and verify repository structure |
When troubleshooting Claude Code hooks, always check the plugin manifest first and verify the hook file has the correct event frontmatter.
Conclusion
Claude Code hooks transform the tool from a capable assistant into a customized automation platform. By investing time in Claude Code hooks configuration, you create a development environment that adapts to your workflow, enforces standards automatically, and eliminates repetitive tasks.
The key takeaways from this guide on Claude Code hooks:
- Claude Code hooks execute automatically at defined points in your session
- Start simple with SessionStart hooks and gradually add complexity
- Use specific matchers to target exactly the operations you want to automate
- Consider performance to avoid slowing down your development workflow
- Share configurations across your team for consistent practices
- Test incrementally to isolate issues and build reliable automation
As you continue developing with Claude Code, revisit your Claude Code hooks configurations regularly. Your needs will evolve, and your Claude Code hooks should evolve with them. The most effective Claude Code hook setups are refined over time based on actual usage patterns and pain points.
For more Claude Code productivity techniques, check out our guide on Claude Code tips and tricks. To extend Claude's capabilities with external tools, see our complete guide to MCP servers or explore the best MCP servers for Claude Code. For a comparison of AI coding assistants, read our Claude Code vs OpenAI Codex analysis.
Related Resources
- Claude Code Documentation - Official Claude Code guides
- Plugin Development Guide - Building custom plugins
- Model Context Protocol - MCP specification for external tools