Claude Code Hooks: Automate Your Workflow with PreToolUse, PostToolUse, and Stop Events
Master Claude Code's hook lifecycle to automate security checks, file formatting, and workflow orchestration. Production patterns with exit codes and JSON output.
Correction (2026-10-27): an earlier version of this post said a PreToolUse hook blocks a tool call by exiting with code 1, and that exit 0 approves it. Both were wrong. Exit code 2 blocks; exit 1 is a non-blocking error and the tool still runs; exit 0 with no output leaves the call in the normal permission flow. The guard example, config format, and payload field names have been corrected against the official hooks reference. Thanks to the reader who reported it.
Most AI workflow bottlenecks stem from manual intervention between tool calls. Engineers watch Claude Code execute, then manually format output, run linters, or verify changes. The pattern that teams overlook is the hook system: a lifecycle API that runs your own scripts at fixed points in a session.
Claude Code exposes many hook events. The three this post focuses on are PreToolUse (runs before a tool call and can block it), PostToolUse (runs after a tool call succeeds), and Stop (runs when Claude finishes responding). Others include UserPromptSubmit, Notification, SubagentStop, PreCompact, SessionStart, and SessionEnd. The distinction between these events determines whether your automation catches errors early or scrambles to fix them afterward.
Without PreToolUse guards, Claude can run a destructive command you never meant to allow. Without PostToolUse formatters, commits fail CI checks. Without Stop hooks, nobody hears that the work finished.
Understanding the Hook Lifecycle: PreToolUse, PostToolUse, and Stop Events
PreToolUse fires first and receives the tool name and its input as JSON on stdin. It can block the call by exiting with code 2, or by printing a JSON decision. PostToolUse fires after the tool succeeds and receives both the input and the tool's response. Stop fires each time Claude finishes a response, not once per session (use SessionEnd for end-of-session work).
stateDiagram-v2
[*] --> PreToolUse: Tool call triggered
PreToolUse --> Blocked: exit 2 or permissionDecision deny
PreToolUse --> PermissionFlow: exit 0, no decision
PreToolUse --> ToolExecution: permissionDecision allow
PermissionFlow --> ToolExecution: Allowed by rules or user
Blocked --> ClaudeResponse: stderr reason fed to Claude
ToolExecution --> PostToolUse: Tool succeeded
PostToolUse --> ClaudeResponse: Processing complete
ClaudeResponse --> PreToolUse: Next tool call
ClaudeResponse --> Stop: Claude finishes responding
Stop --> [*]
classDef framework fill:#064e3b,stroke:#34d399,color:#6ee7b7
classDef userAction fill:#1e3a8a,stroke:#60a5fa,color:#e0eaff
class PreToolUse,PostToolUse,Stop framework
class ToolExecution,ClaudeResponse userAction
Hooks are configured under a hooks key in a settings file: ~/.claude/settings.json for every project, .claude/settings.json for a project (committed), or .claude/settings.local.json for a project (not committed). Each command receives a JSON payload on stdin and reports back through its exit code and, optionally, JSON on stdout.
The exit-code contract is the part that matters most, and it is not the usual Unix one:
| Exit code | Meaning | Effect on a PreToolUse call |
|---|---|---|
0 | Success | Any JSON on stdout is applied. With no JSON, the call continues through the normal permission flow (it is not auto-approved) |
2 | Blocking error | The tool call is blocked; stderr is shown to Claude as the reason |
anything else (including 1) | Non-blocking error | The error is reported, and the tool call still runs (unless the hook sets "onFailure": "block") |
That last row is the trap. process.exit(1) looks like "fail", but to Claude Code it means "this hook broke, carry on". A guard that exits 1 enforces nothing.

PreToolUse Hooks: Security Guards and Auto-Approval Patterns
PreToolUse hooks act as circuit breakers. The hook receives tool_name and tool_input before execution, validates the request, and blocks it with exit code 2 when it fails a check. The most common pattern is path validation: preventing writes outside project boundaries.
// .claude/hooks/pre-tool-guard.ts
import * as path from 'node:path';
interface PreToolUseInput {
hook_event_name: 'PreToolUse';
tool_name: string;
tool_input: {
file_path?: string;
command?: string;
};
cwd: string;
}
function block(reason: string): never {
// Exit code 2 blocks the tool call. Exit 1 does NOT, unless the hook
// sets "onFailure": "block" (then any failure blocks).
// stderr becomes the reason Claude sees.
console.error(reason);
process.exit(2);
}
async function main() {
let payload: PreToolUseInput;
try {
payload = JSON.parse(await readStdin());
} catch {
// Fail closed: a crash would exit 1, which lets the tool run.
block('Guard could not parse hook input; blocking to be safe');
}
// Block writes to system directories
const dangerPaths = ['/etc', '/usr', '/bin', '/System'];
if (
(payload.tool_name === 'Write' || payload.tool_name === 'Edit') &&
payload.tool_input.file_path
) {
const targetPath = path.resolve(payload.cwd, payload.tool_input.file_path);
if (dangerPaths.some((danger) => targetPath.startsWith(danger))) {
block(`Blocked write to system path: ${targetPath}`);
}
}
// Block destructive bash commands
if (payload.tool_name === 'Bash' && payload.tool_input.command) {
const cmd = payload.tool_input.command;
const destructive = ['rm -rf /', 'dd if=', ':(){:|:&};:'];
if (destructive.some((pattern) => cmd.includes(pattern))) {
block('Blocked destructive bash command');
}
}
// No objection: exit 0 with no output. This does NOT approve the call;
// it just leaves it to the normal permission rules.
process.exit(0);
}
function readStdin(): Promise<string> {
return new Promise((resolve) => {
let data = '';
process.stdin.on('data', (chunk) => (data += chunk));
process.stdin.on('end', () => resolve(data));
});
}
main();Note the try/catch around JSON.parse. An uncaught exception makes Node exit with code 1, and exit 1 is non-blocking, so a guard that crashes silently lets every call through. Security hooks should fail closed. Claude Code v2.1.295+ can also enforce that from config: set "onFailure": "block" on the hook and any failure (a crash, a wrong script path, a timeout) blocks the call instead of letting it run.
Substring matching on commands is also easy to bypass (rm -r -f /, extra spaces, a script file). Treat a hook like this as a safety net for mistakes, and keep real restrictions in Claude Code's permission deny rules as well.
The auto-approval pattern goes the other way. Instead of prompting on every file write, the hook approves writes inside known-safe directories by printing a JSON decision and exiting 0:
// Inside the same hook, for an approved path:
process.stdout.write(
JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'allow', // or 'deny' / 'ask'
permissionDecisionReason: 'Write inside src/ is pre-approved',
},
}),
);
process.exit(0);permissionDecision accepts allow (skip the prompt), deny (block, an alternative to exit 2), and ask (force a confirmation prompt). Your settings' deny and ask rules are still evaluated whatever the hook returns, and when several hooks disagree, deny wins over ask, which wins over allow.
PostToolUse Hooks: Auto-Formatting and File Processing
PostToolUse hooks run after a tool succeeds. The hook receives tool_input and tool_response, so it can act on exactly what changed. The canonical use case is automatic code formatting after file writes.
// .claude/hooks/post-write-format.ts
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import * as path from 'node:path';
const execFileAsync = promisify(execFile);
interface PostToolUseInput {
hook_event_name: 'PostToolUse';
tool_name: string;
tool_input: {
file_path?: string;
};
}
async function main() {
const payload: PostToolUseInput = JSON.parse(await readStdin());
const filePath = payload.tool_input.file_path;
if (!filePath || !['Write', 'Edit'].includes(payload.tool_name)) {
process.exit(0);
}
const ext = path.extname(filePath);
try {
if (ext === '.ts' || ext === '.tsx') {
// execFile passes the path as an argument, not through a shell
await execFileAsync('npx', ['prettier', '--write', filePath]);
await execFileAsync('npx', ['eslint', '--fix', filePath]);
} else if (ext === '.json') {
await execFileAsync('npx', ['prettier', '--write', filePath]);
}
process.exit(0);
} catch (error) {
// Advisory: report the failure but don't interrupt Claude
console.error(`Formatting failed: ${(error as Error).message}`);
process.exit(1);
}
}
function readStdin(): Promise<string> {
return new Promise((resolve) => {
let data = '';
process.stdin.on('data', (chunk) => (data += chunk));
process.stdin.on('end', () => resolve(data));
});
}
main();The key decision is what to do when the formatter fails. The pattern above exits 1: a non-blocking error that gets logged while Claude carries on, which suits advisory formatting. For a check Claude must act on, such as schema validation, exit 2 instead. The write has already happened by then, so PostToolUse cannot undo it, but exit 2 feeds stderr back to Claude so it fixes the problem in its next step. A PostToolUse hook can also return JSON with "decision": "block" and a reason, or add additionalContext for Claude to read alongside the tool result.

Stop, SessionEnd, and Notification Events: Workflow Orchestration
Stop hooks fire every time Claude finishes responding, not once per session. The payload includes the usual session fields (session_id, transcript_path, cwd) and Claude's last message. It does not include tool-call counts or success metrics; if you want those, read them from the transcript file. A Stop hook can also return "decision": "block" with a reason to make Claude keep working, which is how "don't stop until the tests pass" loops are built. For work that should happen once when the session closes, use SessionEnd instead.
flowchart TD
Finished[Claude finishes responding] --> StopHook[Stop hook fires]
StopHook --> ReadTranscript[Read transcript_path]
ReadTranscript --> CheckTests{Tests passing?}
CheckTests -->|No| BlockStop[decision block: keep working]
CheckTests -->|Yes| Notify[Post summary to Slack]
Notify --> Complete[Allow stop]
BlockStop --> Finished
classDef framework fill:#064e3b,stroke:#34d399,color:#6ee7b7
classDef dataStore fill:#1e293b,stroke:#64ffda,color:#e2e8f0
class StopHook,CheckTests framework
class ReadTranscript dataStore
A practical pattern is to have the Stop hook check git status for modified files and run your test command. If the tests fail, it blocks the stop and hands Claude the failure output. If they pass, it posts a summary to Slack. Guard against infinite loops: the Stop payload includes a stop_hook_active flag that is true when Claude is already continuing because of a Stop hook.
Notification hooks fire when Claude Code sends a notification: for example when it is waiting for a permission decision (permission_prompt) or has been idle waiting for your input (idle_prompt). The main use is alerting: push a desktop or phone notification so you know a long-running session needs you.
Production-Ready Hook Configurations (With Exit Codes and JSON Output)
Production hooks require three components: exit-code discipline, structured logging, and idempotency. Exit codes must be deliberate: 2 when you mean "block", 0 otherwise, and never rely on 1 to stop anything. Logs should be machine-readable. Hooks must handle re-execution gracefully.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit|Bash",
"hooks": [
{ "type": "command", "command": "npx tsx \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/pre-tool-guard.ts" }
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{ "type": "command", "command": "npx tsx \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/post-write-format.ts" }
]
}
],
"Stop": [
{
"hooks": [
{ "type": "command", "command": "npx tsx \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/stop-workflow.ts" }
]
}
],
"Notification": [
{
"hooks": [
{ "type": "command", "command": "npx tsx \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/notify.ts" }
]
}
]
}
}Each event maps to a list of matcher groups. matcher is matched against the tool name (Write|Edit|Bash matches any of the three), and $CLAUDE_PROJECT_DIR points at the project root, so hook paths work no matter which directory Claude is in.
For logging, write one JSON object per line to a log file. Stdout and stderr are part of the hook protocol (stdout carries JSON decisions; stderr becomes the block reason on exit 2), so keep diagnostics out of them unless you mean Claude to see them.
Idempotency requires that hooks check whether their action already completed. A PostToolUse formatter should tolerate running on an already-formatted file. A Stop hook should check if the PR already exists before creating a new one, especially since Stop fires after every response.
Common Hook Failure Modes and How to Prevent Them
Hook failures fall into four categories: wrong exit codes, timeouts, environment mismatch, and payload schema drift. The first is the one that silently disables a guard, so test it directly: pipe a sample payload into the hook and check echo $? prints 2 for a request it should block.
Timeouts occur when hooks perform expensive operations synchronously. Command hooks get a generous default timeout (600 seconds for most events), and you can set timeout per hook, but a slow PreToolUse hook stalls every tool call. Keep guards fast, and move slow, non-blocking work into hooks marked "async": true, which run in the background.
flowchart TD
HookStarts[Hook execution starts] --> Parse{Payload parses?}
Parse -->|No| ExitTwo[Exit 2: block, fail closed]
Parse -->|Yes| Check{Request allowed?}
Check -->|No| LogReason[Write reason to stderr]
LogReason --> ExitTwo
Check -->|Yes| ExitZero[Exit 0]
ExitZero --> Complete[Normal permission flow]
ExitTwo --> Blocked[Tool call blocked]
classDef framework fill:#064e3b,stroke:#34d399,color:#6ee7b7
classDef badPattern stroke:#ef4444,fill:#450a0a,color:#fca5a5
class Check,Parse framework
class ExitTwo badPattern
Environment mismatches happen when hooks assume tools are globally available. A hook that calls prettier will fail if Prettier isn't in PATH. Use npx, absolute paths, or $CLAUDE_PROJECT_DIR-relative paths.
Payload schema drift is the most insidious failure mode. Claude Code adds fields and events over time, and a hook that relies on a field name that changes breaks quietly. Parse payloads defensively: check required fields, branch on hook_event_name and tool_name, and for security hooks, fail closed (exit 2) when the payload is not what you expect.
Building Your First Hook Pipeline: A Complete Example
A practical hook pipeline combines all three events. PreToolUse blocks dangerous paths and commands with exit 2 and auto-approves safe writes with permissionDecision: "allow". PostToolUse formats code after every write. Stop runs the tests and keeps Claude working until they pass, then notifies you.
The pipeline runs in development environments where engineers iterate rapidly. PreToolUse hooks prevent accidental system modifications. PostToolUse hooks maintain code quality without manual intervention. Stop hooks make sure a response ends with working code, not just changed code.
Hooks compose into higher-level modes. A "safe development mode" combines strict PreToolUse guards with aggressive PostToolUse formatters. A "CI integration mode" runs tests in Stop hooks and blocks the stop if coverage drops. A "pair programming mode" logs every tool call to a shared dashboard for team visibility.
Apply these in your own setup, and verify each guard by feeding it a payload it should reject and checking for exit code 2. The hook system is only as strong as its exit codes.