株式会社オブライト
Software Development2026-03-08

Complete Guide to Claude Code Hooks — Maximizing Development Efficiency Through Automation and Workflow Customization

A comprehensive guide to Claude Code Hooks covering all event types and practical applications. Learn implementation patterns for auto-formatting, lint checks, security protection, and automated testing using SessionStart, PreToolUse, and PostToolUse events.


What Are Hooks — Guaranteed Execution at Lifecycle Points

Claude Code Hooks are mechanisms that automatically execute commands or checks at specific points in the AI agent's execution lifecycle. Unlike system prompts, Hooks provide 'guaranteed execution' rather than 'instructions to the LLM.' They're ideal for automation tasks requiring certainty—ensuring formatters run on file saves, enforcing lint checks before commits, or reliably blocking dangerous commands. Enterprise development teams in Shinagawa and Minato wards have achieved approximately 40% reduction in QA check workload during code reviews by implementing Hooks.

Hook Event Types — Six Lifecycle Trigger Points

Claude Code supports Hooks at six event timings: 1. **SessionStart** - At session initialization. Used for environment checks, dependency validation, and project-specific setup. 2. **UserPromptSubmit** - Immediately after user submits a prompt. Useful for content filtering and logging. 3. **PreToolUse** - Just before tool execution. Used for pre-execution checks on Bash, Edit, Write, and other specific tools. 4. **PostToolUse** - After successful tool execution. Applied for auto-formatting after file saves, test execution, etc. 5. **PostToolUseFailure** - When tool execution fails. Useful for error logging and retry logic implementation. 6. **SessionEnd** - At session termination. Used for resource cleanup and report generation. Combining these events enables comprehensive automation of the entire development workflow.

Three Hook Types — Command, Prompt, and Agent

Hooks come in three implementation types: **Command type** - Directly executes shell commands. Ideal for deterministic operations like `prettier --write {file}` or `npm test`. Lightest weight and fastest. **Prompt type** - Delegates judgment to the LLM. Used when decisions are needed: 'Is this code safe?' or 'Is this commit message appropriate?' Offers high flexibility but incurs API costs, requiring caution for frequently triggered Hooks. **Agent type** - Launches sub-agents for detailed verification. Applied for complex code reviews and security audits requiring deep analysis. A Shibuya-based startup implemented automated pull request reviews with agent-type Hooks, reducing average review wait time by 2 hours.

Configuration Method — Writing to .claude/settings.json

Hooks are configured in `.claude/settings.json` at the project root: ```json { "hooks": [ { "event": "PostToolUse", "tool": "Write", "type": "command", "command": "prettier --write {file}", "description": "Auto-format saved files" } ] } ``` **Matcher patterns** allow applying Hooks to specific files only: ```json { "tool": "Write", "matcher": "**/*.{js,ts,jsx,tsx}", "command": "eslint --fix {file}" } ``` The `{file}` placeholder automatically expands to the actual file path. Web production companies in Minato ward use this mechanism to standardize quality criteria across all projects.

Auto-Formatting on File Save — Leveraging PostToolUse

One of the most practical Hook patterns is auto-formatting on file save: ```json { "event": "PostToolUse", "tool": "Write|Edit", "type": "command", "matcher": "**/*.{js,ts,jsx,tsx}", "command": "prettier --write {file} && eslint --fix {file}" } ``` Immediately after the `Write` or `Edit` tool executes, prettier and ESLint run automatically. This ensures: - AI-generated code always complies with project coding standards - Manual formatting work becomes unnecessary - Zero style-related comments in code reviews A SaaS company in Shinagawa saved approximately 20 hours of work per month with this configuration.

Pre-Commit Lint Checks — Intercepting git commit with PreToolUse

The PreToolUse event enables enforcing lint checks before git commit execution: ```json { "event": "PreToolUse", "tool": "Bash", "matcher": "*git commit*", "type": "command", "command": "npm run lint-staged", "description": "Run lint checks before commit" } ``` If the command fails (exit code 1), git commit won't execute. This provides Husky and lint-staged equivalent functionality through Claude Code configuration alone. A Shibuya development team completely eliminated 'I'll fix lint issues later' pull requests with this mechanism.

Security Hooks — Detecting and Blocking Dangerous Commands

PreToolUse can block dangerous commands before execution: ```json { "event": "PreToolUse", "tool": "Bash", "matcher": "*rm -rf*|*git push --force*|*DROP TABLE*", "type": "prompt", "prompt": "This command is potentially dangerous. Analyze the context and confirm if it should be allowed.", "description": "Protect against destructive commands" } ``` Prompt-type Hooks enable the LLM to understand context and make judgments—allowing 'test directory cleanup' while blocking 'production data deletion.' A FinTech company in Minato ward reduced production environment misoperation risk to near zero with this configuration.

Automated Test Execution — Running Related Tests After File Edits

PostToolUse enables automatic execution of tests related to edited files: ```json { "event": "PostToolUse", "tool": "Edit", "matcher": "src/**/*.ts", "type": "command", "command": "npm test -- --findRelatedTests {file}", "description": "Run tests related to edited files" } ``` Using Jest's `--findRelatedTests` option runs only tests affected by changes, accelerating the feedback loop. A product development team in Shinagawa reduced regressions from 'forgetting to test after changes' by 80% with this configuration.

Prompt-Type Hook Applications — Advanced LLM-Based Judgment

Prompt-type Hooks enable flexible checks leveraging LLM reasoning capabilities: ```json { "event": "PreToolUse", "tool": "Bash", "matcher": "*npm install*|*yarn add*", "type": "prompt", "prompt": "Review the package being installed. Check for: 1) Known security vulnerabilities, 2) Suspicious package names (typosquatting), 3) License compatibility. Approve or reject with explanation.", "description": "Security review for new dependencies" } ``` However, prompt-type Hooks incur API costs per invocation, so best practice limits them to **low-frequency events** (dependency additions, pre-deployment checks). Engineering teams in Shibuya use prompt-type Hooks only for ~10 monthly dependency additions, keeping costs under $5/month.

MCP Integration Hook Patterns — Hooking MCP Tool Events

Tools provided by MCP servers can also trigger Hooks. Tool names follow the format `mcp__<server>__<tool>`: ```json { "event": "PostToolUse", "tool": "mcp__database__execute_query", "type": "command", "command": "echo 'Query executed: {args}' >> audit.log", "description": "Log all database queries" } ``` This enables automation and monitoring of all MCP-mediated operations: database operation audit logs, external API call rate limiting, filesystem access tracking, and more. Compliance-focused companies in Minato ward implement full data access logging through Hooks.

Team Hook Sharing — Version Controlling .claude/settings.json

Including `.claude/settings.json` in your Git repository enables sharing unified workflows across the entire team: ```bash # Project root ├── .claude/ │ └── settings.json # Team standard Hook configuration ├── .gitignore └── package.json ``` When new members clone the project, all Hooks automatically apply from their first Claude Code launch. A web development company in Shinagawa completely eliminated 'development environment setup oversights' during onboarding with this mechanism. **Example team standard Hook collection**: - Pre-commit lint - Auto-format on save - Security command blocking - Test execution after code changes - Dependency audit on package.json changes

Hook Development Best Practices

Best practices for effective Hook configuration: **1. Debugging** - Use `--verbose` flag to check Hook execution logs. Verify exit codes and stderr on failures. **2. Error Handling** - Use `continueOnError: true` option to prevent Hook failures from stopping entire sessions. **3. Performance** - Place heavy operations (full test runs, builds) in PostToolUse; keep PreToolUse for lightweight checks only. **4. Gradual Adoption** - Start with one Hook (auto-format), observe team reactions, then add more. **5. Documentation** - Enrich each Hook's `description` field and maintain a Hook list in README. Oflight in Shibuya and Minato wards supports Hook design optimized for your workflow.

Conclusion — Elevate Development Workflow with Hooks

Claude Code Hooks represent the 'standard equipment for automation' in AI agent development. By reliably executing formatting on file saves, pre-commit checks, security protection, and automated testing, they improve code review quality, reduce work time, and boost overall team productivity. Companies in Shinagawa, Minato, and Shibuya wards considering Claude Code adoption should consult Oflight Inc. We support enterprise-grade AI development environment construction—from Hook design and team standard formulation to CI/CD integration.

Feel free to contact us

Contact Us