Lesson 6.116 min · 5 cards · 8 exercises · 1 mission

The lifecycle and hook events

A hook is a command Claude Code runs every time an event happens: a session's lifecycle, configuration, JSON input, exit codes, matchers and safety.

Since level 2, everything you've told Claude has been a request: CLAUDE.md says "run the tests before you finish", a skill says "don't edit src/". Claude usually follows them, but not always. Lesson 4.3 even showed a delegation message overriding the instructions in an agent file. This level introduces something that doesn't depend on Claude remembering: a hook, a command Claude Code runs on its own every time an event happens, every single time.

What a hook is

A hook is a shell command you write that Claude Code runs at fixed points in a session: when the session starts, before Claude uses a tool, after Claude edits a file, when Claude finishes answering…

The key difference from CLAUDE.md and skills:

CLAUDE.md, skills Hooks
Who decides to run it Claude, following instructions Claude Code, whenever the event happens
Result Can vary from run to run The same every time
Good for Work that needs judgement Things that must always happen

The docs put it plainly: hooks give you deterministic control, so certain actions always happen rather than depending on the model choosing to run them. Good uses: formatting code after every edit, blocking dangerous commands, notifying you when Claude needs an answer, adding information at the start of every session.

Most hooks are "type": "command", a shell command. There are also http (send the data to a URL), mcp_tool (call a tool on an MCP server), prompt (ask a model for a quick judgement) and agent (experimental). This level uses command.

The life of a session

Events happen at three rhythms:

  • Once per session: SessionStart when a session begins or resumes; SessionEnd when it ends.
  • Once per turn: UserPromptSubmit when you send a message, before Claude processes it; Stop when Claude finishes answering.
  • On every tool call: PreToolUse before the tool runs, and this is the event that can block; PostToolUse after the tool succeeds.

There are many other events, such as Notification when Claude Code sends a notification, SubagentStart and SubagentStop around each subagent (level 4), PreCompact before context is compacted, and PermissionRequest when Claude Code is about to ask you for permission.

We attached a logging hook to the six main events and asked Claude to run npm test in todo-api. The log recorded the lifecycle exactly:

SessionStart (startup)
UserPromptSubmit
PreToolUse  (Bash: npm test)
PostToolUse (Bash)
Stop
SessionEnd

If Claude uses five tools in one turn, you'll see five PreToolUse/PostToolUse pairs between UserPromptSubmit and Stop.

Configuring a hook

Hooks live in the hooks block of a settings file, in three levels: event → matcher group (when to run) → handler (what runs).

JSON
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{event: .hook_event_name, tool: .tool_name}' >> \"$CLAUDE_PROJECT_DIR\"/.claude/hooks.log"
          }
        ]
      }
    ]
  }
}

This hook writes a line to .claude/hooks.log every time Claude finishes a Bash command. jq is a JSON tool that ships with recent macOS. $CLAUDE_PROJECT_DIR is the project root, so the path stays right even after Claude has cd-ed somewhere else.

Where to put it depends on who needs it:

File Applies to Shared
~/.claude/settings.json All your projects No
.claude/settings.json This project Yes, committed to the repo
.claude/settings.local.json This project No

Hooks can also come from plugins, from your organization's managed settings, and from the frontmatter of a skill or subagent (lessons 3.3 and 4.3).

Type /hooks to see every hook in effect, grouped by event and labelled with where it comes from. To switch them all off for a while, set "disableAllHooks": true. There's no way to turn off a single hook while keeping its configuration: to drop one, delete it from the file.

What a hook receives and returns

When an event happens, Claude Code sends the hook JSON on stdin. Common fields include session_id, cwd and hook_event_name; each event adds its own. For PreToolUse when Claude runs Bash:

JSON
{
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": { "command": "npm test" }
}

The hook answers with its exit code:

  • Exit 0: no objection. Note that on PreToolUse, exit 0 does not mean "allowed"; the command still goes through the normal permission flow.
  • Exit 2: block. What the hook prints to stderr is sent back, and on PreToolUse Claude reads the reason and can try another way. Lesson 6.3 uses this to block rm -rf.
  • Any other code: on most events the action goes ahead, with an error notice.

On SessionStart and UserPromptSubmit, whatever the hook prints to stdout (with exit 0) is added to Claude's context. We tested a SessionStart hook that printed the git branch. Asked "which branch am I on?" with no tools allowed, Claude answered correctly and said the information came from the hook's output. A more useful example, since Claude can't know it otherwise:

JSON
"SessionStart": [
  { "hooks": [ { "type": "command", "command": "echo \"Node $(node --version)\"" } ] }
]

For finer control, exit 0 and print JSON instead, for example permissionDecision: "deny" with a reason. Lesson 6.3 uses that.

Matchers: choosing when to run

Without a matcher, a hook runs every time its event happens. A matcher narrows that, and what it filters on depends on the event:

  • Tool events filter on the tool name: Bash, Edit|Write (editing or writing a file), mcp__github__.* (every tool from level 5's GitHub server).
  • SessionStart filters on how the session started: startup, resume, clear, compact.
  • Some events, such as UserPromptSubmit and Stop, have no matcher: they always run.

Matchers are case-sensitive: bash doesn't match Bash. It's the most common reason a hook "doesn't run".

To filter beyond the tool name, use the if field with the permission-rule syntax from lessons 1.3 and 5.3, such as "if": "Bash(git *)" so the hook only runs for git commands. The docs note that if is a best-effort filter; for hard rules, use the permission system.

One caveat: Claude can change files with shell commands, not just Edit or Write. A hook that only matches Edit|Write misses those changes.

Hooks run with your permissions

A hook is a shell command running with your full account permissions: it can read, change or delete anything you can. So:

  • In an interactive session, Claude Code holds back every hook until you accept the folder trust dialog.
  • But claude -p treats the folder as trusted, so hooks committed in an unfamiliar repo's .claude/settings.json will run. Before running -p on a repo that isn't yours, read its .claude/ folder, or switch hooks off for that run: claude -p --settings '{"disableAllHooks": true}' "…".

Habits for writing hooks:

  • Quote variables ("$VAR") and use full paths with $CLAUDE_PROJECT_DIR.
  • Test a hook first by piping sample JSON into it:
    Terminal
    echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh; echo $?
  • For a separate script, remember chmod +x.
  • In a session, press Ctrl+O to open the transcript and see what a hook blocked or which errors it reported.

Lesson 6.2 uses PostToolUse to format code and run tests automatically; lesson 6.3 uses PreToolUse to block what must never happen.

Practice lesson 6.1

5 flashcards, 8 exercises checked right on the page, 1 mission on your machine.

Start practice

Related reference

Type to search the reference, templates and lessons.