Guides

Claude Code Hooks Explained, With Working Examples

A Claude Code hook is a command that Claude Code runs on its own at a set moment, such as before a tool call, after a file edit, or when a session needs your input. You define hooks in a settings file. Use them for things that must happen every time, with no reliance on the model remembering to do them.

What hooks are for

An instruction in a prompt is a request. The model usually follows it, but nothing forces it to. A hook is different: Claude Code itself runs the command, so the result is the same on every run.

Gander

See every Claude Code session on one screen, get pinged when one needs you, track what it costs, and stop a bad command before it runs.

Open it freeRead about it

Typical uses:

  • Format a file each time Claude edits it.
  • Block edits to files that must not change.
  • Send a desktop notification when a session waits for you.
  • Add project reminders to the context when a session starts.
  • Feed session activity to a log or a dashboard.

The hook events you will use most

Each hook is tied to an event. Claude Code has more than thirty of them. These are the ones most setups start with:

EventWhen it fires
SessionStartWhen a session begins or resumes
UserPromptSubmitWhen a prompt is submitted, before Claude processes it
PreToolUseBefore a tool call runs. It can block the call.
PostToolUseAfter a tool call succeeds
NotificationWhen Claude Code sends a notification, for example when it waits for input or permission
StopWhen Claude finishes responding
SubagentStopWhen a subagent finishes
PreCompactBefore context compaction
SessionEndWhen a session ends

The full list is in the hooks reference in the official Claude Code documentation. Type each event name exactly as shown.

Where hooks live

Hooks go in a hooks block inside a settings file. The file you pick sets the scope.

FileScope
~/.claude/settings.jsonAll your projects, on your machine only
.claude/settings.jsonOne project. You can commit it, so the team shares it.
.claude/settings.local.jsonOne project, for you only

Plugins can also bring their own hooks, in a hooks/hooks.json file inside the plugin.

The shape of a hook

The config has three levels: the event, a matcher group, and one or more handlers.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/lint-check.sh"
          }
        ]
      }
    ]
  }
}
  • The event name is a key inside the single hooks object. To add a second event, add a second key next to the first.
  • The matcher filters when the hook fires. For PreToolUse and PostToolUse it matches the tool name. Edit|Write means either tool. An empty string, "*" or no matcher means match everything.
  • The handler says what to run. "type": "command" runs a shell command. Other types exist, including http, which posts the event to a URL, and prompt, which asks a Claude model to decide.

How a hook talks to Claude Code

A command hook receives the event as JSON on standard input. Every event includes fields such as session_id, cwd and hook_event_name. Tool events add tool_name and tool_input.

The exit code of your command is the answer:

Exit codeMeaning
0Success. The action goes ahead.
2Blocking error. On events that can block, Claude Code stops the action and passes your stderr text to Claude as the reason.
Any otherNon-blocking error. The action goes ahead.

Example 1: a notification when Claude needs you

Add this to ~/.claude/settings.json. The command shown is for Linux.

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
          }
        ]
      }
    ]
  }
}

On macOS, use this line as the command value:

"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

The empty matcher fires on every notification type. To narrow it, set the matcher to a type such as permission_prompt or idle_prompt.

Example 2: format every file Claude edits

This goes in .claude/settings.json in the project. It runs Prettier after each Edit or Write tool call. The command reads the file path from the input JSON with jq, so jq must be installed.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
          }
        ]
      }
    ]
  }
}

Example 3: block edits to protected files

A PreToolUse hook runs before the tool does, so it can stop the edit. Register a script in .claude/settings.json:

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

Save the script below as .claude/hooks/protect-files.sh. On macOS and Linux, make it executable with chmod +x.

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Normalize Windows backslash separators so the patterns below match
FILE_PATH="${FILE_PATH//\\//}"

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0

The script reads the JSON from standard input and pulls out the file path. If the path matches a protected pattern, it prints a message to stderr and exits with code 2. Claude sees the message and can change its approach.

This hook covers the Edit and Write tools only. Claude can still change a file with a shell command. Add permission deny rules or sandboxing if you need a stronger limit.

Check and debug your hooks

  1. Type /hooks at the Claude Code prompt. It opens a browser of the hooks Claude Code has loaded. Your hook should appear under its event.
  2. Check that the JSON is valid. Trailing commas and comments are not allowed.
  3. Run the command by hand in a terminal first. A command that fails there will fail as a hook.
  4. Check the matcher. It is case sensitive, so edit does not match the Edit tool.

A hook runs with your user account's rights. Read any hook before you add it, and review hooks in a project you did not write.

Hooks as a data feed

Because every event carries the session, the folder and the tool call, hooks are also how outside tools watch Claude Code. Gander, a free local dashboard, is fed by these hooks and shows every session on one screen. That helps most when you run several sessions at once.

Gander

See every Claude Code session on one screen, get pinged when one needs you, track what it costs, and stop a bad command before it runs.

Open it freeRead about it

Claude Code hooks automation settings.json AI agents
✉

Get new articles in your inbox

SCCM guides, AI tools, automation tips — sent when published. No spam.

Keep reading

Comments