Automate Your Dev Workflow with Claude Code Hooks
Hooks let you run custom shell commands when Claude Code takes specific actions. Auto-format on save, block dangerous edits, or inject context automatically.
Claude Code Hooks are shell commands that execute automatically in response to events. When Claude Code edits a file, runs a command, or starts a session, your hooks fire. This lets you build guardrails, enforce standards, and automate repetitive setup without manual intervention.
What hook events are available?
| Event | When it fires | Common use case |
|---|---|---|
| PreToolUse | Before Claude executes a tool | Block dangerous operations, validate inputs |
| PostToolUse | After Claude executes a tool | Auto-format edited files, run linters |
| Notification | When Claude sends a notification | Log to file, send to Slack |
| SessionStart | When a new session begins | Inject context, check environment |
| ConfigChange | When settings change | Validate configuration |
How do you create a hook?
Use the interactive menu or edit settings.json directly:
# Interactive hook setup
claude /hooks
# Or edit settings.json directly
# Project: .claude/settings.json
# Global: ~/.claude/settings.jsonHere's a settings.json with hooks configured:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "npx prettier --write "$CLAUDE_FILE_PATH"",
"description": "Auto-format edited files with Prettier"
}
],
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "echo $CLAUDE_FILE_PATH | grep -q \.env && echo 'BLOCKED: Cannot edit .env files' && exit 1 || exit 0",
"description": "Block edits to .env files"
}
],
"SessionStart": [
{
"command": "cat .claude/context-injection.md",
"description": "Inject additional context at session start"
}
]
}
}What are the most useful hooks?
1. Auto-format on edit
Run Prettier, Black, or gofmt every time Claude Code edits a file:
// PostToolUse hook
{
"matcher": "Edit|Write",
"command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
}2. Block sensitive file edits
Prevent Claude Code from modifying environment files, secrets, or critical configs:
// PreToolUse hook
{
"matcher": "Edit|Write",
"command": "echo $CLAUDE_FILE_PATH | grep -qE \"\.env|\.secret|credentials\" && exit 1 || exit 0"
}3. Re-inject context after compaction
When Claude Code compacts its context window, important details can be lost. A hook can re-inject critical information:
// PostToolUse hook for compaction
{
"matcher": "Compact",
"command": "cat .claude/critical-context.md"
}Start with the auto-format hook. It's the highest-value hook with the lowest risk. Once you're comfortable, add file protection and context injection.