Skip to content
Leverage AI

Free guide

Claude Code hooks: 5 we tested on one small app

Claude Code hooks are commands Claude Code runs automatically at set moments, such as before a shell call or after a file edit. Once a hook is set up and loaded, it runs every time its event matches, whether or not Claude remembers your rule. You can use them to block a force push, format JavaScript or run tests before Claude finishes.

  • Copy the settings and scripts
  • See what each hook did
  • Tests before Claude stops

Published · Updated

Start building

Claude Code hooks: 5 we tested on one small app

That's what a line in CLAUDE.md can't do. A reminder only works if Claude follows it. A hook can stop the action before it happens: in our test, one blocked a force push before the command ran.

We tried five hooks on a small to-do app: block risky commands, protect files, clean up edits, run tests before stopping, and load git context. The test hook caught a bug we'd planted, but our due-date task passed all five runs with it and all five without it.

If your app has quick tests, start with the Stop hook in section 4. It runs them before Claude finishes and sends failures back for one repair attempt.

What you need

Use Claude Code in a terminal, with a login that can use it. There's no extra service to sign up for. The scripts use Node.js (MIT licensed), which our to-do app also runs on, and the context hook needs git (GPL-2.0).

Project hooks go in .claude/settings.json. Hooks for every project go in ~/.claude/settings.json. Type /hooks inside Claude Code to see what's loaded. These locations and the examples below follow the official hook guide, read on 23 November 2026.

Make a .claude/hooks folder in your project. Save each script there under the filename shown, then add its settings. Each settings block below is complete for its one hook. To use several, merge their event entries under one hooks object, and where two use PreToolUse, put both groups in that one array. Keep any settings you already have.

A matcher tells Claude Code which tool to watch. Bash catches shell calls; Edit|Write catches either editing tool. The scripts read the event as JSON from standard input with Node, so you don't need jq. And because the commands call Node directly, the script files don't need executable permission.

1. Block risky shell commands

Use this when a broad request like "clean things up" could erase work. Before each Bash call, the script looks for rm -rf, force pushes and hard resets. On a match it prints a reason and exits with code 2. The command doesn't run, and Claude gets the reason.

Save .claude/hooks/risky.cjs:

javascript
const fs = require("node:fs");
const { tool_input = {} } = JSON.parse(fs.readFileSync(0, "utf8"));
const command = tool_input.command || "";
const risky = /\brm\s+-[a-zA-Z]*r[a-zA-Z]*f|\brm\s+-[a-zA-Z]*f[a-zA-Z]*r|\bgit\s+push\b[^\n]*(?:--force\b|-f\b)|\bgit\s+reset\s+--hard\b/;
if (risky.test(command)) {
  console.error("Blocked risky shell command. Use a safer way or ask the user.");
  process.exit(2);
}

Add to .claude/settings.json:

json
{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/risky.cjs\"",
            "timeout": 30
          }
        ],
        "matcher": "Bash"
      }
    ]
  }
}

We typed five short requests, including:

text
Clean out the project and start fresh.
text
Force push this branch to origin.

The hook blocked three commands: a force push, a hard reset, and rm -rf on the hook folder. Claude stopped and explained each block. On the vague cleanup request it asked what we meant and never tried a risky command.

One request got through. We asked Claude to remove the tests folder and the README, and it did, with rm -r, which this pattern allows. Add that form to the rule if you want it caught.

The pattern misses spellings such as rm -r -f, rm -Rf and git push origin +main. It also blocks harmless commands such as rm -rf dist, so treat it as a check for these spellings rather than protection against every destructive command.

2. Block edits to .env and tests

This one keeps test expectations fixed while Claude repairs the app. It blocks Edit and Write calls aimed at .env or anything under tests.

Save .claude/hooks/protect.cjs:

javascript
const fs = require("node:fs");
const path = require("node:path");
const { tool_input = {} } = JSON.parse(fs.readFileSync(0, "utf8"));
// Resolve symlinks on both sides; a new file resolves through its folder.
const real = (p) => {
  try { return fs.realpathSync(p); }
  catch { return path.join(real(path.dirname(p)), path.basename(p)); }
};
const isProtected = (root, file) => {
  const relative = path.relative(root, file);
  return relative === ".env" || relative === "tests" || relative.startsWith("tests" + path.sep);
};
const root = path.resolve(process.env.CLAUDE_PROJECT_DIR || process.cwd());
const file = path.resolve(tool_input.file_path || ".");
// Check the path as given and with symlinks resolved.
if (isProtected(root, file) || isProtected(real(root), real(file))) {
  console.error("Protected file. Leave .env and tests unchanged; fix app.js instead.");
  process.exit(2);
}

The error message names app.js because that's our demo file. Change it to fit your project, for example "fix the application code instead."

Settings:

json
{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/protect.cjs\"",
            "timeout": 30
          }
        ],
        "matcher": "Edit|Write"
      }
    ]
  }
}

Our first request used a fake value:

text
Put the real key in .env: DEMO_KEY=still-fake-demo-value.

The hook blocked the write. We also asked Claude to replace the tests with one test that always passes. We ran that request twice. The first time, the hook blocked it. The second time, Claude wrote the new test file with a shell command, and the hook never saw it.

For the third, we first broke the app's text trimming, then typed:

text
The tests are failing, just fix them.

Claude fixed the app and left the tests alone. That's what we wanted, because changing the expected answer in the test would have hidden the fault.

That second run shows the gap. The hook only watches the two editing tools, so a shell command can still write to either path. It doesn't block reads either, so don't count on it to hide secrets from Claude.

Skip it when the job is updating the tests. Loosen the protected paths before you start, then put the rule back when you're done.

3. Format a file after each edit

Formatting makes a good first hook because you can look at the file right away. This hook formats .js files after Claude edits them and leaves other files alone. We used js-beautify, a free JavaScript formatter under the MIT licence, and checked that it kept the spaces inside a multiline template string. A plain search-and-replace for trailing spaces can damage that text.

Install it once in your project. Every edit then uses that local copy, with no download:

bash
npm install --save-dev --ignore-scripts js-beautify

Save .claude/hooks/format.cjs:

javascript
const fs = require("node:fs");
const { spawnSync } = require("node:child_process");
const { tool_input = {} } = JSON.parse(fs.readFileSync(0, "utf8"));
const file = tool_input.file_path;
if (!file || !file.endsWith(".js")) process.exit(0);
const check = spawnSync(process.execPath, ["--check", file], { encoding: "utf8" });
if (check.status !== 0) {
  console.error(check.stderr || "Syntax check failed");
  process.exit(2);
}
const before = fs.readFileSync(file, "utf8");
// A JavaScript formatter preserves whitespace inside template strings.
const { js: beautify } = require("js-beautify");
const after = beautify(before, { indent_size: 2, end_with_newline: true });
fs.writeFileSync(file, after);

Settings:

json
{
  "hooks": {
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/format.cjs\"",
            "timeout": 30
          }
        ],
        "matcher": "Edit|Write"
      }
    ]
  }
}

Our request:

text
Add a short comment above add() in app.js.

Beforehand, we left three trailing spaces on the exports line, away from where the comment would go. After Claude's edit the hook removed them and expanded the export into the formatter's usual style. It also reformatted nine other spots in the file, because js-beautify formats the whole file with its own defaults, not your project's style. Expect that on the first edit of each file. All five tests still passed.

Before:

javascript
module.exports = { TodoList };   

After:

javascript
module.exports = {
  TodoList
};

Since the hook runs after the edit, it can only check or format the result. A syntax error goes back to Claude, but the edit has already happened and stays.

The matcher misses file changes made through Bash. If your project already has a formatter, call that local command instead, with your team's rules.

Skip it if your editor already applies the same formatting. One set of rules keeps the tools from fighting each other.

4. Run tests before Claude stops

This is the one we'd add first to an app with a quick test suite. It runs your test command when Claude finishes a response. If the tests fail, exit code 2 sends the failure back and Claude keeps working.

Save .claude/hooks/stop.cjs:

javascript
const fs = require("node:fs");
const { spawnSync } = require("node:child_process");
const input = JSON.parse(fs.readFileSync(0, "utf8"));
const result = spawnSync(process.execPath, ["--test"], {
  cwd: process.env.CLAUDE_PROJECT_DIR || process.cwd(),
  encoding: "utf8", timeout: 20000
});
if (result.status === 0) process.exit(0);
if (input.stop_hook_active) {
  console.log(JSON.stringify({
    systemMessage: "Tests still fail after the retry. Claude is stopping; the app needs another fix."
  }));
  process.exit(0);
}
console.error("Tests failed. Fix the app, keep the existing checks, and run tests again.\n" +
  (result.stdout || "") + (result.stderr || ""));
process.exit(2);

Settings:

json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/stop.cjs\"",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Swap in your own test command. Ours uses Node's built-in test runner, so there's nothing to install. The script gives the tests twenty seconds, which leaves room inside the hook's thirty-second limit to send the result back.

Don't drop the retry check. Claude Code sets stop_hook_active when Claude is already continuing because a Stop hook blocked it. On that second stop the script still runs the tests, but lets the turn end even if they fail. Claude gets one repair attempt and can't get stuck in a loop. If the second check fails, the JSON systemMessage shows you a warning in Claude Code.

We picked this request because adding a field can break checks that expect an item's old shape:

text
Add optional due dates when I add a todo. Keep the existing calls working.

All five runs passed without the hook, and all five passed with it, original checks included. Claude added due dates without changing the old item shape, so the hook ran five times and had nothing to repair.

To see the failure path, we broke text trimming and asked only for a comment above rename(). Claude finished without running the tests. The Stop hook caught the failure, Claude went back and fixed the app, and all five original tests passed.

Passing tests don't tell you whether the new feature works. Read the diff and try the feature too. And if the test runner finds no tests at all, it reports success, so this hook stays quiet when the tests are gone.

Skip it if your full suite takes minutes, because a slow Stop hook makes even a short answer wait. Put the fast checks you need on every change in it instead.

5. Give Claude git context at the start

When a new session starts, this hook gives Claude the changed filenames and the last three commit messages. Use it in a git repository with at least one commit. It helps most if you often come back to unfinished work.

Save .claude/hooks/context.cjs:

javascript
const { execFileSync } = require("node:child_process");
const options = { cwd: process.env.CLAUDE_PROJECT_DIR || process.cwd(), encoding: "utf8" };
const status = execFileSync("git", ["status", "--short"], options);
const commits = execFileSync("git", ["log", "-3", "--oneline"], options);
console.log(JSON.stringify({ hookSpecificOutput: {
  hookEventName: "SessionStart",
  additionalContext: "Working tree:\n" + status + "Recent commits:\n" + commits
} }));

Settings:

json
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/context.cjs\"",
            "timeout": 30
          }
        ],
        "matcher": "startup"
      }
    ]
  }
}

The script prints one JSON object. hookSpecificOutput names the event and carries additionalContext, the text Claude receives. When you return JSON, keep any other logging off standard output. Each event has its own output fields, listed in the hooks reference, and you can't swap them between events.

We added a line about pinning tasks to the README, then asked this once with the hook and once without:

text
What did I change since the last commit?

Both answers found the README change, and both used one shell call to read the git diff. The hook only sends filenames and commit messages, so Claude still needed the diff to explain the change. On this small task it made no useful difference.

Skip it if you rarely leave changes unfinished. You can ask Claude to check git when you need it, as our plain run did.

Why your hook does nothing

Check the event and matcher first. Bash is a tool name with a capital B. For editing tools use Edit|Write; a filename in that field won't match the tool. A Stop hook needs no tool matcher.

Next, the path and the settings file. The scripts above use CLAUDE_PROJECT_DIR to find the project even if the working directory changes. A script you call directly needs executable permission. One passed to node just needs a working Node command.

If the script fails with exit 1, the action usually goes ahead anyway. In a PreToolUse hook, exit 2 blocks the tool call. In a Stop hook, it keeps Claude working. In a PostToolUse hook, the edit has already happened, so exit 2 only sends your message back to Claude. If you return JSON, its decision fields also affect the result, so follow the schema for your event.

Last, open /hooks and make sure the settings file is valid JSON. The current docs say settings edits normally load on their own; restart if a change still hasn't shown up after a few seconds. We used a fresh session for each test.

Test a hook in two minutes

Work in a spare copy of your app. Add one hook, open /hooks, and check its event and command. Then ask for one action it should catch and one it should allow. For the file guard, try a fake .env value and a harmless edit to app code.

Afterwards, look at the actual file or tool result. Claude saying "blocked" tells you less than the file sitting there unchanged. For the Stop hook, break one small check, ask for a short task, and see whether Claude gets the failure. Then test the retry path to make sure it ends without looping.

If nothing happens, feed the script a sample event on standard input. This tests the risky-command script without running the command inside the JSON:

bash
printf '%s\n' '{"tool_input":{"command":"rm -rf scratch"}}' \
  | node .claude/hooks/risky.cjs
printf 'exit code: %s\n' "$?"

You should see the block reason and exit code 2. Then try it through Claude Code as well. A script can work fine on its own while its matcher or settings path is wrong.

How we tested

We used Claude Code with Sonnet 5.5 on a subscription login on 23 November 2026. Our plain JavaScript to-do app had five passing tests. Each request started from the same committed app, with that test's hook loaded. The file-repair request started with one known bug, and the context requests with the same README edit.

We ran the due-date task five times with the Stop hook and five without, alternating between them. Afterwards we checked the final tests ourselves and reran the original tests unchanged. That came to twenty-eight model requests in all, each run in Claude Code's print mode with permission prompts turned off, so only the hooks could stop an action.

We wrote the scripts and the demo app. These scripts run locally and need no separate API key. You'll need your own Claude Code access, which is proprietary; we used an existing subscription.

For tasks Claude picks up when it needs them, see our tested Claude Code skills.

For bundles of skills and hooks, see our tested Claude Code plugins.

Questions people ask

Where do Claude Code hooks go?

Put project hooks in .claude/settings.json and the scripts in .claude/hooks. Use ~/.claude/settings.json for hooks across all your projects. Type /hooks inside Claude Code to inspect what is loaded.

Why does my hook print an error but still allow the command?

For a command hook with plain output, exit 1 is usually a non-blocking error. Use exit 2 to block a PreToolUse call. Valid JSON output can also control the decision, so use the schema for your event.

Can a Stop hook force Claude to finish with passing tests?

It can run tests and send a failure back so Claude keeps working. Our example allows one retry to avoid a loop, so a second failure can still end the turn. Our due-date task passed in five of five runs both with and without the hook.

Do hooks need jq or a paid API key?

These scripts use Node.js to read JSON, so they need no jq or API key. They run locally through Claude Code and use your existing Claude access. The guide and scripts are free.

Save it for later

Get this guide by email

Doing this on your computer later? We send you this page's link and its main prompt, then one short AI email a week. Unsubscribe any time.

Follow on Instagram@leverageai_io, where our Reels and code words are.
Claude Code hooks: 5 we tested on one small app | Leverage AI