How to Set Up Claude Code Hooks
Hooks are deterministic automation that fires on every event — no prompting required. Use them to block dangerous commands, track every edit, restore context on session start, and build a safety net that never forgets.
What Are Hooks?
Hooks are scripts that Claude Code executes automatically when specific events occur. Unlike prompt-based instructions that Claude may interpret loosely, hooks are deterministic — they run the same code every single time the event fires.
Think of them as git hooks for your AI workflow. A pre-commit hook blocks bad commits; a PreToolUse hook blocks dangerous tool calls before they execute.
Hook Types
Claude Code supports several hook points. Each fires at a different moment in the session lifecycle:
Setting Up settings.json
Hooks are configured in .claude/settings.json under the hooks key. Each hook has a matcher (which events to intercept) and a command (what script to run).
Safety Hooks
The highest-value hook is a PreToolUse safety gate on the Bash tool. This intercepts every shell command and blocks dangerous patterns before they execute.
This runs as code, not as a suggestion. Even if Claude is convinced it should run rm -rf /, the hook stops it.
Intelligence Hooks
PostToolUse hooks let you record what Claude does. Every file edit, every command, every tool call — logged and structured.
Edit Tracking
- →Log every file edit with timestamp and diff summary
- →Build an audit trail of all changes per session
- →Feed edit history into memory for smarter context
Metrics Collection
- →Count tool calls per session for usage analysis
- →Track which files are edited most frequently
- →Measure session duration and productivity patterns
Session Hooks
SessionStart and SessionEnd hooks bookend every conversation. Use them to restore context at the start and consolidate memory at the end.
The PreCompact hook is equally critical — it fires before Claude's context window is compressed, giving you a chance to save state that would otherwise be lost.
Writing Hook Handlers
Hook handlers are Node.js scripts (typically .cjs files) that receive event data on stdin and write results to stdout as JSON.
Testing Your Hooks
Always test hooks before relying on them. The simplest approach is to pipe mock event data into your handler:
After verifying with mock data, trigger real events in a test session and check your log files to confirm the hooks fired.
Common Mistakes
Get Pre-Built Hook Templates
The AI Starter Package includes battle-tested hook handlers for safety gates, edit tracking, session memory, context restoration, and metrics collection — ready to drop into any project.