Claude Code hooks for safer automation
Use Claude Code hooks for formatting, checks, notifications and guardrails without turning the workflow into hidden magic.

Put it into practice
What you will produce
A narrowly scoped hook with explicit trigger, input assumptions, command, failure behavior and a reversible config change.
- 01
Pick a deterministic trigger
Choose one repeatable event and a local check whose input is already available at that event; reject hooks that need broad context or an unpredictable network result.
Expected result: A single trigger and check with a clear reason to run automatically.
- 02
Inspect the command boundary
Read every script and referenced path, identify environment variables and possible writes, then decide how the hook reports a nonzero exit without masking the failure.
Expected result: A documented command path with known side effects and failure behavior.
- 03
Add a reversible configuration
Use the hook format supported by the installed Claude Code version, scope it to the intended event, and keep the script and configuration easy to disable or remove.
Expected result: A narrowly scoped hook change that can be reverted without cleanup ambiguity.
- 04
Exercise trigger and failure
Use a disposable fixture to trigger the hook once, make its check fail deliberately, and perform an unrelated action to confirm it does not run there; inspect output for secrets.
Expected result: Evidence of the intended trigger, visible failure and absence of unrelated execution.
Example structure to adapt
// .claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "node .claude/hooks/check-changed-file.mjs"
}
]
}
]
}
}
// .claude/hooks/check-changed-file.mjs
import { spawnSync } from "node:child_process";
import { isAbsolute, relative, resolve, sep } from "node:path";
let raw = "";
for await (const chunk of process.stdin) raw += chunk;
const event = JSON.parse(raw);
const changedPath = event.tool_input?.file_path;
if (event.tool_name !== "Write" && event.tool_name !== "Edit") process.exit(0);
if (typeof changedPath !== "string") process.exit(0);
const project = resolve(event.cwd);
const absoluteFile = resolve(changedPath);
const relativeFile = relative(project, absoluteFile);
if (isAbsolute(relativeFile) || relativeFile === ".." || relativeFile.startsWith(".." + sep)) process.exit(0);
if (!/\.(?:[cm]?[jt]sx?)$/.test(relativeFile)) process.exit(0);
const result = spawnSync("pnpm", ["exec", "prettier", "--check", relativeFile], {
cwd: project,
stdio: "inherit",
});
process.exit(result.status ?? 1);Illustrative example: confirm the schema and matcher in the official docs for your version. Replace the path with an actually changed file so the hook does not format the whole repository. Try it on a disposable branch; hooks execute commands in your environment.
Acceptance checks
- The trigger matches one deterministic use case and does not broaden unrelated work.
- The invoked script, paths, side effects and exit behavior are reviewed.
- A disposable fixture proves both successful triggering and visible failure.
- An unrelated action does not trigger the hook, and output contains no secret.
Limits and trade-offs
Hooks execute commands in your environment. Inspect scripts and paths, avoid secrets in logs, and test with a disposable change.
Official sources
Study hook patterns
Related guides
5 Claude Code Hooks I Use Daily
Claude Code hooks run shell commands on session start, file writes, and tool calls. Here are the 5 I use daily and how to configure them.
Most people discover Claude Code for the AI. They miss the hooks. Hooks are shell commands that execute automatically when something happens in your Claude Code session: a session starts, a tool runs, Claude stops. You define them in .claude/settings.json . They run silently in the background. Here are the 5 I use every day. What hooks look like The available events: SessionStart , UserPromptSubmit , PreToolUse , PostToolUse , Stop . Hook 1 Auto inject date on every prompt Event : UserPromptSubmit Claude doesn't have real time awareness. Every prompt gets the current date injected automatically. Useful for anything time sensitive: changelogs, deadlines, scheduling logic. Hook 2 Push notification when Claude stops Event : Stop Long tasks (refactors, test runs, analysis) can take 2–5 minutes. Without a notification I'd either stare at the screen or miss the result. This fires whenever Claude finishes a task, whether it succeeded or…
Read the guideCLAUDE.md: A Guide for Every Developer
One markdown file that makes AI coding assistants actually understand your codebase. Here's what to put in it.
There's a reason Claude Code writes great code in some projects and generic boilerplate in others. It's not the model. It's CLAUDE.md . It is one part of my Claude Code workflow: project conventions reduce guesswork, but they do not guarantee a speedup or remove the need to review the change. What it is CLAUDE.md is a plain markdown file that Claude Code reads at the start of every session. Think of it as the onboarding doc you'd give a senior contractor on day one: stack, conventions, rules, context. Without it, Claude infers patterns from what it sees in the codebase. Sometimes it infers correctly. Often it doesn't especially for implicit conventions your team just "knows". A CLAUDE.md makes your rules available without repeating them, but does not guarantee compliance: review the diff and run the checks. What to put in it 1. Stack and versions Simple but important. These…
Read the guideClaude Code Subagents: Parallel Agents
Learn when Claude Code subagents help, how to split parallel work, and how to configure a focused custom subagent without creating conflicts.
Subagents are useful when a task can be split cleanly: one agent searches the authentication code, another traces the database path, and the main conversation compares what they found. They add little to "read this file" or to work where every step depends on the same context. Short version: delegate independent research or a separate review when the results are worth the extra context and usage. Give each agent a narrow scope, the files or area to inspect, and a specific report format. Keep dependent work in the main conversation. Claude Code agents vs subagents Claude Code's documentation calls delegated workers subagents and uses Agent for the tool that starts them. When people search for Claude Code agents in this context, they usually mean subagents: workers that handle a delegated task in their own context and return a result to the main conversation. Claude Code's subagent documentation uses this terminology.…
Read the guide