How to use Claude Code hooks: four you can paste today
Instructions in CLAUDE.md are requests. Claude usually follows them, but "always run Prettier after editing" is still something the model has to remember. Hooks are different: they're shell commands that Claude Code itself runs at fixed points, every time, whatever the model decides. If something must happen (or must never happen), a hook is the right tool. This post explains how hooks work in a…
Claude Code hooks are shell commands that run automatically at specific points during the code editing process, providing a way to customize the behavior of Claude Code. These hooks are defined in a settings file, typically located at ~/.claude/settings.json or .claude/settings.json, and are executed on various events, such as before or after a tool runs, when Claude needs attention, or when the session starts.
There are four hooks that can be easily implemented today:
1. Notification hook: This hook displays a notification when Claude Code needs your attention. To enable it, add a "Notification" entry to the hooks block in the settings file. On macOS, use the osascript command to display a notification, while on Linux, use the notify-send command.
2. Formatter hook: This hook formats every file Claude edits using a specified formatter, such as Prettier. In the .claude/settings.json file, add a "PostToolUse" entry with a matcher of "Edit|Write" and a command that uses the jq tool to extract the file path from the JSON input and then runs the formatter on that file.
3. Protection hook: This hook prevents Claude Code from editing certain files, like .env files or package-lock.json. Create a shell script, make it executable, and then add a "PreToolUse" entry to the hooks block with the script's path. The script checks the file path against a list of protected patterns and exits with an error if a match is found.
4. Dangerous command block hook: This hook blocks specific dangerous shell commands, like dropping tables in SQL or using git with --force. Create another shell script, test it to ensure it works correctly, and then add a "PreToolUse" entry with the script's path and a matcher for the specific tool (e.g., "Bash").
To use these hooks, simply add the appropriate sections to the hooks block in the settings file and save the file. Claude Code will automatically run the hooks on the specified events, allowing you to customize its behavior to suit your needs. Remember to check the JSON syntax if your hooks are not firing and ensure that the scripts are executable and the command names are spelled correctly.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to