5.1 — Claude Code hooks: why CLAUDE.md is not enough
Since the start of this course, you've configured Claude Code with CLAUDE.md files and team conventions. That works most of the time. But CLAUDE.md is only advice. Claude reads it and interprets it, with no guarantee it will apply it. An LLM can forget an instruction, misread it or decide it doesn't apply here.
Claude Code hooks fill that gap. A hook is usually a shell command or a prompt sent to a model. Claude Code runs it itself at a precise point in the session. The model doesn't choose whether the hook runs. If you configure a hook that blocks file deletions, it runs on every deletion attempt.
CLAUDE.md is like a "30 mph" sign, which a driver can miss. A hook is like an automated speed camera, which checks every car.
Hooks are written as JSON in your settings files. .claude/settings.json applies to the project and is shared with the team. ~/.claude/settings.json applies to all your projects. .claude/settings.local.json applies to you alone on one project. A plugin, a skill or a subagent can also bring their own hooks.
Each hook attaches to a session event, such as startup, a tool call or the end of a response. Here is a first guardrail, which blocks rm commands.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "echo 'Command blocked by hook' >&2; exit 2",
"timeout": 5
}
]
}
]
}
}
The PreToolUse event fires before every tool call. The matcher selects the Bash tool, and the if field limits the hook to rm commands. Exit code 2 blocks the command. The message written to stderr becomes the reason Claude reads.
There are five hook types. The command type runs a script or a shell command. The prompt type asks a model for a verdict. The http type POSTs the event to a URL, and mcp_tool calls a tool on an MCP server. The agent type, still experimental, spawns a subagent that checks things before answering.
You'll mostly use command and prompt. A command hook is fast and always gives the same result for the same input. A prompt hook can judge an ambiguous case, but it costs a model call and can get it wrong. For a strict guardrail, pick command.
Key takeaways
• CLAUDE.md is advice that Claude tries to follow. A hook is run by Claude Code on every event it applies to.
• Hooks are written as JSON in the project, user or local settings files.
• A command hook that exits with code 2 blocks the action, and its stderr gives Claude the reason.
• There are five hook types: command, prompt, http, mcp_tool and agent. The first two cover most needs.
