Skip to content

Claude Code Complete Guide

Claude Code Hooks Revolution: A New Dimension in Development Workflow Automation [2025 Latest]

Introduction

Claude Code Hooks is a groundbreaking feature that brings deterministic control to AI-assisted development. While "lack of consistency" and "remaining manual work" have been persistent challenges in AI development support, Hooks enables full automation of these concerns.

The critical distinction is that Hooks are not chosen or triggered by the AI -- they are user-defined rules that execute reliably every time. This article covers all 14 event types and 3 handler types in Claude Code Hooks, with practical guidance for development workflow automation.

Key Points

  • Deterministic Automation Flow

    Reliably automate pre-commit quality checks, test execution, and deployment checks based on user-defined rules

  • Intelligent Code Formatting

    Automatically run Prettier, Black, and Ruff on file changes to maintain code quality

  • Security Enhancement

    Prevent unauthorized access to production files and detect secrets through pre-execution checks

  • Significant Development Efficiency Improvement

    Eliminate repetitive manual work so developers can focus on essential logic development

Claude Code Hooks: The Core of Next-Generation Development Automation

What Are Hooks?

Claude Code Hooks are user-defined shell commands or LLM prompts that automatically execute at specific points in Claude Code's lifecycle.

Deterministic Control - The Key Differentiator of Hooks

Hooks are NOT triggered by AI (LLM) judgment calls. They execute reliably and deterministically every time based on rules defined by the user in advance. This guarantees consistent quality control without depending on the variability of AI decision-making.

Configuration is in JSON format, written in ~/.claude/settings.json (user settings) or .claude/settings.json (project settings).

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "ruff check --fix $CLAUDE_FILE_PATHS && black $CLAUDE_FILE_PATHS"
          }
        ]
      }
    ]
  }
}

All 14 Event Types

Claude Code Hooks supports 14 event types, each corresponding to a different point in the development lifecycle.

Session Management

EventTimingUse Case
SessionStartWhen a session startsEnvironment setup, dependency checks
SessionEndWhen a session endsCleanup, logging

User Input

EventTimingUse Case
UserPromptSubmitWhen a user prompt is submittedInput validation, context augmentation

Tool Execution Lifecycle

EventTimingUse Case
PreToolUseBefore tool executionFile protection, operation blocking
PermissionRequestWhen permission is requestedEnhanced access control
PostToolUseAfter tool execution (on success)Formatting, testing, quality checks
PostToolUseFailureAfter tool execution failsError handling, notifications

Agent Management

EventTimingUse Case
SubagentStartWhen a subagent startsSubagent configuration
SubagentStopWhen a subagent stopsResult processing
TeammateIdleWhen a teammate becomes idleResource management

Task Completion and Notifications

EventTimingUse Case
StopWhen response stopsPost-processing execution
TaskCompletedWhen a task completesCompletion notifications, report generation
NotificationWhen a notification is triggeredSlack notifications, email sending

Memory Management

EventTimingUse Case
PreCompactBefore context compactionPreserving important information

Three Hook Handler Types

Each hook supports three handler types, used according to the specific need.

1. command - Shell Command Execution

The simplest type. Executes shell commands directly.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "ruff check --fix $CLAUDE_FILE_PATHS"
          }
        ]
      }
    ]
  }
}

2. prompt - Single-Turn LLM Evaluation

Sends a prompt to the LLM, which returns a judgment in the format {ok: true/false, reason: "..."}. Ideal for code review and policy checks.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review the proposed changes. Reject if they modify production database connection strings or contain hardcoded credentials."
          }
        ]
      }
    ]
  }
}

3. agent - Multi-Turn Subagent

Launches a subagent with tool access (Read, Grep, Glob) for more complex analysis and cross-file checks.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "agent",
            "prompt": "Check if the edited files follow the project's coding conventions by reading .editorconfig and comparing with the changes. Report any violations."
          }
        ]
      }
    ]
  }
}

Practical Hook Configuration Examples

1. Complete Automation for Python Development

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "ruff check --fix $CLAUDE_FILE_PATHS && black $CLAUDE_FILE_PATHS && isort $CLAUDE_FILE_PATHS"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bandit -r $CLAUDE_FILE_PATHS -ll -q"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "pytest --tb=short -q && coverage report --show-missing"
          }
        ]
      }
    ]
  }
}

2. TypeScript/React Project Configuration

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write $CLAUDE_FILE_PATHS && eslint --fix $CLAUDE_FILE_PATHS && tsc --noEmit"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm run test -- --passWithNoTests"
          }
        ]
      }
    ]
  }
}

3. Security Hardening Configuration

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "git secrets --scan $CLAUDE_FILE_PATHS || (echo 'Secret detected! Blocking operation.' && exit 1)"
          },
          {
            "type": "prompt",
            "prompt": "Review the proposed file changes. Reject if they contain API keys, tokens, passwords, or any hardcoded credentials. Also reject changes to production configuration files."
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Security hooks active. All file modifications will be scanned for secrets.'"
          }
        ]
      }
    ]
  }
}

Security Considerations

Hook Execution Permissions

Be Aware of Hook Execution Permissions

Hooks execute with the user's full permissions. This means commands configured in hooks have the same privileges as commands run directly in the terminal. Only configure trusted commands.

Hook Snapshots

As a security measure, hook configurations are captured as a snapshot at session startup. This means that even if hook settings are modified during a session, those changes will not take effect in the current session. This prevents malicious code from tampering with hook settings mid-session.

Enterprise Management

When operating Claude Code within an organization, the allowManagedHooksOnly setting can be used to block user-defined, project-defined, and plugin-defined hooks, allowing only administrator-approved (managed) hooks and SDK hooks.

{
  "allowManagedHooksOnly": true
}

This enables enforcement of unified security policies and code quality standards across the entire organization.

Integration with CI/CD Pipelines

Development Flow with Claude Code Hooks

Claude Code Hooks enhances the local AI development environment and maximizes effectiveness when combined with existing CI/CD pipelines.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Check if the changes follow the project's contribution guidelines. Verify that appropriate tests exist for new functionality."
          }
        ]
      }
    ],
    "TaskCompleted": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm run lint && npm run test && echo 'All checks passed - ready for CI/CD pipeline'"
          }
        ]
      }
    ]
  }
}

Real Development Flow Example

graph TD
    A[Developer implements with Claude Code] --> B[SessionStart: Environment Check]
    B --> C[PreToolUse: File Protection & Security]
    C --> D[Tool Execution: Code Generation & Editing]
    D --> E[PostToolUse: Formatting & Linting]
    E --> F[Stop: Test Execution]
    F --> G[TaskCompleted: Completion Notification]
    G --> H[git push to CI/CD Pipeline]
    H --> I[PR Creation, Review & Merge]

Development Improvement Benefits from Hooks

Qualitative Improvements

The following improvements can be expected from adopting Claude Code Hooks.

Quality Improvements

  • Complete code style unification: Formatters run automatically on every file change, eliminating style inconsistencies
  • Early security risk detection: Block secret injection and erroneous production config changes before tool execution
  • Reliable test execution: Tests run automatically with every code change, eliminating forgotten test runs

Efficiency Improvements

  • Elimination of repetitive manual work: Manual steps like running formatters, checking linters, and executing tests become unnecessary
  • Shortened feedback loops: Quality checks happen simultaneously with code changes, accelerating problem detection and resolution
  • Reduced CI/CD rework: Pre-checks at the local level significantly reduce failures in CI pipelines

Quick Start Guide

Step 1: Configure Claude Code Hooks

Write the following in your user settings file (~/.claude/settings.json).

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write $CLAUDE_FILE_PATHS || black $CLAUDE_FILE_PATHS"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm test || pytest -x"
          }
        ]
      }
    ]
  }
}

For project-specific settings, write the configuration in .claude/settings.json at the project root.

Step 2: Verify the Configuration

# Simple file edit with Claude Code
claude "Create a simple Python function to calculate fibonacci"

# Verify hooks execute automatically
# -> PostToolUse: Formatting applied
# -> Stop: Tests run

Step 3: Roll Out to the Entire Project

// .claude/settings.json (project root)
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Project hooks loaded. Python formatting and testing enabled.'"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "ruff check --fix $CLAUDE_FILE_PATHS && black $CLAUDE_FILE_PATHS"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "git secrets --scan $CLAUDE_FILE_PATHS 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Advanced Usage Patterns

1. Multi-Environment Hooks

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "ENV=$(git branch --show-current); case $ENV in main) npm run test:all && npm run security:audit;; staging) npm run test:integration;; *) npm run test:unit;; esac"
          }
        ]
      }
    ]
  }
}

2. Code Review with Prompt Handler

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review the code changes for: 1) Potential performance issues 2) Missing error handling 3) Violation of SOLID principles. Approve only if all checks pass."
          }
        ]
      }
    ]
  }
}

3. Project Consistency Check with Agent Handler

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "agent",
            "prompt": "Read the project's CONTRIBUTING.md and check if the recent changes follow the documented conventions. Also verify that any new public functions have corresponding test files."
          }
        ]
      }
    ]
  }
}

Future Outlook

Evolution of the Hooks Ecosystem

Claude Code Hooks is expected to continue evolving as a foundation for development workflow automation.

  • Expanded event types: From the current 14 types to finer-grained development lifecycle coverage
  • Handler type evolution: Enhanced capabilities for the agent type enabling more advanced automated analysis
  • Strengthened enterprise features: Cross-organizational hook management and policy enforcement

Summary

Claude Code Hooks is a groundbreaking feature that adds a deterministic control layer to AI-assisted development.

  • Deterministic execution: User-defined rules execute reliably every time, without depending on AI judgment
  • 14 event types: Full development lifecycle coverage from session management to task completion
  • 3 handler types: command (shell commands), prompt (LLM evaluation), and agent (subagent) -- chosen according to the use case
  • Security-focused: Safe operation through snapshot mechanisms and enterprise management
  • Quality standardization: Complete automation of formatting, testing, and security checks

Combining Hooks with CI/CD pipelines enables consistent quality management from local development through deployment.

Getting Started Tips

We recommend starting with automatic formatter execution on PostToolUse, then gradually expanding to security checks with PreToolUse and code review with prompt handlers.