Claude Code Hooks

Format an edited file, refuse a risky Bash command and attach a rule to each prompt. Includes working settings and a table of every hook event.

Published

Claude Code Hooks

You can have Claude Code format a file the moment it edits it, refuse a risky shell command before it runs, or attach a project rule to every prompt. Put each job at the right point in the session and you can leave “please remember to…” out of the next request.

Start with the moment you need the rule

Imagine reviewing a change that mixes a bug fix with three screens of reindented code. Asking Claude to remember the formatter leaves you checking its work. A hook lets you assign that step to the editing tool itself. Every successful edit through that tool hands the changed file to the same formatter. To estimate the hours at stake, count last week’s format-only round trips, multiply by the minutes of hands-on work each took, and divide by 60. That gives you a baseline for deciding whether to share the hook.

A hook has three parts. The event is the moment something happens. The matcher filters which occurrences you care about, such as writes and edits. The handler does the work. A command handler gets a small JSON record through standard input, the stream a program reads when it starts. It can act on the named file, print a message, or tell Claude Code how to handle a pending action. Hooks can also call a web endpoint, a connected tool, a model prompt or a subagent. The examples here need only local commands.

Where to put the settings

Use .claude/settings.local.json to try a rule in one checkout. Put a rule the team should review and share in .claude/settings.json at the project root. A personal rule for all your local projects belongs in ~/.claude/settings.json. A cloud session cannot read that file on your laptop.

Organization administrators can supply managed settings. An enabled plugin can supply hooks/hooks.json. A skill or subagent can carry scoped hooks in the settings at the top of its definition. Shared settings hooks also run when a Claude Code subagent calls a matching tool.

Three hooks you can put in one project

This is one settings object for macOS or Linux. If your file already has a hooks key, merge the event entries into it and preserve any handlers you already use. The formatter example assumes Prettier is installed in the project's node_modules and jq, a program for reading JSON, is on your path. Open /hooks in Claude Code to inspect the registered handlers. Anthropic's setup guide

JSON
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "f=$(jq -er '.tool_input.file_path') && \"$CLAUDE_PROJECT_DIR/node_modules/.bin/prettier\" --write --ignore-unknown \"$f\""
      }]
    }],
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "if": "Bash(rm *)",
        "command": "echo 'Deletion requires a human in this project.' >&2; exit 2"
      }]
    }],
    "UserPromptSubmit": [{
      "hooks": [{
        "type": "command",
        "command": "echo 'For this migration, keep the old response fields until all clients switch.'"
      }]
    }]
  }
}

Format the file Claude just edited

For a frontend team that already checks formatting in continuous integration, this is the first hook I'd add. Suppose Claude changes a component through Edit. Once the edit succeeds, PostToolUse receives the path in tool_input.file_path. The command quotes that path so a folder name containing spaces still reaches the formatter as one argument. Prettier rewrites the file using the project's formatting rules and skips unknown file types. The next reviewer gets the formatted version without asking for a cleanup pass.

An edited file passes through a Prettier press and comes out aligned.
PostToolUse has a file to format because the edit has already succeeded.

The filter covers the Edit and Write tools. A Bash script that rewrites the same component takes another route. If one particular file must be watched regardless of what changed it, look at FileChanged. Keep the repository's existing formatting check for work that reaches review by other routes.

Refuse a deletion while it is still a request

A maintainer working around irreplaceable local fixtures might reserve all shell deletions for a human. If Claude proposes rm -rf fixtures, the Bash matcher selects the tool and the if rule selects the matching deletion command. The handler writes the project's reason to standard error and exits with code 2. Claude receives the reason and the requested call stops before the directory is touched. A request for git status continues through the usual permission checks.

A gate stops a Bash request while a separate track leads through the permission check.
A refusal stops the pending call. An unmatched request still needs its ordinary permissions.

This policy deliberately catches an ordinary single-file removal too. If Claude Code cannot split a Bash request into subcommands, it runs the handler regardless of the pattern. This handler refuses that request too. For a hard allow or deny policy, use Claude Code permission rules. A project that needs filesystem-wide write restrictions also needs an appropriate sandbox. The choice of Claude Code permission mode is a separate decision.

Attach a migration reminder to every prompt

A developer maintaining two versions of an API needs Claude to see one constraint even on a short follow-up like “tidy this up.” When UserPromptSubmit fires, plain text printed on successful standard output becomes context Claude can read before processing the request. The example contributes one sentence about the old response fields. Change that sentence when the last client migrates.

A prompt card and a smaller project rule arrive together in Claude's reading tray.
The hook supplies the reminder. A compatibility test can check whether the resulting code honors it.

This distinction matters in review. You can count on the configured hook running at its event. Printing the rule cannot guarantee a compatible response. For an API contract, keep a test that exercises the old client.

How a command hook answers

For a synchronous command hook, Claude Code reads both the program's exit status and its output. Exit 0 is the ordinary success path. A silent, successful PreToolUse handler makes no permission decision. To make a structured decision, print a single valid JSON object on standard output, with no log lines around it, and exit 0. For example, this is an alternative refusal a Bash handler could return when its check matches.

JSON
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Deletion requires a human in this project."
  }
}

Exit 2 with a reason on standard error is the shorter refusal used above. Its effect depends on the event. At PreToolUse the action is still pending. At PostToolUse the tool has already succeeded, so feedback cannot undo the edit. A valid JSON reply cannot turn an exit-2 PreToolUse refusal into an approval.

Another nonzero exit with plain text or empty output usually reports a nonblocking hook error. Valid structured output can still determine the outcome on supported events. Some events have their own rules, and a supported handler configured with "onFailure": "block" can stop an action when the handler crashes or times out. Choose that behavior deliberately if a missing policy script should halt work. Exit status and output combinations

Which Claude Code hook event fires when?

The table follows the hook lifecycle reference as of November 29, 2026. Choose by when you can still affect the outcome. For example, a permission request, a denied tool call and a failed tool execution are three different events.

EventWhen it fires
SetupDuring explicit setup with --init-only, or with --init or --maintenance in print mode (-p).
SessionStartA session starts or resumes.
UserPromptSubmitClaude Code receives a prompt, including on turns it starts itself, before model processing.
UserPromptExpansionA command you type expands into a prompt, before Claude receives it.
PreSkillShellCommandA loading skill is about to run an inline shell command.
PreToolUseA tool is about to execute.
PermissionRequestA tool call needs a permission decision.
PermissionDeniedAuto mode denies a tool call.
PostToolUseA tool call succeeds.
PostToolUseFailureA tool call fails.
PostToolBatchA batch of parallel tool calls finishes, before the next model call.
NotificationClaude Code sends a notification.
MessageDisplayClaude Code displays assistant message text.
SubagentStartClaude Code starts a subagent.
SubagentStopA subagent finishes.
TaskCreatedThe TaskCreate tool is creating a task.
TaskCompletedA task is being marked complete.
StopClaude finishes responding.
StopFailureAn API error ends the turn.
TeammateIdleA teammate in an agent team is about to become idle.
InstructionsLoadedClaude Code loads a CLAUDE.md or a .claude/rules/*.md file into context.
ConfigChangeA configuration file changes during the session.
CwdChangedThe working directory changes.
DirectoryAddedA directory is added to the session while it is running.
FileChangedA file selected for watching changes on disk.
WorktreeCreateClaude Code creates a separate working copy with worktree isolation or its worktree option.
WorktreeRemoveClaude Code cleans up a worktree created by a WorktreeCreate hook.
PreCompactClaude Code is about to summarize the conversation to free context space.
PostCompactThat summarization finishes.
PreModelSwitchA requested model change is about to take effect.
PostModelSwitchThe session's model changes, including an automatic switch.
ElicitationA connected MCP server requests user input during a tool call.
ElicitationResultThe user has responded, before the answer goes back to the server.
SessionEndThe session terminates.

The EndConversation tool skips both PreToolUse and PostToolUse. A logger attached to those two events alone cannot give you a complete record of how a session ended.

The November addition. Version 2.1.332, released November 25, added PreSkillShellCommand. It lets a hook refuse an inline shell command as a skill or command loads. That gives teams sharing Claude Code skills a chance to review those commands at load time. Coordinate upgrades before committing the event to shared settings. Version 2.1.331 and earlier open a dialog at startup if the settings name it. Anthropic's 2.1.332 release notes

Two more jobs worth automating

Tell the developer when a decision is waiting. Someone running a long task beside their editor can attach a desktop notification to Notification with the permission_prompt matcher. They can return when Claude needs approval and spend the intervening time on another task.

Restore the current milestone after a long session is summarized. A migration lead could use SessionStart with the compact matcher to print the rollout stage from a team-maintained file. That puts the current stage back in context at the point where earlier discussion may have been compressed. It avoids repeating the whole rollout plan on every prompt.

What a team might pay for

I'd build a hook test runner first. A platform team about to share a command policy needs to answer two questions in review. Which sample requests does this rule catch? What happens if the script fails? Start with a local runner that feeds recorded, sanitized event JSON to a handler, captures its output and exit status, and compares them with the team's expected results. Include both a refusal and a routine command in every example. The difficult part is keeping the interpretation current with Anthropic's event semantics. Label the installed version and distinguish handler tests from checks inside Claude Code.

DataForSEO's November estimate for “claude code hooks” is 2,900 Google searches per month. That's interest in hooks broadly. The case for a paid runner rests on teams repeatedly reviewing shared policies. A pilot with one platform team would tell you more about willingness to pay than the search total.

A smaller build is a formatter setup check for agencies. A developer switching client repositories could use one command to identify the project's formatter, preview the hook configuration, and run it against a disposable file with a space in its name. Return the actual file difference so the developer can spot a mismatch with the repository's rules. DataForSEO estimates 260 monthly Google searches for “vscode format on save” and 50 for “prettier format on save.” Those searches concern editor workflows, so treat them as evidence of a familiar job. The commercial catch is that a single-repository team can copy the short formatter hook above. The paying customer would need a recurring setup problem across repositories.

What to trust before you enable a hook

Read the command and any script it calls as carefully as code you're about to run in your own terminal. A command hook runs with your account's permissions. It can read, change or delete files you can access. Review it, then exercise it on disposable input before sharing it. Interactive sessions wait for workspace trust before running settings-file hooks. Print-mode and SDK sessions treat the workspace as trusted, a consequential difference for anyone running a checkout unattended. Anthropic's hook security guidance

How do I check my Claude Code hook settings?

Open /hooks and look for the event and handler you expected. If formatting did nothing, check which tool wrote the file and whether the formatter supports it. For an installation tied to an older version, see the 2.1.141 hook configuration fixes.

What Claude Code settings should I use for a team formatter?

Start in .claude/settings.local.json while you check the changed file. Move the working rule into the project's shared .claude/settings.json so its command and any later edits can go through code review.

Do skills work with hooks in Claude Code?

Yes. A skill can define hooks in its own frontmatter. A team that wants to distribute several extensions together can also package hooks in a plugin. The Claude Code plugin comparison is a next read if you prefer an existing package.

If your team needs these checks wired into an existing review workflow, our automation service can help.

Published
Category
Build
Related Articles
How to fine-tune Gemma 4 on one GPU

How to fine-tune Gemma 4 on one GPU

Choose RAG, QLoRA or full tuning, check VRAM for all five Gemma 4 sizes, and follow Google’s single-GPU example from dataset to serving.Nov 28, 2026Build
Anthropic Siren: Why Agents Leave Weak Sandboxes, and What Stops Them

Anthropic Siren: Why Agents Leave Weak Sandboxes, and What Stops Them

Siren tests whether Claude leaves a weakened sandbox. Describing the sandbox's rules cut that by 68% to 96%. What to set up, and what still needs a wall.Nov 28, 2026Build
Blender MCP

Blender MCP

Choose the right Blender MCP, connect it to Claude or another client, and try three scene questions before letting an assistant edit your file.Nov 28, 2026Build
Qwen 3.8 27B: Can Your Machine Run It?

Qwen 3.8 27B: Can Your Machine Run It?

Choose a Qwen 3.8 27B download for a 16 GB or 24 GB GPU or a 32 GB Mac, then start a local chat with Ollama or LM Studio.Nov 28, 2026Build
Grok Build: What It Is, What It Costs, and How to Start

Grok Build: What It Is, What It Costs, and How to Start

Install Grok Build, sign in, and ask your first question about a project. See the commands for macOS, Linux, WSL, and Windows and the model it uses.Nov 27, 2026Build
Claude Dreaming: How Dreams Rebuild an Agent's Memory Between Sessions

Claude Dreaming: How Dreams Rebuild an Agent's Memory Between Sessions

Claude dreaming in Managed Agents: what a dream reads, the new memory store it writes, the request line by line, how to review it, and what it costs.Nov 27, 2026Build
Vercel Workflow SDK 5.8: Which Steps Are Safe to Run Early?

Vercel Workflow SDK 5.8: Which Steps Are Safe to Run Early?

Vercel cut step-to-step overhead from 85 ms to 7 ms. See how speculative execution works, which steps need a retry policy, and how to roll out the upgrade.Nov 27, 2026Build
Claude Agent Teams: Setup, Use Cases and Limits

Claude Agent Teams: Setup, Use Cases and Limits

Enable Claude Code agent teams, split a review across sessions, and choose when peer discussion earns the extra usage. Includes setup and recovery steps.Nov 27, 2026Build
Newsletter

One letter, every Sunday.Working systems, not hot takes.

Weekly. No spam. Unsubscribe anytime.