Write your first Claude Code hook: block secrets before commit
Build a working hook from scratch — the file, the schema, the logic, and the test. By the end you'll have a hook preventing accidentally-committed secrets, and enough understanding to write more.
Prerequisites
- Claude Code installed and working on a project
- A text editor
- About 25 minutes of focused time
- No prior hook experience required
What you'll learn
- What hooks are and when they fire
- The hook file structure and required fields
- How to write matching logic that fires on the right events
- How to test a hook before shipping it
- The pattern for a whole class of "safety net" hooks
Hooks are the smallest, safest thing you can add to your Claude Code setup. They're also underused because "writing a hook" sounds harder than it is. This tutorial walks through building one from scratch — the file, the logic, and the test — so you finish with a working hook and enough understanding to write more.
The specific hook we'll build: block-secrets. When Claude Code is about to write a file, this hook checks the content for anything that looks like an API key or credential. If it finds one, it blocks the write and warns you. This prevents the class of "oops, I asked Claude to modify a config file and it accidentally hardcoded a key" bugs — a small but real problem.
Claude Code hooks are small definitions that run before or after specific events — before a tool is used, after a file is written, before a command executes. They're Claude's equivalent of Git hooks or IDE extensions: small, focused pieces of code that intervene at specific moments.
Common uses:
- Safety nets: block writes that contain secrets, prevent commits to protected branches
- Logging: record what tools got used, for auditing
- Enforcement: require certain conditions be met before a file is written
- Notification: ping Slack when specific events happen
Think of hooks as the answer to "before X happens, check something / do something / warn someone." They're small on purpose — one hook does one thing.
Before writing one, look at one. If you have cctk installed, browse .claude/hooks/ to see what shipped. Otherwise, here's the shape:
---
description: Example hook — logs when files are written
event: PostToolUse
matcher:
tool: Write
---
# Log file writes
After Claude Code writes a file, log the file path and timestamp
to `.claude/write-log.txt`.
Use these values:
- ${tool.args.path} for the file path
- Current timestamp
That's a whole hook. Frontmatter (metadata), then Markdown describing what to do. The framework handles the mechanics — reading the frontmatter, dispatching on the event, expanding the variables.
Before writing code, plan on paper:
- Event: PreToolUse — we need to check before the write happens, not after
- Matcher: tool is Write or Edit (both create file content)
- What to check: the content being written for secret-like patterns
- What to do if matched: block the operation, tell Claude why
- Non-goals: not a full audit, not a git-history scan (see /security-secrets-scan for that)
The hook is simple because it does one thing. Trying to do more (log stats, scan history, check gitignore) would make it fragile. One hook, one job.
Create the file at .claude/hooks/block-secrets.md:
---
description: Block writes that appear to contain credentials or API keys
event: PreToolUse
matcher:
tool: Write
tool: Edit
---
# Block secret leaks
Before allowing a Write or Edit, inspect the content for patterns
matching common credentials.
## Patterns to detect
Block if the content contains any of:
- `AWS_SECRET_ACCESS_KEY = ""`
- API keys in the format `sk-<20+ chars>` (OpenAI, Anthropic style)
- API keys in the format `sk_live_` or `sk_test_` (Stripe)
- GitHub tokens: `ghp_<36 chars>`, `gho_`, `ghs_`, `ghr_`
- Slack tokens: `xox[bpars]-`
- Private key blocks: `-----BEGIN PRIVATE KEY-----`
- Long base64 strings assigned to variables named `password`, `secret`,
`token`, `key` (case-insensitive)
## When matched
Block the operation. Respond:
"Blocked: this write appears to contain a credential.
Move it to an environment variable or secret manager instead.
Detected pattern:
Suggested fix: use process.env.MY_VAR (or equivalent) and set the
actual value in .env (which should be in .gitignore).
If this is a false positive (e.g., an example in documentation),
you can disable this hook temporarily by removing it from
.claude/hooks/, or you can adjust the patterns above."
## When to skip (false positives)
Skip the check if the file is:
- A README, docs/, or example directory
- A test file with a value clearly labeled as fixture/mock
- A file where the value is a placeholder (`YOUR_KEY_HERE`, `xxx`, `changeme`)
If uncertain, block and let the user override.
A few things to notice:
- The frontmatter has
event: PreToolUseso it fires before the write - The
matchercatches both Write and Edit (they're different operations but both create content) - The body describes what to do in plain English — Claude reads and executes
- False-positive handling is explicit: the hook lists common false positives (docs, tests) and describes what to do about them
Restart your Claude Code session so it picks up the new hook. Then try to trigger it:
> Create a file at src/config/aws.ts that sets
AWS_SECRET_ACCESS_KEY = "AKIA1234567890EXAMPLE"Expected: Claude Code refuses, showing the block message from the hook. The file doesn't get written.
Now try a legitimate case:
> Update README.md to add an "Environment variables" section
with an example showing:
AWS_SECRET_ACCESS_KEY=your-key-hereExpected: allowed. The hook recognizes README as documentation and the value your-key-here as a placeholder.
A hook that blocks everything is annoying; a hook that blocks nothing is useless. Test both: it should catch real secrets and skip legitimate placeholder cases. If it gets either direction wrong, adjust the false-positive list.
Try three more scenarios in your own session: (1) a test file with a mock token, (2) a config file with a real-looking token, (3) a docs file explaining API keys. The hook should handle all three appropriately.
The first version of any hook will have false positives. When you find one — Claude blocked a legitimate write — don't just disable the hook. Update it to handle that case.
Common false positives you might encounter:
- Test fixtures with realistic-looking but fake data → add "test files" to skip list
- Migration scripts that reference historical values → add specific migration paths
- Config schemas that show what a config should look like → recognize schema files
Each iteration makes the hook a bit smarter. After a few weeks of use, it'll rarely fire on legitimate writes and reliably catch real leaks. This is the discipline: hooks improve through use, not through initial cleverness.
git add .claude/hooks/block-secrets.md
git commit -m "chore: add block-secrets hook
Prevents accidentally-committed credentials by checking file writes
for common secret patterns. Skips docs, tests, and placeholder values."Now everyone on the team gets the hook automatically when they pull. New team members get it as part of their setup. If the hook needs updating, that's a normal PR.
One hook is a small win. Ten hooks (block-secrets, log-writes, warn-on-force-push, require-tests-for-new-endpoints, etc.) is a genuinely different working environment — one where whole classes of mistakes just can't happen. Start with one; add more as you notice needs.
Recap
You wrote your first Claude Code hook: block-secrets. It fires before writes, checks content for credential patterns, blocks matches, and handles common false positives.
The pattern generalizes to any "safety net" hook: pick an event, define what to check, describe what to do on match, list false positives. Small hooks that do one thing well.
This one hook prevents a whole class of mistake. The next hook you write prevents another. Cumulatively, your Claude Code environment gets safer as your hook library grows.
Common gotchas
- Hook doesn't fire when expected: Check the matcher. The tool name must match exactly (Write, Edit, Bash — case sensitive). Also check the event — PreToolUse fires before, PostToolUse fires after. Getting these wrong means the hook is silent.
- Hook fires on wrong events: Matcher is too broad. Add more specific conditions — file path patterns, content patterns, whatever narrows the fire to only the cases you want.
- False positives block legitimate work: Expected initial state. Add the false-positive case to the skip list. If you're getting many false positives, the pattern might be too aggressive — narrow it, add better context checks.
- Hook silently ignored: Restart your Claude Code session — hooks are read at startup. Check for YAML syntax errors in the frontmatter. If neither, check the hook directory location (should be .claude/hooks/).
- Team wants to disable the hook: Listen to why. Sometimes it's a real problem (too many false positives). Sometimes it's annoyance at any friction. Address the real problem; don't just disable safety measures under pressure.
Get cctk to skip the boilerplate
Everything in this tutorial is already scaffolded in cctk — commands, subagents, hooks, MCP configs. Install and customize instead of starting from scratch.