Table of Contents
What are Kiro Hooks?
Kiro hooks are event-driven automation scripts that execute when specific events occur in your project. Think of them as GitHub Actions for your local development environment - they automate repetitive tasks and ensure consistent quality.
Unlike traditional build scripts or CI/CD pipelines, Kiro hooks run locally and leverage AI agents to intelligently respond to context changes. This means they can understand your code changes and take appropriate actions automatically.
Key Benefits
- Automatic testing - Run relevant tests when files change
- Live documentation - Keep docs synchronized with code
- Code quality - Enforce standards and best practices
- Security scanning - Detect vulnerabilities instantly
- Smart suggestions - Get AI-powered improvement recommendations
Hook Types & Triggers
Kiro supports multiple trigger types for different automation scenarios:
onSave
Triggers when files are saved. Perfect for instant feedback loops.
trigger: onSaveonCreate
Triggers when new files or folders are created. Great for scaffolding.
trigger: onCreateonDelete
Triggers when files are deleted. Useful for cleanup tasks.
trigger: onDeleteonCommit
Triggers before Git commits. Ideal for pre-commit validation.
trigger: onCommitonPush
Triggers before Git pushes. Perfect for final quality checks.
trigger: onPushonInterval
Triggers on schedule. Great for periodic maintenance tasks.
trigger: onIntervalCreating Your First Hook
Let's create a simple hook that runs tests automatically when you save JavaScript files:
# .kiro/hooks/test-on-save.yml
name: "Run Tests on Save"
description: "Automatically run relevant tests when JavaScript files are saved"
# Trigger configuration
trigger: onSave
pattern: "**/*.{js,ts,jsx,tsx}"
# AI agent instructions
action: |
Analyze the saved file and determine which tests should run.
Steps to follow:
1. Identify the file type and its purpose
2. Look for corresponding test files
3. Run the most relevant tests
4. Report results with clear pass/fail status
5. If tests fail, suggest potential fixes
Be concise but informative in your output.
Creating the Hook
To create this hook in your project:
- Open Command Palette (
Ctrl+Shift+P
) - Run "Kiro: Create Hook"
- Choose "onSave" trigger
- Set pattern to
**/*.{js,ts,jsx,tsx}
- Paste the action instructions
Testing Your Hook
To test the hook:
- Open any JavaScript or TypeScript file
- Make a small change (add a comment)
- Save the file (
Ctrl+S
) - Watch the hook execute in Kiro's output panel
Example Hook Output
๐ช Hook: Run Tests on Save
๐ File: src/components/Button.tsx
โ
Found test file: src/components/__tests__/Button.test.tsx
๐งช Running tests...
โ
PASS src/components/__tests__/Button.test.tsx
โ renders button with text
โ handles click events
โ applies correct styling
๐ Results: 3 passed, 0 failed
โฑ๏ธ Completed in 1.2s
Testing Automation Hooks
Here are proven hook patterns for different testing scenarios:
Unit Test Hook
# .kiro/hooks/unit-tests.yml
name: "Smart Unit Testing"
trigger: onSave
pattern: "**/*.{js,ts,jsx,tsx}"
throttle: 2000 # Wait 2 seconds for rapid saves
action: |
You are a testing expert. When a file is saved:
1. Analyze the saved file to understand its functionality
2. Look for existing test files in these patterns:
- Same directory: filename.test.js, filename.spec.js
- Test directory: __tests__/filename.test.js
- Tests directory: tests/filename.test.js
3. If tests exist:
- Run only the relevant test suite
- Report pass/fail status with details
- If failures occur, analyze and suggest fixes
4. If no tests exist:
- Suggest creating tests
- Provide a basic test template
5. For React components, prioritize testing:
- Rendering behavior
- Props handling
- Event interactions
- Accessibility
Integration Test Hook
# .kiro/hooks/integration-tests.yml
name: "API Integration Tests"
trigger: onSave
pattern: "**/api/**/*.{js,ts}"
action: |
You are an API testing specialist. For API-related files:
1. Identify the API endpoints or functions modified
2. Look for integration tests that cover these endpoints
3. Run integration test suites that test the modified code
4. Check for proper error handling and edge cases
5. Validate API contracts and response schemas
6. Test authentication and authorization if applicable
If tests pass: Report success with coverage details
If tests fail: Provide debugging information and suggested fixes
If no tests exist: Suggest integration test scenarios to create
CI/CD Integration Hooks
Automate your deployment pipeline with these CI/CD hooks:
Pre-Commit Quality Gate
# .kiro/hooks/pre-commit-gate.yml
name: "Pre-Commit Quality Gate"
trigger: onCommit
action: |
You are a code quality gatekeeper. Before allowing this commit:
1. **Linting**: Run ESLint/Prettier and report any violations
2. **Type Checking**: Run TypeScript compiler if applicable
3. **Tests**: Execute all tests related to changed files
4. **Security**: Scan for potential security vulnerabilities
5. **Performance**: Check for obvious performance issues
6. **Documentation**: Verify critical functions have JSDoc comments
Only allow commit if ALL checks pass.
For failures:
- List specific issues found
- Suggest automated fixes where possible
- Provide actionable next steps
For success:
- Summarize what was validated
- Highlight any improvements made
Build and Deploy Hook
# .kiro/hooks/build-deploy.yml
name: "Build and Deploy"
trigger: onPush
branch: ["main", "production"]
action: |
You are a deployment specialist. For pushes to production branches:
1. **Pre-Build Validation**:
- Verify all tests pass
- Check environment variables are set
- Validate build configuration
2. **Build Process**:
- Run production build command
- Check for build warnings or errors
- Verify build artifacts are created
3. **Deploy to Staging**:
- Deploy to staging environment
- Run smoke tests against staging
- Validate critical user paths
4. **Production Deploy** (if staging passes):
- Deploy to production
- Monitor for errors in first 5 minutes
- Report deployment status
Provide detailed logs and rollback instructions if anything fails.
Auto Documentation Hooks
Keep your documentation synchronized with your code automatically:
API Documentation Hook
# .kiro/hooks/api-docs.yml
name: "Auto API Documentation"
trigger: onSave
pattern: "**/api/**/*.{js,ts}"
action: |
You are a technical documentation expert. When API files change:
1. **Extract API Information**:
- Identify all endpoints (GET, POST, PUT, DELETE)
- Document request/response schemas
- Note authentication requirements
- List possible error codes
2. **Update Documentation**:
- Update the main API.md file
- Generate OpenAPI/Swagger specs if applicable
- Update postman collections
- Refresh example requests/responses
3. **Validate Documentation**:
- Ensure all endpoints are documented
- Check that examples are valid
- Verify schema definitions match code
4. **Generate Client SDKs** (if configured):
- Update TypeScript types
- Regenerate client libraries
- Update SDK documentation
Always maintain backward compatibility notes and version information.
Component Documentation Hook
# .kiro/hooks/component-docs.yml
name: "Component Documentation"
trigger: onSave
pattern: "**/components/**/*.{jsx,tsx,vue}"
action: |
You are a component documentation specialist. For UI components:
1. **Analyze Component**:
- Extract props interface/types
- Identify component variants and states
- Document accessibility features
- Note any hooks or context usage
2. **Generate Documentation**:
- Create/update component README
- Generate Storybook stories if missing
- Update props table with descriptions
- Create usage examples
3. **Visual Documentation**:
- Suggest screenshot scenarios
- Document responsive behavior
- Note theme/styling variations
- List browser compatibility
4. **Integration Examples**:
- Show common usage patterns
- Document integration with forms
- Provide accessibility examples
- Include testing recommendations
Focus on practical examples that help other developers use the component effectively.
Advanced Hook Patterns
Multi-Step Workflow Hook
# .kiro/hooks/feature-workflow.yml
name: "Complete Feature Workflow"
trigger: onCreate
pattern: "**/features/**/*"
action: |
You are a feature development orchestrator. When new feature files are created:
**Phase 1: Setup**
1. Analyze the feature structure and purpose
2. Create corresponding test files if missing
3. Set up Storybook stories for UI components
4. Initialize documentation templates
**Phase 2: Validation**
1. Check that feature follows project conventions
2. Verify proper TypeScript types are defined
3. Ensure accessibility considerations are included
4. Validate against design system standards
**Phase 3: Integration**
1. Update feature registry/index files
2. Add feature to routing if applicable
3. Update navigation/menu structures
4. Register with any feature flag systems
**Phase 4: Documentation**
1. Generate feature specification document
2. Create user documentation
3. Update API documentation if needed
4. Add to testing checklist
Provide a summary of all actions taken and next steps for the developer.
Security Scanning Hook
# .kiro/hooks/security-scan.yml
name: "Security Scanner"
trigger: onSave
pattern: "**/*.{js,ts,jsx,tsx,py,java,go}"
action: |
You are a security specialist. Scan the saved file for potential vulnerabilities:
**Code Analysis**:
1. Check for hardcoded secrets, API keys, or passwords
2. Identify SQL injection vulnerabilities
3. Look for XSS attack vectors
4. Check for insecure dependencies or imports
5. Validate input sanitization practices
**Authentication & Authorization**:
1. Verify proper authentication checks
2. Ensure authorization is implemented correctly
3. Check for privilege escalation issues
4. Validate session management
**Data Security**:
1. Check for proper data encryption
2. Verify secure data transmission
3. Ensure sensitive data isn't logged
4. Validate GDPR/privacy compliance
**Report Format**:
- ๐ด Critical: Immediate security risks
- ๐ก Medium: Potential security improvements
- ๐ข Good: Security best practices followed
For each issue, provide specific fix recommendations and code examples.
Hook Best Practices
Performance Considerations
Hooks count toward your monthly AI interaction limit. Use throttling and specific patterns to avoid excessive usage. Consider using throttle: 3000
for frequently triggered hooks.
Hook Configuration Guidelines
- Use specific patterns - Target exact file types instead of wildcards when possible
- Add throttling - Prevent rapid-fire execution during active editing
- Include descriptions - Document what each hook does for team members
- Test thoroughly - Verify hooks work across different project scenarios
- Version control - Commit hook configurations to share with your team
Action Writing Tips
- Be specific - Clear instructions produce better AI responses
- Include context - Explain the project structure and conventions
- Define success criteria - Specify what constitutes a successful execution
- Handle edge cases - Account for missing files, test failures, etc.
- Provide examples - Show the AI what good output looks like
Debugging Hook Issues
Common Hook Problems
- Hook not triggering - Check pattern syntax and file matching
- Slow execution - Add throttling or narrow the pattern scope
- Inconsistent results - Make action instructions more specific
- Resource usage - Monitor interaction counts in Kiro settings
Team Hook Management
# .kiro/hooks/team-config.yml
# Team-shared hook configuration
# Global settings for all team hooks
global:
throttle: 2000 # Default throttle for all hooks
timeout: 30000 # Maximum execution time
retries: 2 # Number of retries on failure
# Environment-specific overrides
environments:
development:
enabled: true
verbose: true
production:
enabled: false # Disable hooks in production
ci:
enabled: true
timeout: 60000 # Longer timeout for CI
# Team conventions
conventions:
test_patterns:
- "**/*.test.{js,ts}"
- "**/*.spec.{js,ts}"
- "**/__tests__/**/*"
documentation_patterns:
- "**/README.md"
- "**/docs/**/*.md"
- "**/*.mdx"
Next Steps
You're now ready to implement powerful automation with Kiro hooks! Start with simple testing hooks and gradually add more sophisticated workflows as your team becomes comfortable with the system.
- Try the basic test-on-save hook first
- Experiment with different trigger types
- Share successful hooks with your team
- Monitor usage and optimize patterns
Related Resources
- Getting Started with Kiro - Basic setup and first project
- Spec Writing Guide - Writing effective specs for features
- EARS Format Guide - Requirements syntax deep dive
- Kiro Cheat Sheets - Quick reference for all Kiro features