Skip to content
explainroo
Working with AI agents

Claude Code Hooks: How They Work, with Examples

Updated 4 min read

With explainroo How to Prompt a Coding Agent to Make an Explainer Video
On this page
  1. When hooks run and what they receive
  2. Where to configure hooks
  3. Examples that automate common tasks
  4. Keep hooks narrow and test their results

When you use Claude Code to edit files or run commands, hooks let you run your own code at specific points in the session. A hook is a rule that Claude Code runs when an event occurs, such as before a tool call or after an edit. Because a hook runs as code outside Claude’s reasoning, it applies checks and actions consistently instead of depending on Claude to remember an instruction.

Hooks work well for tasks such as formatting edited files, blocking changes to protected paths, and sending notifications. They are configured in Claude Code settings as shell commands or other supported hook types. Hooks can enforce project rules, but shell-script checks do not provide a security boundary.

When hooks run and what they receive

Claude Code uses event names to mark points in a session. PreToolUse runs before a tool acts, so a hook can check or block the action. PostToolUse runs after a tool succeeds, making it a good place for formatting or logging. Other events include SessionStart and UserPromptSubmit, as well as Stop and Notification. PreCompact runs around context compaction. The Claude Code hooks documentation lists supported events and their details.

A hook configuration connects an event to one or more commands. A matcher narrows which events trigger a hook. For example, Write|Edit matches those tool names, while an empty matcher applies to every event of that type. Tool names are case-sensitive.

When a hook runs, Claude Code sends event data as JSON on standard input. A command hook can read fields such as the tool name and the target file path with a utility like jq. Matching hooks run in parallel, so do not rely on one hook finishing before another begins.

Claude Code uses exit codes to interpret command-hook results: exit code 0 allows the action to proceed, 2 blocks it, and 1 reports a non-blocking error. For a PreToolUse hook intended to enforce a rule, use exit code 2 when the hook rejects an action.

Where to configure hooks

You can configure hooks for your account in ~/.claude/settings.json, for a project in .claude/settings.json, or locally in .claude/settings.local.json. You can share project settings through version control. Keep local settings uncommitted for project-specific configuration. The official setup examples show how event names, matchers, and commands fit together.

A project-level formatter hook, for example, can be configured like this:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "file=$(jq -r '.tool_input.file_path // empty'); if [ -n \"$file\" ]; then npx prettier --write \"$file\"; fi"
          }
        ]
      }
    ]
  }
}

This runs Prettier after successful Write and Edit tool calls. It assumes the project has Prettier available through npx. The hook reads the edited file path from the event data, then passes the path as a quoted argument. When the hook succeeds, the file appears reformatted.

Examples that automate common tasks

Block edits to protected files

Use PreToolUse to check a file path before an edit or write proceeds. This example blocks changes to .env, package-lock.json, and files inside .git:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

Save the following script as .claude/hooks/protect-files.sh and make it executable:

#!/bin/sh

file=$(jq -r '.tool_input.file_path // empty')

case "$file" in
  .env|*/.env|package-lock.json|*/package-lock.json|.git/*|*/.git/*)
    echo "Blocked: this file is protected." >&2
    exit 2
    ;;
esac

exit 0

When the script exits with 2, Claude Code blocks the matched tool action and shows the message as feedback. Adjust the patterns for your project. This example checks path strings, but it does not securely validate every path. For example, it does not check for symbolic links.

Notify yourself when Claude needs input

A Notification hook can run a desktop notification command when Claude Code asks for attention. The command depends on the operating system: for example, macOS supports osascript, while Linux commonly uses notify-send. An empty matcher runs for all notification types; a specific matcher lets you respond only to a type such as permission_prompt. Check the hook documentation for supported notification matchers and version requirements.

Restore context after compaction

A SessionStart hook with a compact matcher can print important context to standard output after Claude Code compacts its conversation. Claude Code adds that text to the session context. This is useful for information that should remain available after compaction, such as project-specific instructions that are not otherwise loaded at session start.

Keep hooks narrow and test their results

Match only the tools and events the hook needs. A broad matcher can run a command more often than intended, and broad permission hooks are especially risky if they approve actions automatically. Start with a narrow matcher, then test both the expected result and a rejected case.

Hooks are useful guardrails, but they do not replace Claude Code’s permissions, sandboxing, or careful handling of credentials. A hook that checks command text or file paths does not guarantee that it will catch every risky action. Security guidance describes hooks as guardrails rather than walls; keep permissions limited and avoid exposing secrets unnecessarily.

If a hook returns a structured permission decision such as allow, deny, or ask, verify the response format in the current documentation and test the hook in your installed version. A Claude Code issue reports conflicting response-schema guidance for different hook events.

Free and open source

Let your AI agent make the video

explainroo lets a coding agent like Claude Code or Codex make narrated explainer videos and product demos. The voice, the word timing and the rendering run on your own computer, with no API key and no cost per video. Optional outside services use your own key.

Copy this into your AI agent

Make me a short explainer video about [your topic]. Use explainroo for it: run npx --yes explainroo docs and follow what it prints.

Getting started Example videos GitHub

Made with explainroo: How explainroo makes a video

More on working with ai agents

All guides on working with ai agents