Urgent.News

What's breaking now, across thousands of outlets.

Tech

Hooks in Claude Code: A Beginner's Guide

The Scenario Your .claude/settings.json can ask before git push — but that's where a permission's job ends. It's a gate, not a worker: it can't format a file the moment it's edited, catch a missing test before code ships, or keep a log of what actually happened in a session. None of that is "is this call allowed" — it's "let me run my own logic around this event, whatever that logic needs to do."…

Claude Code offers hooks as a powerful tool for running custom scripts at various points in its workflow. These hooks are not permission checks, but rather scripts you write to inspect what's happening and decide what to do about it. A hook is essentially a script that runs automatically at specific moments, allowing you to perform security checks, formatting, automation, or keep a record of events. The two most important events for starting out are PreToolUse (right before a tool runs) and PostToolUse (right after).

To illustrate, consider a PreToolUse hook that checks whether files being pushed via git push have matching test files. The script `check-tests-before-push.sh` runs through the changes, comparing them to the base branch. If a source file changes but the corresponding test file hasn't also changed, the script exits non-zero, causing the PreToolUse hook to prevent the push. However, this example is simplified and doesn't verify the actual test coverage, just that the test file changed alongside the source file.

Hooks can be used for various purposes, such as auto-formatting, running linters, detecting secrets, session logging, and more. They can both block actions and perform automation, format files, or collect information. However, be cautious as a hook runs unconditionally and silently if it has a bug, potentially blocking legitimate work. It's recommended to test your hooks thoroughly using `claude --debug` before relying on them in real sessions.

Hooks can be configured in the `.claude/settings.json` file alongside permission rules. For example, a hook can be defined under `hooks.PreToolUse`, specifying a matcher and a command to run, like `./scripts/check-tests-before-push.sh`. This script can be found in the provided GitHub repository.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Saturday 19 September →