Reviewed by Jonathan West · Updated Jul 27, 2026

Claude Code Hooks Explained

Shell scripts that run automatically before, during, and after Claude Code actions to enforce formatting, testing, and safety rules.

Reviewed by Jonathan West · Updated Jul 27, 2026

Claude Code hooks are shell commands that fire automatically when the agent does something. They run your code before a tool executes, after a file changes, or when the agent finishes a task. No manual step required.

Hooks solve a specific problem: you want Claude Code to always format files after editing, run tests after touching certain code, or block dangerous commands before they execute. Without hooks, you rely on memory and discipline. With hooks, the guardrails are automatic.

This guide covers the four hook types, how to configure them in settings.json, real examples for common workflows, and the line between hooks and other Claude Code features like skills and subagents.


What Claude Code hooks are

Hooks are shell commands that run in response to Claude Code events. You define them in .claude/settings.json under the hooks key. Each hook specifies when it runs, which tools trigger it, and what command to execute.

Think of hooks as git hooks for AI agents. Git hooks run scripts before or after commits. Claude Code hooks run scripts before or after the agent uses tools like Edit, Write, or Bash. The agent does not choose whether to run them. They fire automatically based on your configuration.

Hooks receive JSON on standard input with context about the event: the tool name, the input parameters, and for PostToolUse hooks, the output. Your script can read this JSON, make a decision, and either succeed silently or exit with a code that blocks the action.

  • Defined in .claude/settings.json under the hooks key.
  • Fire automatically. The agent does not decide whether to run them.
  • Receive JSON on stdin with tool name, inputs, and outputs.
  • Exit codes control behavior: 0 passes, 2 blocks the action.

Need Claude Code hooks configured for your team's formatting, testing, and security policies? We design the hook system and test it before rollout.

Book a Consultation

Four types of Claude Code hooks

PreToolUse hooks run before a tool executes. They can inspect the planned action and block it. If your script exits with code 2, Claude Code cancels the tool call entirely. Use PreToolUse to prevent dangerous commands, block edits to protected files, or validate inputs before they reach the tool.

PostToolUse hooks run after a tool succeeds. They see both the input and the output. Use PostToolUse to auto-format code after edits, run tests after file changes, update documentation after schema modifications, or log completed actions for audit.

Notification hooks run when Claude Code sends status updates. These fire on progress messages, errors, and warnings. Use them to pipe agent activity to Slack, a log file, or a monitoring dashboard.

Stop hooks run when the agent finishes its current task. The agent is done working but has not returned control to you yet. Use Stop hooks to run a final test suite, generate a summary, send a completion alert, or clean up temporary files.

  • PreToolUse: runs before the tool. Exit code 2 blocks the action.
  • PostToolUse: runs after the tool succeeds. Good for formatting and testing.
  • Notification: runs on agent status changes. Good for alerts and logging.
  • Stop: runs when the agent finishes. Good for final checks and notifications.

How to configure hooks in settings.json

Hook configuration lives in .claude/settings.json at the project level or ~/.claude/settings.json globally. Each hook entry has a type, an optional matcher, and a command to run.

Matchers filter which tools trigger the hook. Without a matcher, the hook fires on every tool call of that type. With a matcher, it only fires when the tool name matches. For example, a PostToolUse hook with a matcher for Edit and Write will only run after file modifications, not after Bash or Read calls.

The command is any shell command. It runs in the project root directory. Complex logic can call a script file. Keep hook scripts fast because they run synchronously. A hook that takes ten seconds to complete will add ten seconds to every matching tool call.

  • Type: PreToolUse, PostToolUse, Notification, or Stop.
  • Matcher: optional tool name filter. Supports Edit, Write, Bash, and other tool names.
  • Command: any shell command. Runs in the project root.
  • Speed matters: hooks run synchronously. Slow hooks slow every tool call.

Claude Code hooks real examples

Auto-format after edits is the most common hook. A PostToolUse hook matched to Edit and Write runs prettier or black on the changed file. Claude Code edits a file, the hook formats it, and the result is always clean. No reminder needed.

Run tests after changes is the second most common pattern. A PostToolUse hook matched to Edit checks if the changed file is in the src directory, then runs the relevant test suite. If tests fail, the agent sees the failure output and can self-correct.

Block dangerous commands with a PreToolUse hook matched to Bash. Your script reads the JSON input, checks the command string for patterns like rm -rf, DROP TABLE, or force push, and exits with code 2 to block them. The agent gets a message explaining why the command was blocked.

Send a Slack notification on completion with a Stop hook. When the agent finishes, your script calls the Slack webhook API with a summary of what changed. Your team sees the update without checking the terminal.

  • PostToolUse + Edit: run prettier --write on the changed file path.
  • PostToolUse + Edit: run pytest on the matching test file.
  • PreToolUse + Bash: block commands matching rm -rf or git push --force.
  • Stop: curl a Slack webhook with a completion summary.
  • PreToolUse + Write: reject writes to .env, credentials, or key files.

Hooks vs skills: when to use each

Hooks enforce rules. Skills teach workflows. The distinction is simple but teams often confuse them.

A hook runs automatically and the agent cannot skip it. Use hooks for things that must always happen: formatting, testing, security blocks, logging. These are policy controls that apply regardless of what the agent is trying to do.

A skill is a set of instructions the agent follows when performing a specific task. Use skills for repeatable workflows like writing a migration, creating a component, or deploying to staging. The agent reads the skill and follows the steps. Skills are optional and task-specific.

A common mistake is putting workflow logic in hooks. If you find yourself writing a hook that only makes sense for one type of task, it should be a skill instead. Hooks should be universal guardrails, not task-specific instructions.

  • Hooks: mandatory, automatic, policy-driven. Cannot be skipped.
  • Skills: optional, task-specific, instruction-driven. Agent follows when relevant.
  • Use hooks for formatting, testing, security, and logging.
  • Use skills for deployment procedures, code generation patterns, and review checklists.

Security implications of Claude Code hooks

Hooks run with your user permissions on your machine. A hook can execute any command you can. That power is the point, but it requires care.

Review every hook command before adding it. A hook that runs an arbitrary script from a downloaded repo is a supply chain risk. Pin hook scripts to your own repository and review changes to them like you review production code.

PreToolUse hooks with exit code 2 are your strongest guardrail. They completely prevent the agent from taking an action. Use them for hard security rules: never write to production config files, never run commands with sudo, never push to main without a branch. These rules are more reliable than prompt instructions because the agent cannot override them.

Test hooks in a sandbox first. A misconfigured hook can block all tool calls (matcher too broad) or silently pass everything (wrong exit code). Run Claude Code on a test task with your hooks enabled before using them on real work.

  • Hooks run with your user permissions. They can do anything you can.
  • Review hook scripts like production code. Never run unreviewed third-party scripts.
  • PreToolUse with exit code 2 is the strongest agent guardrail available.
  • Test hooks in a sandbox before production use.

Advanced hook patterns for teams

Conditional hooks parse the JSON input to make decisions. A PostToolUse hook can check if the edited file is a migration, and only run database validation for migrations. This keeps hooks fast for unrelated file changes.

Chained hooks combine multiple checks. A PostToolUse hook for Edit can run formatting first, then linting, then type-checking. If any step fails, the agent sees the error and can fix it. Order the chain from fastest to slowest so failures surface quickly.

Team-shared hooks belong in .claude/settings.json inside the repo so every team member gets the same guardrails. Developer-specific hooks go in ~/.claude/settings.json. A good split: security and formatting hooks are team-shared, notification hooks are personal.

Audit hooks log every tool call to a file or external service. A PostToolUse hook with no matcher writes the tool name, inputs, timestamp, and user to a log. This creates a complete record of what the agent did in a session.

  • Conditional: parse stdin JSON to only act on certain file types or paths.
  • Chained: run format, then lint, then type-check in sequence.
  • Team-shared: security and formatting hooks in project .claude/settings.json.
  • Personal: notification and preference hooks in ~/.claude/settings.json.
  • Audit: log every tool call to a file for compliance and review.

Troubleshooting Claude Code hooks

Hooks that do not fire usually have a matcher problem. Check that the tool name in your matcher exactly matches the Claude Code tool name. Tool names are case-sensitive: Edit is correct, edit will not match.

Hooks that block everything usually have an exit code problem. If your script exits with a non-zero code by default (a failing grep, an unhandled error), PreToolUse treats it as a block. Make sure your script exits 0 for pass and 2 for block, with no other non-zero exits.

Slow hooks are often doing too much. If your PostToolUse hook runs the entire test suite after every edit, agent speed drops. Filter by file path in the hook script so tests only run for relevant changes. Or move expensive checks to a Stop hook so they run once at the end.

Debug hooks by adding logging. Write stdin JSON and your script's decision to a log file. Review the log to see what the hook received and why it made its decision.

  • Not firing: check tool name case sensitivity in matchers.
  • Blocking everything: check for unhandled non-zero exit codes.
  • Slow performance: filter by file path or move to Stop hook.
  • Debugging: log stdin JSON and decisions to a file.

Frequently Asked Questions

  • Yes. A PreToolUse hook matched to the Bash tool can inspect the command before it runs. If your script exits with code 2, Claude Code cancels the command entirely. This is the strongest guardrail available, more reliable than prompt instructions.
  • Hooks run synchronously, so a slow hook slows every matching tool call. Keep hooks fast by filtering with matchers and doing minimal work in the script. Move expensive operations like full test suites to Stop hooks so they run once at the end.
  • Hooks are automatic guardrails that the agent cannot skip. They enforce rules like formatting and security. Skills are optional instruction sets for specific tasks like deployment or code review. Use hooks for policies and skills for procedures.
  • Yes. Put team hooks in .claude/settings.json in your repo and commit the file. Every team member who clones the repo gets the same hooks. Keep personal preference hooks in ~/.claude/settings.json instead.
  • Yes. Hooks fire on tool calls regardless of whether the main agent or a subagent triggered them. A PreToolUse hook that blocks writes to .env files will block both the main agent and any subagent from writing to those files.

Want Hooks Configured for Your Team's Workflow?

Layer3 Labs sets up Claude Code hooks for formatting, testing, security, and compliance so your team gets automatic guardrails from day one.

Book a Free AI Workflow Audit