Hooks & Automation

Hooks are shell commands that Claude Code runs automatically in response to specific events. They let you inject custom logic — linting, formatting, notifications, validation — into the assistant's workflow without manual intervention.

How Hooks Work

You define hooks in your Claude Code settings. Each hook specifies an event type and a command to run. When that event fires, Claude executes your command and incorporates the result into its workflow.

Hook Event Types

EventWhen It Fires
PreToolUseBefore Claude calls a tool (e.g., before editing a file)
PostToolUseAfter a tool call completes successfully
NotificationWhen Claude sends a notification to the user
StopWhen Claude finishes its response

Configuration

Add hooks to your settings file under the hooks key. Each hook needs a type, an optional matcher to filter which tools trigger it, and the command to execute.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "npx eslint --fix $CLAUDE_FILE_PATH"
      }
    ],
    "Notification": [
      {
        "command": "terminal-notifier -message \"$CLAUDE_NOTIFICATION\""
      }
    ]
  }
}

Environment Variables in Hooks

Claude injects context-specific environment variables that your hook commands can use:

VariableDescription
$CLAUDE_FILE_PATHPath of the file being read or written
$CLAUDE_TOOL_NAMEName of the tool being called
$CLAUDE_NOTIFICATIONNotification message text
$CLAUDE_PROJECT_DIRRoot directory of the current project

Example: Auto-Lint on File Save

This hook runs ESLint with auto-fix every time Claude writes or edits a file:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "cd $CLAUDE_PROJECT_DIR && npx eslint --fix \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
      }
    ]
  }
}

Example: Desktop Notification on Completion

Get a macOS notification whenever Claude finishes a long task:

{
  "hooks": {
    "Stop": [
      {
        "command": "osascript -e 'display notification \"Claude has finished\" with title \"Claude Code\"'"
      }
    ]
  }
}

Use Cases

  • Code quality — Run linters and formatters after every file change.
  • Testing — Trigger relevant unit tests after code modifications.
  • Notifications — Alert yourself when long-running tasks complete.
  • Validation — Block tool calls that do not meet project requirements.
  • Logging — Record tool usage for audit or debugging purposes.

Best Practices

  • Keep hooks fast. Slow hooks delay Claude's workflow. Aim for sub-second execution.
  • Fail gracefully. Append || true to prevent hook failures from breaking the flow.
  • Test hooks independently. Run your hook command manually before adding it to config.
  • Use matchers. Narrow hooks to specific tools to avoid unnecessary execution.

Hooks give you fine-grained control over Claude's behavior, turning it into an automated development pipeline tailored to your project.