Skip to main content

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 and the hooks reference. Check those pages for the full event list.

Prerequisites​

  • Claude Code installed and available as claude on your PATH
  • jq 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 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.

LocationScopeShareable
~/.claude/settings.jsonAll your projectsNo, local to your machine
.claude/settings.jsonSingle projectYes, commit it to the repo
.claude/settings.local.jsonSingle projectNo, Claude Code gitignores it when it saves a setting there
Managed policy settingsOrganization-wideYes, 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.

EventWhen it fires
SessionStartWhen a session begins or resumes
UserPromptSubmitWhen a prompt is submitted, before Claude processes it
PreToolUseBefore a tool call executes. Can block it
PostToolUseAfter a tool call succeeds
NotificationWhen Claude Code sends a notification
StopWhen Claude finishes responding
SubagentStopWhen a subagent finishes
WorktreeCreateWhen 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. 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:

{
"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:

#!/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:

{
"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:

{
"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. 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 checks out tracked files only, so each parallel Claude Code session gets the same rules without copying anything.

Two paths matter once a session moves into a worktree. The worktrees docs 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 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:

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.