← LearnClaude Code · Automation

Claude Code Hooks Examples: Real-World Automation Recipes

Claude Code hooks are user-defined shell commands that run automatically at specific lifecycle points — before a tool runs, after it completes, or when Claude needs input. Common examples include desktop notifications, automatic code formatting, bash command logging, and blocking writes to protected files.

What Are Claude Code Hooks, and Why Do They Matter?

Claude Code hooks are user-defined shell commands (or HTTP requests, MCP tool calls, or prompt-based evaluations) that execute automatically at specific points in Claude Code's lifecycle. Unlike asking Claude to perform an action, hooks guarantee deterministic behavior — they always run regardless of what the model decides. This makes hooks suitable for enforcing policies, automating repetitive tasks, and integrating Claude Code into existing development workflows.

In practical terms, a hook is the difference between hoping Claude remembers to run your formatter and guaranteeing it happens every single time. If you've ever had an AI agent skip a step you asked it to follow, hooks are the fix.

You can learn more in the official Claude Code hooks reference and the getting started guide for Claude Code hooks.

What Lifecycle Events Can Hooks Target?

Each hook definition specifies a trigger event. The main events are:

  • PreToolUse — fires before a tool runs, allowing you to inspect, block, or modify the action
  • PostToolUse — fires after a tool completes, useful for formatting, logging, or running tests
  • SessionStart — fires when a Claude Code session begins
  • Notification — fires when Claude is waiting for user input
  • MessageDisplay — a newer event that allows hooks to transform or suppress assistant message text as it is displayed to the user

Hooks receive contextual data via stdin as JSON (for example, the tool name and its inputs), and communicate back to Claude Code via exit codes and stdout/stderr output. A hook can silently allow an action, block it with an explanatory message, or inject additional context into Claude's next turn.

How Do You Set Up Claude Code Hooks?

Hooks are configured as JSON objects in Claude Code's settings files. You can use the interactive /hooks slash command inside Claude Code, or edit the settings files directly.

  1. Install Claude Code and ensure you are on a supported plan (Pro, Max, Team, or Enterprise).
  2. Open your terminal and start a Claude Code session.
  3. Run /hooks inside Claude Code to open the interactive hooks configuration interface.
  4. Select the hook event you want to configure (e.g., PreToolUse, PostToolUse, Notification).
  5. Choose the scope: User settings (applies to all projects) or Project settings (applies only to the current project).
  6. Alternatively, edit the JSON settings file directly: for user-level hooks edit ~/.claude/settings.json; for project-level hooks edit .claude/settings.json in your project root.
  7. Add your hook definition under the hooks key following the required JSON schema.
  8. Restart your Claude Code session for any direct file edits to take effect (changes made via /hooks apply to new sessions automatically).

What Are the Best Claude Code Hooks Examples?

1. Desktop Notification When Claude Needs Input

You're running a long task and step away from your terminal. A Notification hook fires a desktop alert the moment Claude pauses and waits for your input.

On macOS, the hook command looks like:

osascript -e 'display notification "Claude needs your input" with title "Claude Code"'

On Linux, you'd use notify-send instead. When the hook fires, Claude Code passes JSON via stdin describing the notification event. The hook exits with code 0, and Claude continues waiting. A macOS desktop notification appears immediately — no terminal-watching required.

2. Log All Bash Commands to an Audit File

A PreToolUse hook on the Bash tool intercepts every shell command Claude attempts to run and appends it to a log file. This creates a complete, tamper-resistant record of all shell commands executed during the session.

The hook receives input like:

{ "tool_name": "Bash", "tool_input": { "command": "npm install", "description": "Install dependencies" } }

A command using jq extracts the command string and appends it to ~/.claude/bash-command-log.txt. The hook exits with code 0, so the Bash command proceeds normally. After the session, you have a full audit trail — useful for security reviews and debugging unexpected agent behavior.

3. Auto-Format TypeScript Files After Every Edit

A PostToolUse hook on Edit, MultiEdit, and Write tools runs Prettier automatically on any .ts file Claude touches. The hook checks the edited file path, and if it ends in .ts, runs npx prettier --write on it.

Sample hook input:

{ "tool_name": "Write", "tool_input": { "file_path": "src/utils.ts", "content": "export const foo = (x:number)=>x+1" } }

After Claude writes the file, Prettier reformats it. The formatted version is what ends up on disk — no extra prompt instructions needed, no risk of Claude forgetting.

4. Block Modifications to Protected Files

A PreToolUse hook on Edit, MultiEdit, and Write tools inspects the target file path. If the path matches sensitive files such as .env, package-lock.json, or anything inside .git/, the hook exits with code 2 and returns an explanatory message, preventing Claude from accidentally modifying critical files. This is a hard guarantee — not a suggestion Claude might ignore.

5. Enforce Test Suite Quality Gates

A PostToolUse hook triggers after Claude modifies source files and automatically runs the project's test suite. If tests fail, the hook pipes the error output back to Claude as context, prompting the model to investigate and fix the failures before marking the task complete. This turns your test suite into an automatic feedback loop.

6. Automated Permission Decisions in CI/CD

When running Claude Code in a headless CI/CD pipeline, a PreToolUse hook evaluates whether a proposed tool invocation is safe to auto-approve based on deterministic rules — for example, allowing read operations while blocking network calls to external hosts. This enables autonomous operation without requiring a human to approve every step.

When Should You Use Hooks vs. Other Approaches?

Situation Use Hooks Use the Alternative
Always run formatter after edits PostToolUse hook — guaranteed every time Prompt instruction — Claude may forget
Block writes to .env unconditionally PreToolUse hook — hard block with exit code 2 Permission settings — better for blocking entire tool categories, not conditional logic
Influence Claude's general approach Not ideal — hooks are for deterministic actions System prompt instructions — simpler for probabilistic guidance
Run tests in background without blocking Async hook ("async": true) — runs in background Synchronous hook — use only when Claude must wait for the result
Notify developer when Claude needs input Notification hook — fires automatically Watching the terminal — requires constant attention

What Are the Most Common Hooks Pitfalls?

Mixing exit codes and JSON stdout

Choose exactly one communication strategy per hook: either use exit codes (0 to allow, 2 to block) with a plain stderr message, or exit 0 with a valid JSON object on stdout for structured control. When you exit with code 2, Claude Code ignores any JSON on stdout entirely.

Hook changes not taking effect

Claude Code does not hot-reload hook configurations from settings files during an active session — this is a deliberate security measure against malicious hook injection. Always restart your Claude Code session after editing settings files directly.

Using PostToolUse to undo actions

PostToolUse hooks run after the tool has already executed, so they cannot reverse file writes or command executions. Use PreToolUse hooks to validate and block actions before they happen. Reserve PostToolUse for logging, cleanup, notifications, and injecting context.

Debug output going to stdout

If your hook prints arbitrary text to stdout when Claude Code expects JSON, the internal parser will fail or ignore the output. All debug and informational output must go to stderr. Only valid JSON matching the expected schema should go to stdout.

Long-running hooks blocking the UI

By default, hooks run synchronously and Claude Code freezes while waiting. For hooks that run compilation, test suites, or deployment scripts, add "async": true to the hook definition. Async hooks run in the background and inject results as context on the next turn.

Is the Hooks Feature Worth Setting Up?

If you use Claude Code for anything beyond one-off queries — running it on real codebases, in CI pipelines, or for extended autonomous tasks — hooks are one of the highest-leverage features available. They shift enforcement from "hoping the model follows instructions" to "the system guarantees it happens." The setup cost is low (a few lines of JSON and a shell command), and the payoff is consistent, auditable, policy-enforced behavior across every session.

Hooks can also be distributed as part of Claude Code Plugins — shareable bundles that install with a single command — making it practical to share hook configurations across teams. For deeper programmatic integration, the Claude Agent SDK supports hooks when building custom agents.

Frequently asked questions

What is a Claude Code hook?

A Claude Code hook is a user-defined shell command (or HTTP request, MCP tool call, or prompt-based evaluation) that executes automatically at a specific point in Claude Code's lifecycle, such as before or after a tool runs. Unlike prompt instructions, hooks guarantee deterministic execution regardless of what the model decides.

How do I add a hook to Claude Code?

Run the /hooks slash command inside a Claude Code session to use the interactive interface, or directly edit the JSON settings file at ~/.claude/settings.json (user-level) or .claude/settings.json in your project root. Restart your session after editing files directly.

Can a PreToolUse hook block Claude from running a command?

Yes. A PreToolUse hook can exit with code 2 and return an explanatory message to block the tool invocation entirely. Claude Code will not execute the tool and will receive the hook's message as context.

What is the difference between PreToolUse and PostToolUse hooks?

PreToolUse hooks fire before a tool executes, allowing you to inspect, modify, or block the action. PostToolUse hooks fire after the tool has already completed, making them suitable for logging, formatting, running tests, or sending notifications — but not for reversing what the tool did.

Can hooks run asynchronously so they don't block Claude Code?

Yes. Adding async: true to a hook definition causes it to run in the background. Async hooks inject their results as context on the next turn rather than blocking Claude Code while they execute. This is recommended for long-running operations like test suites or builds.

What plans support Claude Code hooks?

Hooks are available on Claude Code with Pro, Max, Team, and Enterprise plans.

Go deeper

Hooks is one of 85 features in Claude Master — the independent, continuously updated manual with worked examples, the pitfalls, and the workflows that put Claude to work.

Get Claude Master — founding price →

Independent product. Not affiliated with or endorsed by Anthropic. "Claude" is a trademark of Anthropic, used here only to describe the subject of this guide.