Back to Hooks

Format on Save

PostToolUse

Run Prettier to format files after Claude Code writes or edits them

formattingprettiercode-quality
By Claude Code Community

Hook Script

#!/bin/bash
# Format on Save Hook
# Runs Prettier on files after they are written or edited

FILE_PATH="$CLAUDE_FILE_PATH"

# Check if file exists
if [[ -f "$FILE_PATH" ]]; then
  # Check if Prettier is available
  if command -v prettier &> /dev/null || [ -f "./node_modules/.bin/prettier" ]; then
    npx prettier --write "$FILE_PATH" 2>/dev/null
  fi
fi

Settings Configuration

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "./hooks/format-on-save.sh"
      }
    ]
  }
}

How to use

  1. Create a hooks directory in your project: mkdir hooks
  2. Save the hook script as hooks/format-on-save.sh
  3. Make it executable: chmod +x hooks/format-on-save.sh
  4. Add the configuration to your Claude Code settings
  5. Restart Claude Code to apply changes