Skip to main content
hooksSource-backedReview first Safety Privacy

Auto Code Formatter Hook - Claude Code Hooks

Automatically formats code files after Claude writes or edits them using industry-standard formatters including Prettier 3.6.2+ (JavaScript/TypeScript/Web), Black or Ruff (Python), gofmt (Go), and rustfmt (Rust).

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://prettier.io/docs/, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/auto-code-formatter-hook.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Get file extension
EXT="${FILE_PATH##*.}"

# Format based on file type
case "$EXT" in
  js|jsx|ts|tsx|json|md|mdx|css|scss|html|vue|yaml|yml)
    # JavaScript/TypeScript/Web files - use Prettier
    if command -v prettier &> /dev/null; then
      prettier --write "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Prettier" >&2
    fi
    ;;
  
  py)
    # Python files - use Black
    if command -v black &> /dev/null; then
      black "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Black" >&2
    elif command -v ruff &> /dev/null; then
      ruff format "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Ruff" >&2
    fi
    ;;
  
  go)
    # Go files - use gofmt
    if command -v gofmt &> /dev/null; then
      gofmt -w "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with gofmt" >&2
    fi
    ;;
  
  rs)
    # Rust files - use rustfmt
    if command -v rustfmt &> /dev/null; then
      rustfmt "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with rustfmt" >&2
    fi
    ;;
esac

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/auto-code-formatter-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}

About this resource

Features

  • Supports multiple formatters including Prettier 3.6.2+ (JavaScript/TypeScript/Web), Black or Ruff (Python), gofmt (Go), rustfmt (Rust)
  • Language-specific formatting rules with automatic file type detection and appropriate formatter selection
  • Runs automatically after file modifications via PostToolUse hook with support for Write, Edit, and Multiedit operations
  • Preserves file permissions and structure while applying formatting changes in-place
  • Silent operation with optional feedback using stderr redirection for user notifications
  • Configurable timeout and error handling to prevent hanging on large files or slow formatters
  • Modern high-performance formatter support including Ruff (10-100x faster than Black) with Black-compatible formatting
  • Automatic formatter detection with fallback options (Black → Ruff for Python) ensuring formatting works in all environments

Use Cases

  • Maintain consistent code style across team projects with automatic formatting on every file modification
  • Automatically fix formatting issues after AI code generation ensuring all code follows project standards
  • Enforce project coding standards without manual intervention reducing code review time and friction
  • Support multiple programming languages in the same project with unified formatting workflow
  • Reduce code review friction by handling formatting automatically allowing reviewers to focus on logic and architecture
  • CI/CD pipeline integration for pre-commit formatting validation ensuring all committed code is properly formatted

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/auto-code-formatter-hook.sh
  3. Make executable: chmod +x .claude/hooks/auto-code-formatter-hook.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • jq installed (for JSON parsing)
  • Formatter tools: Prettier ^3.6.0 (npm i -D prettier), Ruff ^0.8.0 or Black ^24.0.0 (pip install ruff/black), gofmt (built into Go), rustfmt (built into Rust toolchain)
  • Language-specific runtime: Node.js (for Prettier), Python 3.8+ (for Ruff/Black), Go toolchain (for gofmt), Rust toolchain (for rustfmt)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/auto-code-formatter-hook.sh",
      "matchers": ["write", "edit", "multiedit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Get file extension
EXT="${FILE_PATH##*.}"

# Format based on file type
case "$EXT" in
  js|jsx|ts|tsx|json|md|mdx|css|scss|html|vue|yaml|yml)
    # JavaScript/TypeScript/Web files - use Prettier
    if command -v prettier &> /dev/null; then
      prettier --write "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Prettier" >&2
    fi
    ;;

  py)
    # Python files - use Black
    if command -v black &> /dev/null; then
      black "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Black" >&2
    elif command -v ruff &> /dev/null; then
      ruff format "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with Ruff" >&2
    fi
    ;;

  go)
    # Go files - use gofmt
    if command -v gofmt &> /dev/null; then
      gofmt -w "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with gofmt" >&2
    fi
    ;;

  rs)
    # Rust files - use rustfmt
    if command -v rustfmt &> /dev/null; then
      rustfmt "$FILE_PATH" 2>/dev/null
      echo "✅ Formatted $FILE_PATH with rustfmt" >&2
    fi
    ;;
esac

exit 0

Examples

Auto Code Formatter Hook Script

Complete hook script that automatically formats code files using Prettier, Ruff/Black, gofmt, or rustfmt based on file extension

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path // .tool_input.path // \"\"")
if [ -z "$FILE_PATH" ]; then exit 0; fi
EXT="${FILE_PATH##*.}"
case "$EXT" in
  js|jsx|ts|tsx|json|md|css|scss|html|vue|yaml|yml)
    if command -v prettier &> /dev/null; then
      prettier --write "$FILE_PATH" 2>/dev/null
      echo "Formatted $FILE_PATH with Prettier" >&2
    fi
    ;;
  py)
    if command -v ruff &> /dev/null; then
      ruff format "$FILE_PATH" 2>/dev/null
      echo "Formatted $FILE_PATH with Ruff" >&2
    elif command -v black &> /dev/null; then
      black "$FILE_PATH" 2>/dev/null
      echo "Formatted $FILE_PATH with Black" >&2
    fi
    ;;
  go)
    if command -v gofmt &> /dev/null; then
      gofmt -w "$FILE_PATH" 2>/dev/null
      echo "Formatted $FILE_PATH with gofmt" >&2
    fi
    ;;
  rs)
    if command -v rustfmt &> /dev/null; then
      rustfmt "$FILE_PATH" 2>/dev/null
      echo "Formatted $FILE_PATH with rustfmt" >&2
    fi
    ;;
esac
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable automatic code formatting on file writes, edits, and multiedits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit|Multiedit",
        "hooks": [
          {
            "type": "command",
            "command": "./.claude/hooks/auto-code-formatter-hook.sh"
          }
        ]
      }
    ]
  }
}

Prettier with Config File Fallback

Enhanced hook script that uses Prettier with explicit config file and fallback to default settings

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [[ "$FILE_PATH" == *.js ]] || [[ "$FILE_PATH" == *.ts ]]; then
  if command -v prettier &> /dev/null; then
    prettier --write --config .prettierrc "$FILE_PATH" 2>/dev/null || \
      prettier --write "$FILE_PATH" 2>/dev/null
    echo "Formatted with Prettier" >&2
  fi
fi
exit 0

Python Formatter with Timeout and Ruff Priority

Python formatting hook that prioritizes Ruff (faster) over Black with timeout protection for large files

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [[ "$FILE_PATH" == *.py ]]; then
  if command -v ruff &> /dev/null; then
    timeout 30s ruff format "$FILE_PATH" 2>/dev/null
    echo "Formatted with Ruff" >&2
  elif command -v black &> /dev/null; then
    timeout 30s black "$FILE_PATH" 2>/dev/null
    echo "Formatted with Black" >&2
  fi
fi
exit 0

Multiedit Support for Multiple Files

Hook script that handles Multiedit operations by formatting all files in the edits array

#!/usr/bin/env bash
INPUT=$(cat)
if echo "$INPUT" | jq -e ".tool_input.edits" &> /dev/null; then
  echo "$INPUT" | jq -r ".tool_input.edits[].file_path" | while read -r FILE_PATH; do
    if [[ "${FILE_PATH##*.}" == "js" ]]; then
      prettier --write "$FILE_PATH" 2>/dev/null
    fi
  done
fi
exit 0

Troubleshooting

Formatter runs but changes get overwritten immediately

Check for competing hooks or watchers. Verify PostToolUse timing - runs after file write completes. Add debouncing if multiple formatters conflict. Review hook execution order. Check if editor auto-format is enabled and conflicts with hook.

Prettier config ignored and default settings applied

Verify .prettierrc exists in project root or ancestor directories. Check config search path: prettier --find-config-path file.js. Set explicit config: prettier --config path/to/.prettierrc. Verify .prettierignore doesn't exclude the file.

Hook matches multiedit but only formats first file

Check if FILE_PATH is array in multiedit context. Parse all paths: jq -r '.tool_input.edits[].file_path'. Loop through each file for formatting. Verify jq parsing handles arrays correctly.

Formatter executable found but exits with permission denied

Verify formatter binary permissions: ls -la $(which prettier). Install locally: npm i -D prettier. Use npx to ensure correct binary: npx prettier --write file. Check node_modules/.bin is in PATH.

Silent failures with no feedback on format errors

Remove 2>/dev/null to expose stderr. Capture exit codes: prettier --write file || echo "Failed: $?" >&2. Add --loglevel debug for verbose output. Check formatter version compatibility.

Ruff format command not found but Black works

Install Ruff: pip install ruff or uv add ruff. Verify Ruff version supports format command: ruff --version (requires 0.1.0+). Check PATH includes Python bin directory. Use python -m ruff format as alternative.

Prettier 3.6+ formatting differs from previous versions

Prettier 3.6+ includes breaking changes. Review Prettier changelog for version-specific changes. Update .prettierrc config for new defaults. Test formatting with --check flag before applying: prettier --check file.js.

Formatting takes too long on large files causing timeouts

Add timeout wrapper: timeout 30s prettier --write file.js. Implement file size check before formatting: [ $(stat -f%z file.js) -lt 1000000 ]. Consider excluding large files in .prettierignore. Use formatter-specific performance options.

Source citations

Add this badge to your README

Show that Auto Code Formatter Hook - Claude Code Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/auto-code-formatter-hook.svg)](https://heyclau.de/entry/hooks/auto-code-formatter-hook)

How it compares

Auto Code Formatter Hook - Claude Code Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Automatically formats code files after Claude writes or edits them using industry-standard formatters including Prettier 3.6.2+ (JavaScript/TypeScript/Web), Black or Ruff (Python), gofmt (Go), and rustfmt (Rust).

Open dossier

Automatically creates timestamped backups of files before modification to prevent data loss. This hook runs before file editing operations (Edit, Write, Multiedit) and creates versioned backups in a centralized .backups directory with ISO 8601-compliant timestamps including nanoseconds for collision prevention.

Open dossier

A Claude Code hook that flags files exceeding complexity thresholds after you edit them — estimating cyclomatic complexity, line and function counts, and nesting depth (via ESLint's complexity rule and Radon).

Open dossier

A Claude Code SessionEnd hook that scans a project for dead code and writes a report to .claude/reports. It runs available tools per language: ESLint and Knip for JS/TS, autoflake or pylint for Python, Knip for unused npm dependencies, ripgrep for unreferenced src files, and jq to flag zero-coverage files.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs after edits to JS/TS/Python files and prints advisory warnings only; the line/function/brace counts are heuristics, not a substitute for ESLint or Radon run on the full project.Registered as a SessionEnd hook, so it runs automatically every time a Claude Code session ends. Invokes external tools via npx (ts-prune, Knip, eslint) and locally installed binaries (autoflake, pylint, vulture, jq, rg), which can trigger package downloads and execute project tooling. Defaults to DRY_RUN=true and only writes a report; setting DRY_RUN=false is intended to enable destructive cleanup, so review the report before changing it. Creates directories under .claude/backups and .claude/reports in the working tree.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Reads the contents of files you edit to compute complexity locally; it prints warnings to hook output and does not transmit code, but those messages can reveal file structure.Writes a dead-code report containing file paths, export names, and dependency names from the project to .claude/reports/dead-code-report.txt and echoes it to stderr. Running tools via npx may fetch packages from the npm registry over the network.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/auto-code-formatter-hook.sh && chmod +x .claude/hooks/auto-code-formatter-hook.sh
mkdir -p .claude/hooks && touch .claude/hooks/auto-save-backup.sh && chmod +x .claude/hooks/auto-save-backup.sh
mkdir -p .claude/hooks && touch .claude/hooks/code-complexity-alert-monitor.sh && chmod +x .claude/hooks/code-complexity-alert-monitor.sh
mkdir -p .claude/hooks && touch .claude/hooks/dead-code-eliminator.sh && chmod +x .claude/hooks/dead-code-eliminator.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/auto-code-formatter-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "preToolUse": {
      "script": "./.claude/hooks/auto-save-backup.sh",
      "matchers": [
        "edit",
        "write",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/code-complexity-alert-monitor.sh"
    }
  }
}
{
  "hooks": {
    "sessionEnd": {
      "script": "./.claude/hooks/dead-code-eliminator.sh"
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.