skip to content

How do you set up a Claude Code hook that runs your formatter on every file Claude edits, and what does it miss?

level: juniorimportance: must knowfreq 30%

answer

  1. after the tool, not before
  2. PostToolUse with an Edit|Write matcher
  3. jq pulls tool_input.file_path from stdin
  4. commit it in .claude/settings.json
  5. shell-made changes slip past the matcher

basics

~20 s

A PostToolUse command hook matched on Edit|Write, committed in .claude/settings.json, reads tool_input.file_path from stdin with jq and formats that one file. It runs after the edit, and files changed through Bash slip past that matcher.

solid answer

~50 s

I register a `PostToolUse` hook with `"matcher": "Edit|Write"` and a `command` such as `jq -r '.tool_input.file_path' | xargs npx prettier --write`. Claude Code pipes the event as JSON to the command's stdin, so `tool_input.file_path` (always an absolute path) names the file Claude just touched. I put it in the project's `.claude/settings.json` so everyone who clones the repo gets it, and check it shows up under `PostToolUse` in `/hooks`. Three limits matter: `PostToolUse` fires after the tool has run, so it fixes formatting rather than preventing anything; a successful run shows nothing in the conversation, so you confirm it by looking at the file or the debug log; and the matcher only sees the `Edit` and `Write` tools, so a file rewritten by a `Bash` command is not formatted. A `FileChanged` hook or a once-per-turn `Stop` scan covers those.

code

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

go deeper

for a junior

Recall the three parts: the PostToolUse event, the Edit|Write matcher and a command that reads the file path from stdin JSON. Know that the project's .claude/settings.json shares it with the team.

for a middle

Explain how the matcher is evaluated (exact list versus regex, case-sensitive), where tool_input.file_path comes from, and why a successful run is silent so you verify through the file or the debug log.

for a senior

Show you know the coverage gap: shell-made edits bypass the matcher, a broken formatter only raises a non-blocking notice, and a post-hoc hook never undoes a write. Say what closes each gap.

for a principal

Frame the hook as a developer-experience layer and decide where the real gate sits, in CI or a commit hook, so formatting stays enforced even for changes that never pass through Claude.

## What a format-on-edit hook is A **hook** in Claude Code is a handler that the harness itself runs at a fixed point in the agent's lifecycle. Because the harness runs it, it happens every time the event fires — unlike a line in `CLAUDE.md` asking Claude to "always run Prettier", which only shapes what the model tends to do. **Format-on-edit** is usually the first hook a team writes: every time Claude changes a file with its file tools, the project's formatter runs on that file, so diffs never carry formatting noise. ## The configuration The hook lives under the `hooks` key of a settings file: ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" } ] } ] } } ``` There are three levels of nesting: the **event** (`PostToolUse`), a **matcher group** that filters when it fires (`Edit|Write`), and one or more **handlers** (`type: "command"`) that run when it matches. ## How each piece works - **`PostToolUse`** fires after a tool call succeeds. That is the right moment: the file now holds Claude's new content. `PreToolUse` would run before the write exists. - **`"Edit|Write"`** contains only letters and `|`, so Claude Code treats it as a list of exact tool names. Matchers are **case-sensitive**: `edit|write` never matches. A pattern with other characters, such as `Edit.*`, becomes an unanchored regular expression and also catches `NotebookEdit`. - **stdin JSON**: the handler receives the event data on stdin. For `Edit` and `Write`, `tool_input.file_path` is the absolute path of the file. `jq -r` extracts it and `xargs` hands it to the formatter. - **Location**: `.claude/settings.json` is the shared project file, committed with the code. `~/.claude/settings.json` would apply to all your projects but nobody else's; `.claude/settings.local.json` is for personal, uncommitted tweaks. - **Feedback**: on success Claude Code shows nothing in the conversation and writes stdout to the debug log only, so you confirm the hook by checking the file, `/hooks`, or `claude --debug`. ## Where it falls short | Gap | Why | What covers it | |---|---|---| | Edits made through the shell | `sed -i`, redirects and code generators run in the `Bash` tool, which `Edit\|Write` does not match | a `FileChanged` hook on named files, a `Stop` hook that scans `git status --porcelain` once per turn, or also matching `Bash\|PowerShell` | | Undoing a bad write | the tool already ran | a `PreToolUse` guard, if the goal is to stop the write | | A broken formatter | a non-zero exit other than 2 is a non-blocking error: a notice appears and the edit stands | fix the tool; the edit is never rolled back | ## Making it robust 1. **Move logic into a script** once it grows past one line, stored under `.claude/hooks/` and referenced as `"$CLAUDE_PROJECT_DIR"/.claude/hooks/format.sh`, so the path resolves whatever directory Claude has moved into. 2. **Skip files the formatter does not own** — check the extension in the script before running it, so a Markdown or lock-file edit does not produce an error notice. 3. **Keep it fast.** A command hook's default timeout is 600 seconds, and a synchronous hook holds Claude until it finishes; formatting one file should take well under a second. 4. **Install `jq`** (or parse the JSON in Python or Node) on every machine that runs the hook; a missing `jq` turns into a `command not found` error notice on every edit. ## Variations teams use - **One formatter per language.** A script can branch on the file extension: Prettier for `.ts`, `gofmt` for `.go`, `ruff format` for `.py`, and exit 0 for everything else. - **Spawn less often.** On tool events a handler's `if` field narrows by tool and argument with permission-rule syntax, so `"if": "Edit(*.ts)"` starts the process only for TypeScript files. - **Exec form for scripts.** With `"args": []`, Claude Code spawns the script directly with no shell, so a project path containing spaces needs no quoting. - **Ship it in a plugin.** The same hook can live in a plugin's `hooks/hooks.json`, referencing `${CLAUDE_PLUGIN_ROOT}/scripts/format.sh`, so several repositories share one maintained copy. Format-on-edit is a convenience layer, not an enforcement boundary: pair it with the formatter check in CI or a git pre-commit hook if unformatted code must never land.

  • The file was edited but never reformatted. How do you find out why?
    Run `/hooks` and confirm the hook sits under `PostToolUse` in the settings file you expect. Check the matcher's case: `edit|write` never matches `Edit`. Look for a `PostToolUse hook error` notice, which usually means `jq` or the formatter is missing. For full detail, start with `claude --debug` (or run `/debug`) and read which hooks matched, their exit codes and their stderr.
  • How would you also format files Claude changes through shell commands?
    Matching `Edit|Write` cannot see them. Add a `Stop` hook that lists changed files with `git status --porcelain` and formats them once per turn, or also match `Bash|PowerShell` and do the same per call. For specific files, a `FileChanged` hook with literal filenames fires whatever wrote the file.

  • A PreToolUse hook is the right place to format the file Claude is about to write.
  • The Edit|Write matcher also catches files Claude rewrites with sed in a Bash command.
  • Claude Code passes the edited file's path to the hook as a positional argument like $1.
  • A successful formatter run prints a confirmation line into Claude's conversation.
  • Hook matchers ignore case, so edit|write works the same as Edit|Write.