HookStackGitHub
Back to catalogue
ValidationPostToolUse· Write|EditPostToolUseAfter tool execution · non-blocking· non-blocking

Automatic formatting after write

Every file lands already Prettier-clean

After every file write or edit, runs Prettier on the modified file to ensure consistent formatting without agent intervention.

What does the Automatic formatting after write hook do?

Automatic formatting after write is a Claude Code PostToolUse hook matching Write|Edit. It fires automatically at that lifecycle event — outside the model, so it can't be skipped or forgotten. Every file lands already Prettier-clean.

Use cases

  • Style consistency
  • Reduced diff noise
  • Code quality

Tags

#validation#prettier#format#quality

settings.json fragment

{
  "hooks": {
    "PostToolUse": [
      {
        "hooks": [
          {
            "command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/autoformat.mjs",
            "type": "command"
          }
        ],
        "matcher": "Write|Edit"
      }
    ]
  }
}

Script · .claude/hooks/autoformat.mjs

#!/usr/bin/env node
// Formate le fichier avec prettier après écriture (PostToolUse Write|Edit)
import { readFileSync } from 'fs';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';

function defaultExec(cmd) {
  execSync(cmd, { stdio: 'ignore', timeout: 10_000 });
}

export function run(input, { exec = defaultExec } = {}) {
  const filePath = input.tool_input?.file_path ?? '';
  if (!filePath) return null;

  try {
    exec(`npx --no-install prettier --write "${filePath}"`);
    return { formatted: filePath };
  } catch {
    // prettier absent ou erreur de format — non bloquant
    return null;
  }
}

/* v8 ignore next 4 */
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const input = JSON.parse(readFileSync(0, 'utf8'));
  run(input);
}