$ skilldirectory
— zsh — registry.skilldirectory.dev
skill libraryblogguidesabout

home / blog / claude code

Claude Code Hooks: 5 Practical Examples and How to Set Them Up (2026)

Quick answer: Claude Code hooks are shell commands (or HTTP calls, or small model checks) that run automatically at set points in a session, such as before a tool call or after a file edit.

You add them to a hooks block in a settings file like .claude/settings.json. A hook that exits with code 2 blocks the action, which is how you enforce rules Claude might otherwise skip.

If you have ever told Claude "always run the formatter" and watched it forget on the third file, hooks are the fix. Instructions in a prompt are suggestions. A hook is code that runs every time.

This guide explains how hooks work, where to put them, and five examples you can copy. Everything was checked against Anthropic's hooks guide on November 19, 2026. Hook events and version requirements change, so verify against the docs for your installed version.

What are Claude Code hooks?

According to the docs, hooks are user-defined commands that Claude Code runs at specific points in its lifecycle. That gives you deterministic control: certain things always happen instead of relying on the model to choose to do them.

Common uses include formatting code, blocking commands before they execute, sending notifications when Claude needs input, and injecting context at session start.

There are five hook types:

TypeWhat it doesUse it for
commandRuns a shell commandMost hooks: formatters, linters, scripts
httpPOSTs the event data to a URLLogging or checks on your own server
mcp_toolCalls a tool on a connected MCP serverReusing an existing integration
promptSingle-turn check by a Claude model (Haiku by default)Judgment calls, such as "is the task finished?"
agentMulti-turn check with tool access (experimental)Verification that needs to read files

Most people only ever need command.

The events you will use most

There are more than 30 events in the docs. These are the ones that matter on day one:

EventWhen it fires
SessionStartA session begins or resumes
UserPromptSubmitYou submit a prompt, before Claude sees it
PreToolUseBefore a tool call runs. Can block it
PostToolUseAfter a tool call succeeds
NotificationClaude is waiting for input or permission
StopClaude finishes responding
PreCompact / PostCompactAround context compaction

Matching hooks for an event run in parallel.

Where to put hooks

The location decides who gets the hook:

FileScopeShared?
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonOne projectYes, commit it
.claude/settings.local.jsonOne projectNo, gitignored
Managed policy settingsWhole organizationYes, set by admins

Plugins, skills and subagents can also carry hooks in their own files. Run /hooks inside Claude Code to browse everything configured, grouped by event. The menu is read-only, so to change a hook you edit the JSON or ask Claude to do it.

How a hook decides what happens

Claude Code sends event data to your script as JSON on stdin. Your script answers with its exit code:

  • Exit 0: no objection. For UserPromptSubmit and SessionStart, anything printed to stdout is added to Claude's context.
  • Exit 2: block the action, and write the reason to stderr. For many events, Claude gets that message as feedback and adjusts.
  • Any other exit code: a non-blocking error. The action proceeds and you see a hook error notice.

For finer control, exit 0 and print a JSON object instead. The docs advise picking one approach per hook rather than mixing exit 2 with JSON.

One caution: exit 0 on a PreToolUse hook does not approve the tool call. The normal permission flow still applies.

5 practical hook examples

1. Get a notification when Claude needs you

This uses the Notification event, so you can switch to other work and still know when Claude is waiting. This version is for macOS and goes in ~/.claude/settings.json:

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

On Linux, the docs use notify-send 'Claude Code' 'Claude Code needs your attention' instead. That command needs a desktop notification daemon, so it will not work over SSH or in most containers.

2. Auto-format after every edit

A PostToolUse hook with an Edit|Write matcher runs Prettier on each file Claude touches. Add it to .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ]
  }
}

This example needs jq installed. When it succeeds, Claude Code shows nothing, so check the file itself to confirm it ran.

3. Block edits to protected files

A PreToolUse hook can stop Claude from touching .env, lockfiles or .git/. Save this as .claude/hooks/protect-files.sh:

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

for pattern in ".env" "package-lock.json" ".git/"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done
exit 0

Make it executable with chmod +x .claude/hooks/protect-files.sh, then register it under PreToolUse with the matcher Edit|Write, using the command "$CLAUDE_PROJECT_DIR"/.claude/hooks/protect-files.sh. Claude sees the "Blocked" message and can choose another approach.

4. Re-inject context after compaction

When the context window fills, compaction summarizes the conversation and can drop details. A SessionStart hook with the matcher compact reminds Claude of what matters:

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

Whatever the command prints to stdout is added to Claude's context.

5. Ask a model whether the work is really done

For decisions that need judgment, use a prompt hook. This Stop hook asks a model whether all tasks are complete, and if not, Claude keeps working:

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

Note that Stop hooks fire whenever Claude finishes responding, not only at the end of a task, and they do not fire on user interrupts.

Hooks vs CLAUDE.md vs skills

These three get confused, so here is the split:

  • CLAUDE.md holds guidance. Claude reads it as context and usually follows it, but nothing forces compliance.
  • Hooks enforce behavior. They run as code regardless of what Claude decides.
  • Skills package a method Claude loads when a task calls for it. Start with what Claude skills are.

A good rule: if a failure would be annoying, put it in CLAUDE.md. If a failure would be costly, such as editing a secrets file, put it in a hook. For a fuller comparison that includes subagents and plugins, see subagents vs skills vs hooks vs commands vs plugins.

Hooks also pair well with disciplined workflows. Skills like test-driven development and verification before completion describe the habit, and a hook can make the checking automatic. More ideas are in 10 Claude workflows you can set up today.

Limits and safety

A few constraints from the docs worth knowing:

  • Command hooks talk to Claude Code only through stdout, stderr and exit codes. They cannot trigger slash commands or tool calls.
  • PostToolUse hooks cannot undo anything, because the tool already ran.
  • Default timeouts: 10 minutes for command, http and mcp_tool hooks, 30 seconds for prompt hooks, and 60 seconds for agent hooks. Override with the timeout field.
  • Several PreToolUse hooks that rewrite the same tool input race each other, because hooks run in parallel.
  • Hooks run with your user's permissions, so read any hook before you trust it, especially one that arrived through a shared repository. The docs link to a security considerations section for shared and production environments.
  • To turn hooks off, set "disableAllHooks": true. Hooks in managed settings still run unless that setting is also applied there.

Debugging a hook that does nothing

  1. Run /hooks and confirm the hook appears under the right event.
  2. Check the settings file is in the correct location.
  3. Run your script by hand with sample JSON and check echo $?.
  4. Start with claude --debug-file /tmp/claude.log and read the log to see which hooks matched and what they returned. You can also run /debug mid-session.
  5. Build JSON output with jq rather than string concatenation, so quotes inside values do not break parsing.

FAQ

What are Claude Code hooks? User-defined commands that run automatically at specific points in a Claude Code session, such as before a tool call or after a file edit.

Where do I configure hooks? In a hooks block in ~/.claude/settings.json, .claude/settings.json or .claude/settings.local.json, or in plugin, skill or subagent files.

How do I block an action with a hook? Use a PreToolUse hook that writes a reason to stderr and exits with code 2.

Can a hook run a model instead of a script? Yes. prompt hooks send a single-turn check to a Claude model (Haiku by default), and agent hooks can run a multi-turn check with tool access.

Do hooks replace CLAUDE.md? No. CLAUDE.md guides, hooks enforce. Most projects use both.

Are hooks safe? They run with your permissions, so only use hooks you have read, and review any that come from a repository you did not write.

Sources: Automate actions with hooks and How Claude remembers your project (Anthropic documentation).