Add lifecycle hooks to enforce team standards
Hooks run at Claude Code lifecycle events (PreToolUse, PostToolUse, Stop) to enforce team conventions automatically. This tutorial builds a <code>block-secrets</code> hook step-by-step.
Prerequisites
- Comfortable with shell scripting (bash) or Python
- Familiar with slash commands (see first tutorial)
- Claude Code installed
What you'll learn
- What lifecycle hooks are and when they fire
- How to write a hook script (reads JSON, exits with a code)
- How to register hooks in .claude/settings.json
- How matchers scope hooks to specific tools
- How to test hooks before shipping them
- How to build a block-secrets hook from scratch
Hooks are the least-known part of Claude Code and arguably the most valuable for teams. They're scripts that run at lifecycle events (before a tool runs, after a session ends, etc.) and can block actions, log events, or trigger side effects.
This tutorial builds a real hook — block-secrets, which scans content being written and blocks the write if it looks like an API key or credential. By the end, you'll have a working hook and understand how to build more.
Claude Code fires events at specific points: PreToolUse (before Claude runs a tool), PostToolUse (after), SessionStart (session begins), Stop (session ends), plus a few others. Hooks are scripts you register to run on these events.
Hooks live in .claude/hooks/. Create the folder if it doesn't exist:
mkdir -p .claude/hooksHook scripts can be shell, Python, Node — anything you can execute. The convention is one file per hook, named after what it does.
A hook script reads a JSON payload from stdin, processes it, and exits with a status code. Exit 0 = allow the action. Exit 1 = block the action.
Create .claude/hooks/block-secrets.sh:
#!/usr/bin/env bash
# block-secrets: Blocks Write/Edit operations that look like they contain secrets.
set -euo pipefail
# Read the JSON event from stdin
input=$(cat)
# Extract the content being written
content=$(echo "$input" | jq -r '.tool_input.content // .tool_input.new_string // ""')
file=$(echo "$input" | jq -r '.tool_input.file_path // "unknown"')
# Skip if content is empty
[ -z "$content" ] && exit 0
# Patterns that suggest a secret
patterns=(
'AKIA[0-9A-Z]{16}' # AWS access key
'-----BEGIN [A-Z ]+PRIVATE KEY-----' # Private key
'sk_live_[a-zA-Z0-9]{20,}' # Stripe live secret key
'xoxb-[0-9]{11}-[0-9]{11}-[a-zA-Z0-9]{24}' # Slack bot token
'ghp_[a-zA-Z0-9]{36}' # GitHub personal access token
'(password|passwd|pwd)[[:space:]]*[=:][[:space:]]*[\x22\x27][^\x22\x27]{6,}' # password = "..."
)
# Check each pattern
for pattern in "\${patterns[@]}"; do
if echo "$content" | grep -qE "$pattern"; then
echo "block-secrets: Blocked write to $file — content matches pattern for secret" >&2
echo "Pattern matched: $pattern" >&2
exit 1
fi
done
exit 0
Make it executable:
chmod +x .claude/hooks/block-secrets.shHooks are registered in .claude/settings.json. This file tells Claude Code which hooks to run and on what events.
Create or edit .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/block-secrets.sh"
}
]
}
]
}
}Two things to notice: (1) matcher uses a regex to scope which tools trigger this hook — Write|Edit means it fires for Write and Edit but not other tools. (2) hooks is a list, so you can chain multiple scripts on the same event.
The hook receives a JSON payload on stdin describing the event. The structure varies by event type. For PreToolUse, you get:
{
"session_id": "...",
"transcript_path": "...",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.ts",
"content": "..."
}
}Different tools have different tool_input shapes. Write has {file_path, content}. Edit has {file_path, old_string, new_string}. Bash has {command}. Read has {file_path}. Check Claude Code docs for the full spec.
Our script uses jq to extract the fields we care about. This is more robust than parsing with grep because JSON escaping (newlines, quotes) is handled correctly.
Before shipping, test it in a session. Open Claude Code and ask it to write a file containing a fake AWS key:
# In Claude Code:
> Write a config file at src/config-test.ts with AWS_KEY = "AKIA1234567890ABCDEF"✓ Claude attempts to write src/config-test.ts
⛔ Hook blocked action:
block-secrets: Blocked write to src/config-test.ts — content matches pattern for secret
Pattern matched: AKIA[0-9A-Z]{16}
Claude Code: I couldn't write the file — a hook blocked it because the content
looks like it contains an AWS access key. If this is a test value, use a
placeholder instead like AWS_KEY = "<AWS_KEY>".The hook fired, blocked the write, and Claude even reasoned about how to work around it (by suggesting a placeholder). This is the pattern working correctly.
Try triggering the hook with different patterns — a fake private key, a Slack token, a Stripe key. Confirm each gets blocked. Then try normal file writes and confirm those pass through.
This is where you catch false positives (things blocked that shouldn't be) or false negatives (things allowed that shouldn't be).
Exit codes have specific meanings:
The distinction between exit 1 and exit 2 matters when Claude might retry. For "the content is bad, try again" issues, exit 1. For "this action is fundamentally not allowed," exit 2 to prevent retry loops.
- Exit 0: Allow the action. Normal.
- Exit 1: Block the action. Claude sees the error message (stderr) and can adjust and retry.
- Exit 2: Block and don't re-prompt. Claude sees the error but shouldn't retry the same action. Use for hard denials.
Commit both the hook script and the settings.json:
git add .claude/hooks/block-secrets.sh .claude/settings.json
git commit -m "feat(claude): add block-secrets hook"
git pushEveryone who pulls now has the hook active in their Claude Code sessions. Zero per-machine setup. That's the power of the .claude/ folder convention.
The hooks list is executed in order. First hook to exit non-zero blocks the action. Put your most-important safety checks first (block-secrets before auto-format, so you don't auto-format a secret file before blocking).
Recap
You built a hook that blocks secret leaks automatically. The pattern generalizes: write a script that reads JSON from stdin, processes it, exits with a status code, register it in settings.json with the right matcher.
Hooks are how team standards become invariants — instead of "we should really check for secrets" it's "secrets literally can't be committed." The 12 hooks in cctk's catalog cover the most common team needs; the pattern here lets you write your own for anything else.
The next tutorial covers MCP server integration — how to give Claude access to external services like Sentry, GitHub, and Datadog.
Common gotchas
- Hook doesn't fire: Check the matcher regex —
Write|Editmatches Write and Edit exactly. Wildcards need to be explicit. Also check the script is executable (chmod +x) and the path is relative to project root. - jq: command not found: Install jq (
brew install jqorapt install jq). Alternatively, use Python or Node for hook scripts — both have built-in JSON parsing. - Hook silently fails without blocking: Add
set -euo pipefailat the top of bash scripts. Without it, silent failures are common. Also check the script writes errors to stderr (>&2), not stdout. - False positives blocking legitimate writes: Tune the regex patterns. Common issue: too-broad patterns for "password" catch
PASSWORD_FIELD_NAME = "password". Require quotes + minimum length in the pattern. - Hook works locally but not in CI: CI might not have jq/Python installed, or the shell env differs. Test hooks in the same environment they'll run in. For CI-heavy usage, consider Python hooks (more portable).
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.