Mastering Claude Code Hooks and SDK: A Step‑by‑Step Guide
This article explains how Claude Code hooks work, walks through configuring PreToolUse and PostToolUse hooks, shows concrete JSON and Node.js examples for protecting sensitive files, automating type checks, preventing duplicate queries, and demonstrates how the Claude Code SDK can be integrated into larger AI‑driven development workflows.
Claude Code allows you to run custom commands before or after a tool is invoked. Hooks are inserted into the normal Claude‑Code interaction flow, enabling automation such as code formatting, testing, or access control.
Understanding Hooks
There are two hook types:
PreToolUse hook – runs before the tool call.
PostToolUse hook – runs after the tool call.
Hook Configuration
Hooks are defined in Claude configuration files. You can place them in the global ~/.claude/settings.json, a project‑level .claude/settings.json, or a personal .claude/settings.local.json. The configuration consists of a matcher that selects tools and a command that is executed.
PreToolUse Hook Example
{
"PreToolUse": [
{
"matcher": "Read",
"hooks": [
{
"type": "command",
"command": "node /home/hooks/read_hook.ts"
}
]
}
]
}The command receives a JSON payload describing the proposed tool call. It can either allow the operation or block it by exiting with code 2 and writing an error message to stderr.
PostToolUse Hook Example
{
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "node /home/hooks/edit_hook.ts"
}
]
}
]
}Because the tool has already run, a PostToolUse hook cannot stop the action, but it can perform follow‑up tasks such as formatting the edited file or providing additional feedback.
Practical Use Cases
Code formatting after Claude edits a file.
Running tests automatically when files change.
Blocking Claude from reading or editing specific files (e.g., .env).
Providing code‑quality feedback by running a type checker.
Logging file accesses for audit purposes.
Validating naming conventions or coding standards.
Example: Preventing Access to .env
To stop Claude from reading a sensitive .env file, add a PreToolUse hook that matches Read|Grep and runs a Node.js script:
{
"matcher": "Read|Grep",
"command": "node ./hooks/read_hook.js"
}The script parses the incoming JSON, checks tool_input.file_path for the string .env, and exits with code 2 if a match is found:
async function main() {
const chunks = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
const toolArgs = JSON.parse(Buffer.concat(chunks).toString());
const readPath = toolArgs.tool_input?.file_path || toolArgs.tool_input?.path || "";
if (readPath.includes('.env')) {
console.error("You cannot read the .env file");
process.exit(2);
}
}After saving the configuration and script, restart Claude Code and attempt to read .env. The hook intercepts the call, returns the error message, and Claude reports that the operation was blocked.
Core Advantages
Proactive protection – blocks risky actions before they happen.
Transparent feedback – Claude receives a clear error explaining why the operation was denied.
Flexible matching – the same hook can monitor multiple tools.
Clear error messages – helps developers understand security policies.
Other Useful Hooks
Notification– runs when Claude sends a notification (e.g., after a permission request or after being idle for 60 seconds). Stop – runs when Claude finishes a response. SubagentStop – runs when a sub‑agent task completes. PreCompact – runs before a compression operation. UserPromptSubmit – runs when a user submits a prompt, before Claude processes it. SessionStart / SessionEnd – run at the beginning or end of a session.
Complexity of Hook Input
The JSON sent to a hook varies by hook type and by the tool being monitored. For example, a PostToolUse hook for the TodoWrite tool receives a list of todos, while a Stop hook receives only a flag indicating whether the stop hook is active.
Debugging Tips
To inspect the exact input a hook receives, create a generic logging hook that writes the stdin to a file:
{
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "jq . > post-log.json"
}
]
}
]
}This makes it easy to understand which fields your command should examine.
Claude Code SDK
The Claude Code SDK lets you programmatically run Claude Code from TypeScript, Python, or the CLI. It shares the same tool set as the CLI version, with default read‑only permissions. Write permissions can be granted by specifying allowedTools in a query or by configuring the project’s .claude settings.
Core Features
Programmatic execution of Claude Code.
Same capabilities as the terminal version.
Inherits settings from the current directory.
Default read‑only mode; optional write tools.
Ideal for embedding AI capabilities into larger automation pipelines.
Basic TypeScript Example
import { query } from "@anthropic-ai/claude-code";
const prompt = "Look for duplicate queries in the ./src/queries dir";
for await (const message of query({ prompt })) {
console.log(JSON.stringify(message, null, 2));
}This script streams the raw Claude‑Code conversation and prints the final response.
Permissions
By default the SDK can only read files and run grep. To enable write tools, add allowedTools: ["Edit"] to the query options or adjust the .claude settings.
Real‑World Applications
Automated Git hook that reviews code changes.
Build scripts that analyze and optimise code.
CLI commands that assist with documentation generation.
CI/CD pipelines that enforce code‑quality checks.
Overall, Claude Code hooks and the SDK provide a flexible way to embed AI‑driven automation directly into development workflows, giving you fine‑grained control over tool usage, security policies, and feedback loops.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
