Hooks cookbook

Claude Code hooks cookbook: 8 recipes to paste into settings.json

Updated November 17, 202610 min read

Claude Code hooks are commands that Claude Code runs by itself at fixed moments: before a tool runs, after a file is edited, when Claude needs you, or when it tries to finish. You write them in a hooks block in a settings.json file. This cookbook starts with the hook events in plain words, then gives eight recipes based on Anthropic's own examples, each with JSON you can paste, and ends with a table of every event.

Hook events in plain words

SessionStart
A session starts, resumes, is cleared or has just been compacted. Text your hook prints is added to Claude's context.
UserPromptSubmit
You press Enter on a prompt, before Claude sees it. Can add context or block the prompt.
PreToolUse
Claude is about to use a tool, such as editing a file or running a command. The one hook that can stop the action before it happens.
PermissionRequest
Claude Code is about to show you a permission prompt. A hook can answer it for you.
PostToolUse
A tool call has just succeeded. Good for formatting or checking what changed. It cannot undo the action.
Notification
Claude Code sends a notification, for example because it needs approval or has been idle.
Stop
Claude finishes its reply. A hook can send it back to work.
SubagentStop
A helper subagent finishes its job.
PreCompact
The conversation is about to be summarised to free space.
SessionEnd
The session closes. Hooks here get only a short time to run.

Every hook follows the same shape in settings.json: the event name, then a matcher (which tools or types it applies to), then one or more handlers. You can put hooks in ~/.claude/settings.json (all your projects), .claude/settings.json (one project, shared through git) or .claude/settings.local.json (one project, only you). Plugins, skills and subagents can carry hooks too.

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolName or pattern",
        "hooks": [
          { "type": "command", "command": "your-command-here", "timeout": 30 }
        ]
      }
    ]
  }
}

If your file already has a hooks key, add new events inside it as siblings. Do not paste a second hooks block. Type /hooks in a session to see every hook Claude Code has loaded.

Recipe 1: a desktop alert when Claude needs you (Notification hook)

Paste this into ~/.claude/settings.json. The macOS version shows a notification in the corner of the screen:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

On Windows, use PowerShell. This opens a dialog box, which can appear behind your terminal:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
          }
        ]
      }
    ]
  }
}

On Linux, make the command notify-send 'Claude Code' 'Claude Code needs your attention'. An empty matcher fires on every notification type. Use permission_prompt to fire only when Claude needs approval, or idle_prompt for when Claude finished about 60 seconds ago and you have not typed since.

On a Mac, if nothing appears, run osascript -e 'display notification "test"' once in Terminal, then turn on notifications for Script Editor under System Settings, Notifications.

One session or ten: choosing how you get alerted

A Notification hook

You run one or two Claude Code sessions and are happy editing JSON. It is free and built in.

A Stop hook with a sound

You want a signal every time Claude finishes a reply, not only when it is waiting on you.

VibeCodingDeck

You run many sessions and need to know which one is waiting. Every pane has a status light (working, idle, waiting, done), three alert levels with three sounds, a jump to the waiting agent, and one alert when the whole fleet finishes. See Claude Code notifications.

Recipe 2: tidy every edited file with Prettier (PostToolUse)

Put this in .claude/settings.json in your project. After each Edit or Write, it pulls the file path out of the hook input with jq (a small JSON tool) and runs Prettier on it:

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

The matcher Edit|Write means exactly those two tools. A matcher with other characters, such as mcp__memory__.*, is treated as a pattern. When the hook works you see nothing in the chat, only a tidier file. You need jq installed for this and several other recipes.

Recipe 3: guard .env and lock files (PreToolUse)

Save this script as .claude/hooks/protect-files.sh and, on Mac or Linux, make it runnable with chmod +x .claude/hooks/protect-files.sh:

#!/bin/bash
# protect-files.sh
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

Then register it as a PreToolUse hook in .claude/settings.json:

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

Exit code 2 is what blocks the edit. The message you print to stderr goes back to Claude as the reason, so it can change course. This hook only covers the edit tools: Claude could still change .env with a shell command, so also add a deny rule such as Edit(/.env) under permissions.deny.

Recipe 4: keep Claude working until the job is done (Stop hook)

A Stop hook runs every time Claude tries to end its reply. This version uses a prompt hook, which asks a Claude model to judge whether the work is finished. If the answer is "ok": false, Claude keeps going with the reason as its next instruction:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."
          }
        ]
      }
    ]
  }
}

For a hard check, such as tests passing, a command hook that exits with code 2 does the same job without asking a model. Claude Code overrides a Stop hook after it blocks eight times in a row with no tool call in between. Make your script check the stop_hook_active field and step aside once it has already sent Claude back:

#!/bin/bash
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
  exit 0  # Allow Claude to stop
fi
# ... your check goes here

Keep Stop checks fast. A full test suite on every reply slows everything down and uses more of your plan, since every failed check means another round of work. A quick typecheck or lint is usually the right size.

Recipe 5: repeat your key rules after compaction (SessionStart)

When a long chat is compacted (summarised to free space), details can get lost. A SessionStart hook with the compact matcher runs right after each compaction, and whatever it prints is added back into Claude's context:

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"
          }
        ]
      }
    ]
  }
}

Swap the echo for something dynamic, such as git log --oneline -5, to remind Claude of recent commits. For rules that should load at the start of every session anyway, CLAUDE.md is the simpler place.

Recipe 6: approve finished plans without the pop-up (PermissionRequest)

If you always approve plans, this hook answers the plan approval prompt for you. It matches only ExitPlanMode, the tool Claude calls when a plan is ready, and returns an allow decision as JSON:

{
  "hooks": {
    "PermissionRequest": [
      {
        "matcher": "ExitPlanMode",
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input}}}'"
          }
        ]
      }
    ]
  }
}

Keep this matcher narrow. An empty matcher or .* would approve every permission prompt, including file writes and shell commands. Most people are better off reading plans, so treat this one as an option for experienced users.

Recipe 7: keep a log of settings changes (ConfigChange)

This appends a line to a log file whenever a settings or skills file changes during a session. Useful on shared machines, or when you want to know who changed what:

{
  "hooks": {
    "ConfigChange": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"
          }
        ]
      }
    ]
  }
}

The matcher can narrow it to user_settings, project_settings, local_settings, policy_settings or skills. Exiting with code 2 would block the change instead of logging it.

Recipe 8: send tool events to your own server (HTTP hook)

An http hook posts the same JSON a command hook would receive to a web address. This one sends every successful tool call to a logging service on your own machine:

{
  "hooks": {
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "http",
            "url": "http://localhost:8080/hooks/tool-use",
            "headers": {
              "Authorization": "Bearer $MY_TOKEN"
            },
            "allowedEnvVars": ["MY_TOKEN"]
          }
        ]
      }
    ]
  }
}

Only environment variables listed in allowedEnvVars are filled in, which stops a header from leaking other secrets. If the server is down, Claude Code reports a non-blocking error and carries on.

Hook safety rules before you paste anything

Watch out

Hooks run with your own user's permissions, every time, without asking. Only add hooks you understand, and read the .claude/settings.json of any repository you clone before you start Claude Code inside it.

  • Only exit code 2 blocks. Exit code 1 and other non-zero codes count as a non-blocking error, and the action still goes ahead.
  • A PreToolUse hook that returns permissionDecision: "deny" blocks the tool even in bypass permissions mode, so hooks are a good place for rules nobody should be able to switch off.
  • Put JSON fields at the right level. permissionDecision belongs inside hookSpecificOutput; at the top level it is silently ignored.
  • Build JSON output with jq or another encoder, never by gluing strings together, so quotes inside values do not break it.
  • Keep secrets out of hook commands. Read them from environment variables.

When a hook does nothing: quick fixes

  • Not listed in `/hooks`? Check the JSON is valid (no trailing commas, no comments) and that the file is in the right place. Restart the session if the change was not picked up.
  • Listed but never fires? Matchers are case-sensitive and must match the tool name exactly, such as Bash, Edit or Write.
  • "command not found"? Use full paths or $CLAUDE_PROJECT_DIR, and install jq if the error names it.
  • Script not running on Mac or Linux? Make it executable with chmod +x.
  • JSON ignored with no error? Something in your shell profile may print text before your JSON. Wrap those echo lines so they only run in interactive shells.
  • Want to see what happened? Press Ctrl+O for the transcript view, or start with claude --debug and read the debug log.

Test a script by hand before wiring it up: echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh, then echo $? to see the exit code. Or skip the script writing entirely and ask Claude: write a hook that blocks edits to the migrations folder. See our Claude Code tips for more habits like this.

Every Claude Code hook event in one table

EventFires whenMatcher filters on
SessionStartA session begins or resumesstartup, resume, clear, compact, fork
SetupStarted with --init-only, or --init / --maintenance in -p modeinit, maintenance
UserPromptSubmitYou submit a prompt, before Claude processes itNo matcher
UserPromptExpansionA typed command expands into a promptCommand name
PreToolUseBefore a tool call runs (can block it)Tool name
PermissionRequestA tool call needs a permission decisionTool name
PermissionDeniedAuto mode denies a tool callTool name
PostToolUseAfter a tool call succeedsTool name
PostToolUseFailureAfter a tool call failsTool name
PostToolBatchAfter a batch of parallel tool calls finishesNo matcher
NotificationClaude Code sends a notificationNotification type
MessageDisplayWhile reply text is shownNo matcher
SubagentStartA subagent is startedAgent type
SubagentStopA subagent finishesAgent type
TaskCreatedA task is createdNo matcher
TaskCompletedA task is marked completeNo matcher
StopClaude finishes respondingNo matcher
StopFailureThe turn ends because of an API errorError type, such as rate_limit
TeammateIdleAn agent team teammate is about to go idleNo matcher
InstructionsLoadedA CLAUDE.md or rules file loadsLoad reason
ConfigChangeA config file changes during a sessionConfig source
CwdChangedThe working folder changesNo matcher
DirectoryAddedA folder is added with /add-dirHow it was added
FileChangedA watched file changes on diskFile names, such as .envrc|.env
WorktreeCreateA worktree is createdNo matcher
WorktreeRemoveA worktree is removedNo matcher
PreCompactBefore the chat is compactedmanual, auto
PostCompactAfter the chat is compactedmanual, auto
PreModelSwitchBefore a model switchModel name
PostModelSwitchAfter a model switchModel name
ElicitationAn MCP server asks you for inputMCP server name
ElicitationResultYou answer an MCP server's requestMCP server name
SessionEndThe session endsclear, resume, logout, prompt_input_exit, other

That is 33 events as of November 2026, from Anthropic's hooks reference. Besides command, a hook's type can be http, mcp_tool (call a tool on an MCP server), prompt or agent (experimental). Hooks that start helper agents pair well with subagents.

Three hook questions we get

Where do I put Claude Code hooks?

+

In a hooks block inside ~/.claude/settings.json for all projects, .claude/settings.json for one shared project, or .claude/settings.local.json for one project that only you use.

Why is my PreToolUse hook not blocking the command?

+

Only exit code 2 blocks. Exit code 1 and other non-zero codes are treated as non-blocking errors, so the action continues. Also check that the matcher spells the tool name exactly, with the same capital letters.

How do I get a notification when Claude Code finishes?

+

Use a Notification hook for alerts when Claude is waiting on you, or a Stop hook for an alert every time it finishes a reply. Put your system's notification command in either one.

Sources

Run up to 12 AI coding agents in one window.

Claude Code, Codex, Gemini, Grok and more, side by side. Windows and Mac. From $29 a month.

Get started

Keep reading