# How to Use Claude Code Hooks

_Run your own commands at fixed points in Claude Code's loop, so the rules that cannot bend hold in every session and every worktree._

## Goal

Turn a rule you keep writing in `CLAUDE.md`, such as "run the formatter" or "never edit `.env`", into a hook that Claude Code runs every time. Then commit it so every parallel agent on the repository follows the same rule.

As of December 2026, the event names, settings paths, and examples below come from the [Claude Code hooks guide](https://code.claude.com/docs/en/hooks-guide) and the [hooks reference](https://code.claude.com/docs/en/hooks). Check those pages for the full event list.

## Prerequisites

- Claude Code installed and available as `claude` on your `PATH`
- [`jq`](https://jqlang.org/) installed, because the examples parse hook input with it
- A repository where you can commit `.claude/settings.json`

## Hooks versus CLAUDE.md

`CLAUDE.md` is an instruction the model reads and then decides how to apply. A hook is configuration that Claude Code itself executes at the configured event, whatever the model decided. The [Claude Code best practices](https://code.claude.com/docs/en/best-practices) page draws the line this way. Guidelines go in `CLAUDE.md`. Anything that must happen every time goes in a hook, a deny rule, or a managed setting.

## Where hooks live

Hooks sit under a `hooks` key in a settings file. The file decides who the hook applies to.

| Location | Scope | Shareable |
| --- | --- | --- |
| `~/.claude/settings.json` | All your projects | No, local to your machine |
| `.claude/settings.json` | Single project | Yes, commit it to the repo |
| `.claude/settings.local.json` | Single project | No, Claude Code gitignores it when it saves a setting there |
| Managed policy settings | Organization-wide | Yes, admin-controlled |

Run `/hooks` inside Claude Code to browse configured hooks grouped by event.

## The events you will use first

Claude Code fires more than thirty hook events. Most projects start with these.

| Event | When it fires |
| --- | --- |
| `SessionStart` | When a session begins or resumes |
| `UserPromptSubmit` | When a prompt is submitted, before Claude processes it |
| `PreToolUse` | Before a tool call executes. Can block it |
| `PostToolUse` | After a tool call succeeds |
| `Notification` | When Claude Code sends a notification |
| `Stop` | When Claude finishes responding |
| `SubagentStop` | When a subagent finishes |
| `WorktreeCreate` | When Claude Code creates a worktree, for example with `--worktree`. Replaces the default git behavior |

For tool events, the `matcher` field filters on the tool name, such as `Bash`, `Edit|Write`, or `mcp__.*` for every [MCP tool](/learn/how-to/claude-code-mcp). Matchers are case-sensitive.

## How a hook talks to Claude Code

Claude Code passes event data to the hook as JSON on stdin. Every event includes `session_id` and `cwd`. Tool events add `tool_name` and `tool_input`.

The exit code carries the decision:

- **Exit 0** means no objection. On `PreToolUse` the call still goes through the normal permission flow, because exit 0 does not approve it.
- **Exit 2** blocks the action on events that can block. Claude Code passes stderr to Claude as feedback, so the agent can adjust.

A `PreToolUse` hook that denies a call holds in every permission mode, including `bypassPermissions`.

## Format every edit

This `PostToolUse` hook runs Prettier on each file Claude edits. Add it to `.claude/settings.json`:

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

The `Edit|Write` matcher skips files that a `Bash` command rewrites. The docs point to a `FileChanged` hook for that case.

## Block edits to protected files

Save this script as `.claude/hooks/protect-files.sh` and run `chmod +x` on it:

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

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
```

Register it as a `PreToolUse` hook. `$CLAUDE_PROJECT_DIR` holds the project root where the session started, so the path resolves from any directory:

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

The hook only sees the `Edit` and `Write` tools. Claude can still change the file with a shell command, so pair it with an `Edit` deny rule under `permissions.deny`.

## Stop the agent until checks pass

A `Stop` hook runs when Claude tries to end its turn. Exit 2 sends Claude back to work with stderr as the reason. This one from the best practices page blocks the stop until the typecheck passes:

```json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "pnpm tsc --noEmit 1>&2 || exit 2" }
        ]
      }
    ]
  }
}
```

The compiler output goes to stderr so Claude reads the errors. After eight blocked stops in a row with no tool call between them, Claude Code overrides the next block and ends the turn. This is the in-session version of a [quality gate](/learn/concepts/ai-engineering/quality-gates-for-agent-output). Keep it fast, and leave slow suites to CI.

## Hooks across parallel worktrees

Commit hooks and their scripts in `.claude/settings.json` and `.claude/hooks/`. A new [git worktree](/learn/concepts/git/git-worktrees) checks out tracked files only, so each [parallel Claude Code session](/learn/how-to/how-to-run-multiple-claude-code-sessions) gets the same rules without copying anything.

Two paths matter once a session moves into a worktree. The [worktrees docs](https://code.claude.com/docs/en/worktrees) state that `$CLAUDE_PROJECT_DIR` keeps pointing at the checkout where the session started. The `cwd` field in the hook input follows Claude into the worktree. A hook that formats or checks files must read `cwd`, or it runs against the main checkout instead of the agent's changes.

Treq workspaces are separate working copies too, so the same rule applies. A committed `Stop` hook gives the agent a fast gate during the session. Treq's [Workspace Checks](/docs/concepts/checks) then run your full install, lint, and test workflow per workspace and keep a pass or fail history you read before review.

## Common failure cases

**Hook never fires.** Run `/hooks` and confirm it appears under the right event. Check that the matcher matches the tool name exactly, including case.

**`/hooks` shows nothing.** Check the JSON for trailing commas or comments, which settings files do not allow. Confirm the file path. If the menu says only managed hooks run, your organization has set `allowManagedHooksOnly`.

**Hook errors in the transcript.** The script exited non-zero. Test it by piping sample input:

```bash
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh
```

**Stop hook loops.** Read `stop_hook_active` from the input and exit 0 when it is `true`, so the hook does not block a stop it already triggered.

## Related

- [How to Add a Claude Code MCP Server](/learn/how-to/claude-code-mcp): connect external tools and match them in hooks
- [Quality Gates for Agent Output](/learn/concepts/ai-engineering/quality-gates-for-agent-output): design the checks a hook should run
- [How to Run Multiple Claude Code Sessions](/learn/how-to/how-to-run-multiple-claude-code-sessions): run agents side by side in worktrees
- [How to Review Code with Claude Code](/learn/how-to/claude-code-review): review what the agent produced
