Claude Code Hooks: Block Secrets and Destructive Commands
You wrote "never run rm -rf" and "never commit secrets" in CLAUDE.md, and one afternoon Claude Code did something close to both anyway. Instructions in a prompt file are requests, and a long session buries them. Claude Code hooks fix that by moving the rule out of the model's judgment and into a script that runs every time.
Claude Code hooks are user-defined shell commands that Claude Code runs automatically at specific points in a session, such as before a tool call, after a file edit, or when a prompt is submitted. A hook receives a JSON description of what is about to happen on stdin, and its exit code decides whether it proceeds. This article shows the contract, a working guard for destructive commands and secrets, and the limits you should know before trusting it.
What do Claude Code hooks actually do?
A hook runs your own code at a lifecycle event and can approve, block or annotate what Claude was about to do. The event you want for safety is PreToolUse, which fires after Claude has decided to call a tool (Bash, Edit, Write and so on) but before the tool runs.
Hooks live in a settings file: .claude/settings.json for the project, .claude/settings.local.json for your machine only, or ~/.claude/settings.json for every project. Each entry names an event, a matcher that selects tools by name, and the command to run. The official Claude Code hooks documentation is the source of truth for the full event list, and you should check it for the version you run.
The mechanism matters more than the syntax. A hook is deterministic: the same input always gives the same decision. A prompt rule is probabilistic, because the model reads it, weighs it against everything else in context, and may still choose otherwise.
How does a hook block a command?
A PreToolUse hook blocks a tool call by exiting with code 2. Anything it writes to stderr is passed back to Claude as the reason, so the model can adjust and try a safer approach instead of stalling.
The exit codes behave differently, and this is where most broken guards come from:
| Exit code | Effect on the tool call | What Claude sees |
|---|---|---|
| 0 | Proceeds normally | Nothing, unless the hook printed structured output |
| 2 | Blocked | Your stderr text, as the reason for the block |
| Any other non-zero (such as 1) | Not blocked; treated as a non-blocking error | The error is shown to you, and the tool still runs |
That last row is the failure mode worth remembering: a guard script that crashes, or that someone "fixes" to exit 1, fails open. The command it was meant to stop goes through, and the only evidence is a line in the transcript. Always test the block path, not just the allow path.
How do I write a guard against destructive commands?
Read the command from the JSON on stdin with jq, match it against a short list of patterns, and exit 2 on a match. This is a complete, working guard for the Bash tool:
#!/usr/bin/env bash
# .claude/hooks/block-destructive.sh
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // empty')
if printf '%s' "$cmd" | grep -Eq 'rm +(-[a-zA-Z]+ +)*-[a-zA-Z]*r|git +push .*--force|git +reset +--hard|DROP +(TABLE|DATABASE)'; then
echo "Blocked: destructive command. Propose a narrower, reversible alternative." >&2
exit 2
fi
exit 0Register it in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": ".claude/hooks/block-destructive.sh" }
]
}
]
}
}The stderr message is written for the model, not for you. Telling Claude what to do instead ("propose a narrower, reversible alternative") turns a dead end into a redirect, and in practice that is the difference between a guard that is helpful and one that makes the session loop.
How do I stop Claude from writing secrets into files?
Add a second PreToolUse hook on the file-writing tools and scan the content being written for known credential formats. Match Write|Edit, then read .tool_input.content for a Write or .tool_input.new_string for an Edit.
#!/usr/bin/env bash
# .claude/hooks/block-secrets.sh
input=$(cat)
text=$(printf '%s' "$input" | jq -r '.tool_input.content // .tool_input.new_string // empty')
if printf '%s' "$text" | grep -Eq 'AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36}|-----BEGIN [A-Z ]*PRIVATE KEY-----'; then
echo "Blocked: this looks like a credential. Read it from an environment variable instead." >&2
exit 2
fi
exit 0The three patterns are an AWS access key ID (AKIA followed by 16 characters), a classic GitHub personal access token (ghp_ followed by 36 characters), and a PEM private key header. They have fixed shapes, so false positives are rare. Generic patterns such as "any long random string" are a different matter: they flag hashes, UUIDs and lockfile integrity values, and a guard that cries wolf gets deleted within a week.
What is the fastest way to install and test a hook?
Install one hook at a time and prove it blocks before you trust it. This sequence takes a few minutes per hook:
- Save the script under
.claude/hooks/and runchmod +xon it. - Pipe a fake payload into it by hand:
echo '{"tool_input":{"command":"rm -rf /tmp/x"}}' | .claude/hooks/block-destructive.sh; echo $? - Confirm the printed exit code is 2 for a bad command and 0 for a harmless one such as
ls. - Add the matcher block to
.claude/settings.json. - Start a session and ask Claude to run a command your guard should block, then confirm it is refused and that Claude proposes an alternative.
- Commit the hook and the settings file so every teammate gets the same guard.
Step 2 is the one people skip. Testing the script outside Claude Code isolates your pattern logic from the hook wiring, so when something fails you know which half to debug.
Hooks, CLAUDE.md or permission rules: which should enforce a rule?
Use CLAUDE.md for guidance, permission rules for simple allow and deny lists by tool and path, and hooks when the decision needs logic or must be logged. They overlap, and the cleanest setups use all three for different jobs.
| Mechanism | Enforced by | Good for | Weak at |
|---|---|---|---|
| CLAUDE.md rule | The model's judgment | Conventions, style, project context | Anything that must never happen |
| Permission rules | Claude Code itself | Static allow or deny by tool or path | Inspecting what is inside a command or file |
| Hook | Your script | Pattern checks, formatting, tests, audit logs | Anything your script cannot parse |
Hooks differ from skills and subagents because they are not instructions to the model at all. They are code that runs around it, which is why they belong in a different part of your setup.
Where do hooks fall short?
A hook is a guardrail, not a sandbox. A regex over the command string cannot see through every indirection: rm hidden behind a variable, a script Claude writes and then executes, or a destructive call made through a language runtime rather than a shell command all slip past a string match.
Treat hooks as a way to catch the common, accidental mistakes reliably, and keep the real boundary elsewhere. Work in a branch, use credentials that cannot touch production, and keep backups. A guard that stops most accidents is valuable, but only if nobody believes it stops all of them.
Writing and maintaining a dozen of these is where the manual route gets tedious. Each hook needs its payload shape checked, its quoting tested, and its exit codes verified, and the hook contract is easy to misread. BuyCoded sells a Claude Code Hooks Pack for exactly this: 10 ready-to-install hooks that block secrets and destructive commands, auto-format, run the right tests, gate on typecheck and log every tool call, written in Bash and jq with the hook contract documented from captured payloads. If you also want Claude to follow your workflows, not just be fenced in, the Claude Code Skills Pack covers that side.
Is it worth buying hooks instead of writing them?
The honest objection is that a guard script is twenty lines and you can write it yourself, and for one or two hooks that is true. The two guards above are a fair starting point and cost you nothing.
The cost shows up in the long tail: hooks that run tests only for the files that changed, a typecheck gate that does not hang a session, and a tool-call log that stays readable. Those are the ones that take an afternoon each to get right, and a wrong one either blocks nothing or blocks everything. Buy a pack if you would rather start from tested scripts and edit them than debug your own from a blank file. Skip it if you only need the two guards in this article.
What should you do next?
Copy the destructive-command guard above into a project, run the fake-payload test from step 2, and watch Claude get refused once on purpose. Then browse the BuyCoded catalog, where the Claude Code Hooks Pack is listed with its full contents, license and refund terms, and pick the pack that fits the tool you use most.
Frequently asked questions
What are Claude Code hooks?
Claude Code hooks are shell commands that run automatically at set points in a session, such as before a tool call or after a file edit. Each hook receives a JSON description of the event on stdin, and its exit code can allow or block the action. They are configured in a settings.json file.
Which exit code blocks a tool call in a Claude Code hook?
Exit code 2 blocks the tool call from a PreToolUse hook, and whatever the script writes to stderr is passed back to Claude as the reason. Exit code 0 allows the call. Other non-zero codes such as 1 are treated as non-blocking errors, so the tool still runs, which is why a mistyped exit code makes a guard fail open.
Where do I put Claude Code hooks configuration?
Put hooks in .claude/settings.json to share them with a project, in .claude/settings.local.json for personal settings that stay out of version control, or in ~/.claude/settings.json to apply them to every project on your machine. Each entry names an event, a tool matcher, and the command to run.
Can a Claude Code hook stop Claude from leaking API keys?
Yes, for credentials with a known format. A PreToolUse hook on Write and Edit can scan the content for patterns such as AWS access key IDs, GitHub tokens or private key headers and exit 2 on a match. It cannot catch an arbitrary secret with no recognizable shape, so keep real keys out of the working tree.
Are hooks safer than putting rules in CLAUDE.md?
For rules that must never be broken, yes. A CLAUDE.md rule is read by the model and weighed against everything else in context, so it can be missed. A hook is code that runs the same way every time. Use CLAUDE.md for conventions and hooks for hard stops.