Claude Code Hooks for Founders: 7 Ready-to-Paste JSON Snippets to Stop Dumb Mistakes

By Rakshit Yadav (@yadavrakshit60)•Updated Nov 2026•11 min read

Updated November 2026.

Short answer: Claude Code hooks are shell commands, configured in .claude/settings.json, that run automatically on lifecycle events like PreToolUse, PostToolUse, and Stop — before a tool call, after a file edit, on session stop — and a hook can block the action by exiting non-zero. Below are 7 copy-paste JSON snippets that stop the mistakes that actually cost founders time: a stray rm -rf, a committed .env, a migration nobody tested, a commit that skips lint, a deploy with no guard rail, a PR with no template, and a tool loop that quietly burns tokens.

Most "Claude Code hooks" posts explain the 12 lifecycle events like a reference manual. That's useful once. It's not useful at 11pm when you're about to git commit a .env.local file into a public repo. This post skips the primer and goes straight to the JSON. Want more than these 7 — idle notifications, cost tracking, PR guardrails? See the 15-hook catalog or the 20-hook ROI-ranked catalog.

What are Claude Code hooks?

A Claude Code hook is a shell command tied to a lifecycle event in .claude/settings.json. The three events you'll touch most: PreToolUse fires before a tool call and can block it outright (exit code 2); PostToolUse fires after a tool call completes and can only warn, not undo; Stop fires when a turn is about to end. No model judgment is involved — the hook is a deterministic gate, not a suggestion the agent can skim past.

Why hooks beat "just remember to be careful"

A rule or a CLAUDE.md instruction is advice the model reads. It can still be skimmed past on a long, tired turn — not because the model is careless, but because a 40-message session has a lot of context competing for attention. A hook is different: it's a shell command your OS runs on a matching event, with no model judgment involved on the hook's side. If the hook exits with status 2, Claude Code blocks the action and feeds the hook's stderr back to the model as the reason.

That distinction matters most for the handful of actions where "the model usually gets it right" isn't good enough — deleting files, touching secrets, pushing to main. For those, write a hook, not a reminder.

Claude Code hooks live in .claude/settings.json under a hooks key, keyed by lifecycle event (PreToolUse, PostToolUse, Stop, etc.), each with a matcher (a regex against the tool name) and a list of command-type hooks to run. All seven snippets below follow that shape — drop them into your own settings.json, merging into the hooks object if you already have one.

The lifecycle events these snippets use (and the ones they don't)

EventFires whenCan block (exit 2)?Used below
PreToolUseBefore a tool call executesYes — the only hard gateSnippets 1, 2, 3, 5, 6
PostToolUseAfter a tool call completesStops the turn, doesn't undo the actionSnippets 4, 7
NotificationClaude is waiting on youNo — informational onlyNot used here
UserPromptSubmitYou submit a new promptYes, before the prompt reaches the modelNot used here
StopA turn is about to endYes, but the action it'd be blocking already happenedSnippet 7
SubagentStopA subagent's turn endsSame as Stop, scoped to the subagentNot used here
PreCompactBefore context gets compactedNoNot used here
SessionStart / SessionEndSession opens or closesNoNot used here

This covers every event the 7 snippets touch. For the fuller reference — idle Notification hooks, a SessionEnd summary — see the 15-hook catalog, and check Anthropic's current hooks docs for the authoritative event list, since Claude Code has added events as the feature matured.

Snippet 1: block destructive bash commands

This is the one every founder wants after the first time an agent runs rm -rf on the wrong path. It intercepts every Bash tool call before execution and rejects anything matching a destructive pattern.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command' | grep -qE 'rm\\s+-rf\\s+/|rm\\s+-rf\\s+\\*|:(){ ?:\\|:& ?};:' && { echo 'Blocked: destructive command pattern detected' >&2; exit 2; } || exit 0"
          }
        ]
      }
    ]
  }
}

The hook reads tool_input.command from stdin JSON, checks it against a small denylist (recursive delete on / or *, a fork bomb), and exits 2 to block — which surfaces the stderr message back to Claude so it can retry with a safer command. Extend the regex for anything else you've been burned by (DROP TABLE, git push --force to main).

Snippet 2: block committing secrets

This one runs before any Bash call and specifically checks git commit and git add invocations for files that look like secrets, regardless of what your .gitignore says.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '^git (add|commit)' && echo \"$cmd\" | grep -qE '\\.env($|\\.[a-z]+)|credentials\\.json|\\.pem$|id_rsa' && { echo 'Blocked: command references a secrets-shaped file' >&2; exit 2; } || exit 0"
          }
        ]
      }
    ]
  }
}

This is a backstop, not a replacement for .gitignore — it catches the case where .env.production was never added to .gitignore in the first place, or someone runs git add -A after creating a new credentials file. Pair it with a real secret-scanning tool for anything beyond filename matching; this snippet only looks at the command text, not file contents.

Snippet 3: run tests before allowing a commit

Rather than trusting "the agent probably ran the tests," make the commit itself contingent on a green test run.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -q '^git commit' && ! npm test --silent > /tmp/claude-pretest.log 2>&1 && { echo \"Blocked: tests failed, see /tmp/claude-pretest.log\" >&2; exit 2; } || exit 0"
          }
        ]
      }
    ]
  }
}

Swap npm test for whatever your project actually runs (pnpm test, pytest, go test ./...). On a slow suite, scope this to a fast subset or a test:pre-commit script instead of the full run — a hook that takes two minutes on every commit attempt will get disabled out of frustration, which defeats the point.

Snippet 4: lint-on-save

Fires after any file write or edit and runs your linter against just the changed file, so style drift gets caught the moment it's introduced instead of at review time.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "file=$(jq -r '.tool_input.file_path'); case \"$file\" in *.ts|*.tsx) npx eslint \"$file\" --quiet || echo \"Lint warnings in $file\" >&2 ;; esac; exit 0"
          }
        ]
      }
    ]
  }
}

This one exits 0 even on lint warnings — it's informational, not a block, because blocking every edit on lint would make iteration painful. If you want it to actually block, change the final exit 0 to exit 2 inside the failing branch.

Snippet 5: deploy guard

Blocks any command that looks like a production deploy or a push straight to main, forcing a deliberate human step instead of letting an agent push on your behalf mid-session.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -qE '(vercel( |$).*(--prod|production)|git push.*(origin )?main$|railway up.*--environment production)' && { echo 'Blocked: production deploy/push requires manual confirmation' >&2; exit 2; } || exit 0"
          }
        ]
      }
    ]
  }
}

Adjust the patterns to match your actual deploy commands — this is a founder-pain-point list (Vercel prod, pushing straight to main, Railway prod environment), not an exhaustive one. The goal is a deliberate pause, not permanently banning deploys from the agent.

Snippet 6: PR template enforcement

Runs when a gh pr create command is about to execute and rejects it if the --body doesn't include your required sections, so you don't end up with a one-line PR description for a 400-line diff.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "cmd=$(jq -r '.tool_input.command'); echo \"$cmd\" | grep -q 'gh pr create' && ! echo \"$cmd\" | grep -q '## Test plan' && { echo 'Blocked: PR body missing required ## Test plan section' >&2; exit 2; } || exit 0"
          }
        ]
      }
    ]
  }
}

This checks the literal command text, so it only works if the PR body is passed inline (--body \"...\" or a heredoc in the same command) rather than from a separate file the hook can't see. If your workflow writes the body to a temp file first, point the grep at that file instead.

Snippet 7: cost-guard on long tool loops

Fires on Stop — when Claude is about to end its turn — and checks a counter file your PostToolUse hook increments, nudging you if a single session has run an unusually high number of tool calls (a common shape for a runaway retry loop).

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "count_file=/tmp/claude-tool-count-$$; echo $(( $(cat \"$count_file\" 2>/dev/null || echo 0) + 1 )) > \"$count_file\"; exit 0"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "count_file=/tmp/claude-tool-count-$$; n=$(cat \"$count_file\" 2>/dev/null || echo 0); [ \"$n\" -gt 150 ] && echo \"Heads up: this session ran $n tool calls — check for a retry loop before continuing.\" >&2; exit 0"
          }
        ]
      }
    ]
  }
}

This is a nudge, not a hard block — exiting 0 always lets the turn end, it just prints a warning to stderr so you see it. $$ scopes the counter file to the current shell session; swap it for a session-ID-keyed path if you want this to persist across a single Claude Code conversation rather than per invocation.

Wiring these into AgenticKit's hook config

AgenticKit doesn't ship its hooks as a template file the way it ships agents, skills, and commands — hooks are environment-specific enough (your test command, your deploy command, your repo's danger zones) that a one-size-fits-all file would either be too loose to matter or too strict to use. Instead:

  1. Create or open .claude/settings.json in your repo root.
  2. Merge the hooks key from whichever snippets above match your real failure modes — don't paste all seven blind if you don't run gh pr create from the CLI, for instance.
  3. If you're also running Cursor, note that Cursor's equivalent file is .cursor/hooks.json with a different event vocabulary (beforeShellExecution, beforeMCPExecution, afterFileEdit) — the hooks builder tool generates that format if you need both.
  4. Test each hook by deliberately triggering the blocked action once and confirming you see the block message, not a silent pass-through.

If you're deciding whether something belongs in a hook versus a rule or a skill in the first place, see Cursor Rules vs Skills vs Commands vs Hooks for the decision table — the short version is: if it has to be unconditional and tied to a specific action, it's a hook, not advice.

FAQ

What are Claude Code hooks? Shell commands configured in .claude/settings.json, keyed by lifecycle event (PreToolUse, PostToolUse, Stop, and others), that run automatically when a matching event fires — no prompt required. A PreToolUse hook can block the action it's gating by exiting with status 2; other events are informational only. They exist for the handful of actions where "the model usually gets it right" isn't good enough, like deleting files or pushing to main.

Do Claude Code hooks work the same way as Cursor hooks? No. Both run shell commands on lifecycle events, but the config files, event names, and matcher syntax differ — Claude Code uses .claude/settings.json with events like PreToolUse and PostToolUse; Cursor uses .cursor/hooks.json with events like beforeShellExecution and afterFileEdit. Port the intent, not the JSON, between the two.

How does a hook actually block an action? The hook command exits with status 2. Claude Code treats that as a block, reads the hook's stderr as the reason, and feeds it back into the conversation so the model can adjust. Exiting 0 lets the action proceed.

Will a PreToolUse hook slow down every single tool call? Yes, slightly — every matching tool call waits for the hook process to exit. Keep hook commands fast (a regex check, not a full test suite) unless you're deliberately gating something slow like Snippet 3, and scope the matcher narrowly so hooks you don't need aren't running on every call.

Can a hook see what the agent is about to do before it happens? For PreToolUse, yes — the hook receives the tool name and its input (e.g. the exact bash command, or the file path and new content for an edit) as JSON on stdin, which is how Snippets 1, 2, 5, and 6 inspect the command text before it runs.

What if I only want a warning, not a hard block? Exit 0 and print to stderr, as in Snippets 4 and 7. The message still reaches the model's context, but the action isn't stopped — useful for lint warnings or usage nudges where blocking would be more annoying than helpful.

Can I install a hook as part of a plugin instead of writing it myself? Yes — a Claude Code plugin can bundle a hook script alongside commands and skills, installed in one /plugin install. That's also the part of a plugin worth reading closely before installing, since a hook runs on every matching tool call rather than waiting for the agent to choose it; see the Claude Code plugins guide for the audit checklist.

Related Tools & Agents

🛠️ Free Tool: hooks-builder🛠️ Free Tool: security-scan🤖 Agent: security-auditor🤖 Agent: devops-engineer🤖 Agent: code-reviewer⚡ Command: /audit⚡ Command: /shipSkill: security-basicsSkill: project-conventions

Build your hooks.json visually

Pick an event and a preset, then download a hooks file instead of hand-writing the JSON.

Open the hooks builder →