Claude Code hooks. A command that always runs, not only when Claude remembers

What a Claude Code hook is, which events you can attach it to and where to save it. Two ready examples, formatting after every edit and blocking changes to .env.

Part of the guideClaude Code, the complete guide. From installation to your own skills and plugins

In this article
  1. What a hook in Claude Code is
  2. Events you can attach a hook to
  3. Where to save a hook
  4. Example 1. Format after every edit
  5. Example 2. Block changes to .env
  6. The /hooks command and safety

In short

A Claude Code hook is a command that Claude Code runs on its own at a chosen event, for example after every file edit or before a shell command runs. You save it in a settings.json file, and the /hooks command lists every hook you have configured. Below are two ready examples, formatting code after edits and blocking changes to the .env file.

Your CLAUDE.md says to run Prettier after every change. Claude usually does. Sometimes, deep into a long session, it forgets, and a file with different formatting ends up in the repository. That kind of rule belongs in a hook, not in CLAUDE.md.

A Claude Code hook is a command that Claude Code itself runs at a set point in its work. The model does not decide whether it runs, so it runs every time. The Anthropic documentation calls this deterministic control. This page is part of our Claude Code guide, as of 10 November 2026.

What a hook in Claude Code is

Most hooks are plain shell commands, type command. Claude Code passes them JSON describing the event on standard input, for example the path of the edited file. The hook answers with an exit code. Exit 0 means no objection. Exit 2 blocks the action, and whatever the hook printed to stderr goes back to Claude as the reason.

There are four other types. http posts the event data to a URL, mcp_tool calls a tool on an MCP server, prompt asks a Claude model for a single decision, and agent runs a check with access to tools. Anthropic marks the agent type as experimental.

The difference from CLAUDE.md is simple. CLAUDE.md is a request the model reads and usually follows. A hook is a mechanism that runs whatever the model thinks.

Events you can attach a hook to

The documentation lists 33 events today. A handful cover most daily needs.

EventWhen it fires
SessionStartWhen a session starts or resumes
UserPromptSubmitAfter you send a prompt, before Claude reads it
PreToolUseBefore a tool runs, and it can block it
PermissionRequestWhen a tool call needs permission
PostToolUseAfter a tool call succeeds
NotificationWhen Claude Code sends a notification
StopWhen Claude finishes responding
PreCompactBefore the conversation is summarised
FileChangedWhen a watched file changes on disk
SessionEndWhen the session ends

The matcher field narrows a hook to certain tools. Edit|Write means the hook only fires when files are edited or written. Matchers are case sensitive.

Where to save a hook

Hooks live in a hooks block inside a settings file. The file decides who the hook applies to.

FileScopeIn the repository
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonOne projectYes
.claude/settings.local.jsonOne project, only youNo
Managed settingsThe whole organisationSet by an admin

Hooks can also come with a plugin, a skill or a subagent. If you edit a settings file during a session, Claude Code normally picks up the change by itself.

Example 1. Format after every edit

This hook runs Prettier on every file Claude changes. The PostToolUse event with the Edit|Write matcher fires after edits and writes. The command pulls the file path out with jq, so jq has to be installed.

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

When the hook works, nothing shows up in the conversation. To test it, ask Claude to add a line with single quotes to a JavaScript file. With default settings, Prettier turns them into double quotes.

Example 2. Block changes to .env

This hook stops Claude from editing .env, package-lock.json or anything inside .git/. The script checks the path and exits with code 2 when it matches the list. Save it as .claude/hooks/protect-files.sh.

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

Then register it as a PreToolUse hook for edits and writes. We call the script through bash, so it does not need the executable bit.

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

Ask Claude to add a comment to .env. The edit is rejected before it runs, and Claude receives the script's message and looks for another way. According to the docs, a deny from a PreToolUse hook holds in every permission mode, bypassPermissions included. Exit 0 approves nothing, the normal permission rules decide then.

The /hooks command and safety

Type /hooks in Claude Code. You get a list of hooks grouped by event, with the file each one comes from. The list is read only. You change or remove a hook in its settings file. "disableAllHooks": true turns all of them off at once.

You can also ask for a hook in plain words. Tell Claude what it should do, for example block edits to the migrations folder, then check the result in /hooks.

Two points from the security section are worth knowing. A command hook runs with your full user permissions, so it can read and delete anything your account can. In a normal session Claude Code holds hooks back until you accept the workspace trust dialog for the folder. In claude -p there is no such dialog, and hooks from someone else's repository run straight away. More on that mode in our post on Claude Code in scripts and CI.

A good start is one hook that protects files with credentials, with formatting added later. If you are wondering where AI could take repetitive work off your team, ask for our free AI audit.

What would you like to change in your business?

Leave your number. We will talk about your process and see whether we can help. The first call is free.

When is the best time to call?
Controller: Oleksandr Bondarenko (BondSoft)Privacy PolicyTerms of Service
Legal details

The data controller is Oleksandr Bondarenko, trading as Oleksandr Bondarenko Software Solutions (BondSoft), ul. Jana Heweliusza 11, 80-890 Gdańsk, Poland, NIP 5833576264, e-mail: office@bondsoft.pl.

We process your data solely to contact you about your enquiry and to present an offer — on the basis of your consent (Art. 6(1)(a) GDPR and Art. 398 of the Polish Electronic Communications Law) and our legitimate interest in handling the enquiry (Art. 6(1)(f) GDPR).

Providing the data is voluntary but necessary for us to reply. You may withdraw your consent at any time by writing to office@bondsoft.pl — this does not affect the lawfulness of processing before the withdrawal.

You have the right to access your data, rectify it, erase it, restrict its processing, transfer it, and lodge a complaint with the President of the Polish Personal Data Protection Office.

Full information: Privacy Policy.

Send us an email

The service this text is about

Automation and AI / OCR

Automation of document re-typing, OCR and checking rules, and your data stays with you.