Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link.
⚡ Get the Claude Code Production Starter Kit
Quick Takeaways
- CLAUDE.md is advisory, not a hard lock: Keep it under ~2,500 tokens (~100 lines), explain why rules exist, and split details with
@imports or Skills.- Hooks are deterministic guardrails:
PreToolUseandPostToolUsescripts block dangerous commands, protect.envsecrets, and auto-format every edit.- Compounding team memory: Run
/init, trim the bloat, and log every repeated mistake intoCLAUDE.md+ Hooks so you never repeat yourself twice.
The day I first opened Claude Code, I did what any developer does — I started poking around. That’s when I noticed a file I hadn’t created: CLAUDE.md. I almost ignored it. I’m glad I didn’t.
That file turned out to be the difference between Claude writing code at your project and writing code for your project. In this piece, I want to show you exactly how — through two tools that changed how I work: CLAUDE.md and Hooks.

CLAUDE.md gives Claude Code project context, while Hooks enforce deterministic guardrails before and after every tool call.
CLAUDE.md — Your Project’s Handbook
An Onboarding Guide for Claude
Picture a developer joining a project for the first time. It’s their first day — they sit down at their desk, pull the repo, and start reading through the code. They’ve got some very basic questions bouncing around their head: “How do I run the build? What command runs the tests? What should I watch out for in the folder structure?” Normally, a senior developer would come over and walk them through the project — the conventions, the technical decisions, the “this is how we do things here” stuff.
But what if the new team member isn’t a person — it’s Claude Code?
That’s exactly what the CLAUDE.md file is for. Every time a session starts, Claude Code reads this file first. It’s an onboarding guide you hand to an AI that arrives at “zero mileage” every single time. Don’t confuse this with the classic README.md that’s written for humans. A README typically explains what the project does. A CLAUDE.md tells the AI how to dive into the project.
Why Do We Need This File?
Your project might contain dozens or hundreds of files, but Claude doesn’t need all of them to work effectively. In fact, too much irrelevant context actively hurts Claude’s performance. The goal is to point Claude to the right information at the right time.
If you say “build me an auth system,” Claude can do it a thousand different ways. But if your project already uses Zustand and Claude goes off building a Redux setup instead, the code works — but it doesn’t fit the fabric of your project.
No matter how talented Claude Code is, if it doesn’t know your project’s specific rules, technology choices, and red lines, it falls back on its own defaults.
CLAUDE.md is a list of technical constraints and rules that keeps Claude aligned with your project. Thanks to this file, Claude knows which libraries you use, which coding standards you follow, and which commands are critical. Instead of producing code that clashes with the project’s architecture every time, it gives you exactly the output you expect.
Quick Start: The /init Command
You don’t have to write CLAUDE.md from scratch. Claude Code’s /init command automatically analyzes your project and generates a starter draft for you.
When this command runs, Claude scans your project’s folder structure, build system, test framework, and code patterns to create a draft. It will ask permission for every file write: you can press Enter to approve each one individually, or press Shift+Tab to cycle through permission modes — the first press switches to Auto-Accept mode (standard file read/write operations run without asking), and the second press switches to Plan mode (Claude makes no changes at all, just analyzes and presents a roadmap).
Rather than using the generated file as-is, delete the lines you don’t need and add rules specific to your project.
💡 Practical Tip: Deleting is easier than writing. Trimming unnecessary lines from the
/initoutput is much faster than writing everything from scratch. Remember: every line that stays in the file eats into the context window Claude needs for the actual work.
3 Critical Rules for Writing CLAUDE.md
Rule 1: Focus on “Why,” Not Just “How”
Instead of simply dictating a technical rule, explain the engineering philosophy behind it. If Claude understands the purpose of a rule, it makes far better decisions in gray areas.
❌ Insufficient:
Use Zustand.
✅ Better:
Use Zustand for state management; we want to keep global
state minimal. For cases that don't require complex business
logic and only carry UI state, prefer React Context. Our goal
is to prevent unnecessary re-renders and keep state as close
to the relevant component as possible.
With this explanation, Claude starts analyzing state scope and choosing the right tool — instead of blindly wiring everything through Zustand.
Define the standards that shape your code structure in clear language:
## 📏 Code Standards (Strict)
- **TypeScript:** `strict` mode is on. Using `any` is an
automatic rejection.
- **Naming:** Components use `PascalCase` (e.g.,
`ProductCard.tsx`), Hooks use `camelCase` (`useCart.ts`).
- **Functions:** Prefer `arrow functions` and `functional
programming` principles wherever possible.
Rule 2: Draw Operational Boundaries
Claude Code’s biggest differentiator is terminal access. But this power, left unchecked, can pollute your project. To prevent Claude from “guessing” its way forward, make your operational workflow explicit.
## Verification Protocol
1. Implement the change.
2. Start the app with the stack-specific command
(e.g., `next dev`, `nx serve`, `npm run dev`).
3. Test critical UI paths with Playwright MCP.
4. If no errors, proceed to the commit stage.
In monorepo setups, for instance, Claude sometimes gets confused about which package goes where. It might install a package meant for apps/web inside packages/ui by mistake. Prevent this by making the rules explicit:
## Package Management Rules
- Before adding a new dependency, always check if it already
exists in `@repo/shared`.
- Always use the `--filter` flag when adding dependencies
(e.g., `pnpm add lodash --filter web`).
- Never add packages to the root directory; always target
the relevant workspace.
⚠️ A Critical Distinction You Should Know: Advice vs. Enforcement
CLAUDE.mdinstructions are “advisory” in nature. Anthropic’s official documentation states this clearly: Claude processes this file as context, but doesn’t feel obligated to follow it like a hard rule every time. The system wraps this file with the caveat: “This context may or may not be relevant to your tasks.”This means Claude can ignore certain rules — especially if the file is too long. That’s why these two tools serve different purposes:
- CLAUDE.md (Nature: Advisory) — Use for guidelines, coding preferences, and architectural decisions.
- Hooks (Nature: Deterministic — Always runs) — Use for hard rules like running lint, formatting code, and blocking dangerous commands.
For operations like running lint, applying formatting, or blocking dangerous commands, trust Hooks — not CLAUDE.md.
Rule 3: Keep It a Living Document (Feedback Loop)
Writing your CLAUDE.md once and shelving it is one of the most common mistakes. This file should be a living knowledge base that breathes alongside your project, updated with every lesson learned.
CLAUDE.md is not a static file. If you find yourself correcting the same Claude mistake twice, add the rule that prevents it to the file immediately. As Boris Cherny (creator of Claude Code and Head of Claude Code) puts it: “If Claude does something wrong, we write it into CLAUDE.md so it never does it again.” This creates a feedback loop where the system improves itself.
Boris takes this a step further: his team tags teammates’ PRs with @.claude, automatically feeding lessons from code reviews into CLAUDE.md. He calls this “Compounding Engineering.” Every PR review becomes permanent team knowledge.
## 🚫 "Don't" List (Lessons Learned)
- **Styling:** Don't create SCSS/CSS files — handle all
design with Tailwind utility classes.
- **Debugging:** Don't use `console.log` — use the
centralized `logger` service and `Error Boundary` patterns.
- **Security:** Never hardcode API URLs — always access
them through `.env` variables.
The most practical way to add a rule on the fly: just tell Claude directly.
"Add to the CLAUDE.md file that we always use TypeScript
strict mode in this project from now on."
Claude opens the file in the background, adds the rule automatically, and confirms the operation.
There’s an even faster route: in the terminal, anything starting with # gets saved directly to project memory (CLAUDE.md) as a note — without Claude generating a response at all:
#Always use bun in this project, not npm
When you hit Enter, Claude asks whether this note should be saved at the project level (the team’s CLAUDE.md) or at the personal level (~/.claude/CLAUDE.md). Something you say once, you never have to say again.
✅ Tip: Add emphasis markers like
IMPORTANT:orYOU MUSTbefore critical rules. Official documentation confirms this technique improves Claude’s compliance rate.
Referencing Files with @
The most practical way to point Claude at the right information is the @ symbol. It works in two different contexts:
During conversation: When you want Claude to look at a specific file or directory, write the file path with @:
How does the auth system work? @auth
Claude lists the relevant files, adds the ones you select to the current conversation context. Instead of loading your entire project into context, you’ve pulled in just the file you need.
Inside CLAUDE.md: You can use the same syntax within your CLAUDE.md file. Files referenced this way are automatically included in every request:
The database schema is defined in @prisma/schema.prisma.
Refer to this file when you need to understand the
database structure.
This way, Claude can answer questions about the schema instantly without having to search for the file each time.
File Locations and Hierarchy
CLAUDE.md doesn’t have to live in just one place. Claude Code loads and merges these files hierarchically:
-
~/.claude/CLAUDE.md(Scope: All projects) — For personal preferences and editor settings. -
./CLAUDE.md(Scope: This project / committed to git) — For team standards and shared rules. -
./CLAUDE.local.md(Scope: This project / added to.gitignore) — For your personal project notes only. -
./frontend/CLAUDE.md(Scope: Frontend directory only) — For rules specific to a subdirectory.
Subdirectory-level CLAUDE.md files are especially powerful in large projects. You can define separate rules for the frontend/ directory and different rules for backend/. Claude automatically loads the relevant file only when working in that directory — your main file doesn’t get bloated for no reason.
Modular Structure
As your CLAUDE.md grows, you can import other files using the @ syntax. This is one of the most effective ways to preserve token economy:
# CLAUDE.md
## Project Overview
Next.js + Turborepo monorepo. Details: @README.md
## Commands
Available npm scripts: @package.json
## Detailed Rules
- Git workflow: @docs/git-rules.md
- API standards: @docs/api-conventions.md
- Personal preferences: @~/.claude/my-preferences.md
Your main file stays short and focused while detailed rules live in separate files. Claude only reads them when needed.
Taking it one step further: you can move instructions that are rarely needed but critical for specific workflows into Skills (.claude/skills/<name>/SKILL.md). Unlike CLAUDE.md, Skills aren’t loaded at every session — they’re only invoked when needed. That means token savings on every conversation.
Token Economy: The Math of Keeping It Short
Boris Cherny’s (creator of Claude Code) team’s CLAUDE.md file is roughly 2,500 tokens — about 100 lines. The team that actually builds Claude Code keeps theirs this short.
The reason is simple: this file gets loaded into Claude’s context window at the start of every session. The longer the file, the less room Claude has for the actual work. An even more serious problem: in overly long files, Claude starts missing important rules altogether.
📌 From the Official Docs: “If Claude keeps making mistakes despite a rule being in CLAUDE.md, the file is probably too long and important rules are getting lost in the noise.”
For every rule, ask yourself: “If I delete this line, will Claude make mistakes?” If the answer is no, delete it.
- Don’t write things Claude already does correctly (e.g., “Use TypeScript” — Claude already knows this)
- Write the mistakes Claude repeatedly makes in your specific project, not general concepts
- Move rarely needed instructions to separate files with
@or into Skills - Commit the file to git — let your team contribute; the value compounds over time
ℹ️ How to use the templates below: These templates are intentionally comprehensive to show what could go into a
CLAUDE.mdfor each stack. Don’t copy them as-is — pick what fits your project and use@to move details into sub-files, keeping the main file within the 2,500-token limit.
Example CLAUDE.md Templates
Template optimized for a Next.js + Turborepo project:
## Stack & Architecture
- Monorepo: Turborepo (Remote Caching active).
- Frontend: Next.js 15 (App Router), React 19, Tailwind.
- Backend: NestJS, GraphQL (Code-first), PostgreSQL.
- State: Zustand (Global), Context (UI), TanStack Query.
- Shared: @repo/ui (components), @repo/utils (helpers).
## Code Standards (NON-NEGOTIABLE)
1. Next.js Patterns: Server Components by default. Use
'use client' only on lowest-level interactive leaves.
2. State Strategy:
- Server data: TanStack Query. NEVER use Zustand.
- Global auth/settings: Zustand.
- Form/UI toggle: local state or Context.
3. GraphQL: Fragment Colocation per component.
4. Turborepo: Strict apps/ vs packages/ boundary.
5. TS: no any. type > interface. Errors: Result pattern.
## Verification Protocol
1. Implement: Write the code.
2. Verify: turbo lint && turbo build --filter=[APP_NAME]
3. Test: If critical change, run Playwright MCP UI test.
4. Commit: Only git commit after verification passes.
## Git Workflow
- Branch: feat/PROJECT-{ID}_desc or fix/PROJECT-{ID}_desc
- Commit: Conventional Commits (feat:, fix:, refactor:)
- Rule: Commits without a Ticket ID will not be accepted.
## Claude's Role
- Role: Principal Full-Stack Architect (10+ years).
- IMPORTANT: Avoid unnecessary abstraction. Optimize for
OWASP security + LCP/CLS.
Template optimized for an Angular & NX Monorepo project:
## Stack & Architecture (Angular & NX)
- Monorepo: NX (Integrated or Package-based).
- Frontend: Angular 19 (Standalone, Signals-based).
- State: NgRx Signal Store, component-store, Signal (UI).
- Backend: NestJS, GraphQL (Code-first), PostgreSQL.
- Shared: @shared/ui, @shared/util, @shared/data-access.
## Code Standards (NON-NEGOTIABLE)
1. Signals-First: Use Signals in new components/services.
OnPush is mandatory. Do not use markForCheck().
2. NX Patterns: Under libs/, use Type (ui/data-access/
feature/util) and Scope (shared/admin/auth) tags.
No imports outside @repo/*.
3. State: Server->NgRx Effects, Global->NgRx Signal Store
(Facade preserved), Local->signal() or component-store.
4. RxJS vs Signals: WebSocket/polling->RxJS; UI->Signals.
5. Styling: Tailwind+DaisyUI. Global SCSS for vars only.
## Operational Safety (via Hooks)
- IMPORTANT: Run nx lint --fix && nx format:write after
every change.
- Code that fails nx type-check cannot be committed.
- YOU MUST: Use nx generate for new components/services.
No manual file creation.
## Verification Protocol
1. Implement -> 2. nx lint ${project} && nx test ${project}
3. nx serve (if UI change) -> 4. Playwright MCP E2E
5. Commit: Only if affected:build succeeds.
## Claude's Role
- Role: Principal Angular Architect (10+ years).
- Anti-Pattern Rejection: any usage, skipping Facade,
non-Standalone components.
- Do not add deps that break NX dep-graph rules.
Template optimized for a MERN Stack project:
## Stack & Architecture (MERN)
- Database: MongoDB (Mongoose).
- Backend: Node.js (Express), JWT Auth.
- Frontend: React 19 (Vite), Redux Toolkit + RTK Query.
- Style: Tailwind CSS + Headless UI.
- Validation: Zod (shared schemas across FE + BE).
## Code Standards (NON-NEGOTIABLE)
1. Controller-Service Pattern:
Route -> Controller (Req/Res) -> Service -> Model (DB).
Never put business logic in routes.
2. API Standards: RESTful with consistent JSON.
HTTP status: 400/401/403/404/500.
3. Security (IMPORTANT): Validate all inputs with Zod.
Passwords -> bcrypt. NoSQL -> Mongoose sanitizer.
4. Frontend State: Server -> RTK Query. UI -> Redux slice.
5. Env Vars: Hardcoding MONGODB_URI/JWT_SECRET is
forbidden. Access via config/.
## Operational Safety
- Pre-commit: Require npm run lint && npm run build.
- When a Model changes, update the matching Zod schema.
- Don't console.log inside try-catch; route to the
centralized error handler.
## Verification Protocol
1. Implement -> 2. API test (Postman/Curl)
3. npm run dev + Chrome DevTools error check
4. Playwright MCP E2E test for critical flows
5. Commit with Conventional Commits.
## Claude's Role
- Role: Senior MERN Developer (10+ years).
- Security First: Review code through the lens of
"how would a hacker exploit this?"
- DRY: Move repeated code into helpers/utilities.
Final Note: Not Perfect — Just Working
Trying to write the “perfect” CLAUDE.md is one of the most common traps. This file doesn’t need to be perfect — it needs to be useful.
To get started: run /init, delete the unnecessary lines, and add a few rules specific to your project. Then put Claude to work. Whenever you catch yourself correcting the same mistake twice, add the rule that prevents it to the file. Over time, CLAUDE.md becomes your team’s collective memory.
Here’s what I wish someone had told me before I spent a week figuring this out:
- Start with
/init→ Shift+Tab to select mode → delete the unnecessary → add project-specific rules - Use
@to reference files both in conversation and insideCLAUDE.md - Use
#for quick notes → Claude writes to memory without generating a response - Keep it modular → respect the ~2,500 token limit, use Skills for token savings
- Commit to git → share with your team → let it grow over time
- Use Hooks for mandatory rules —
CLAUDE.mdis advisory, Hooks are deterministic
HOOKS — Automating Your Engineering Reflexes
Enforcement
We set the project’s rules by preparing the CLAUDE.md file. But a rule being written down doesn’t mean it will always be followed. Expecting a speed-focused agent like Claude to comply 100% of the time would be a bit optimistic.
This is where Hooks come in. Hooks are automated guardrails that run before (Pre) or after (Post) Claude takes action, protecting the project’s quality standards.
When Claude writes code or runs a terminal command, the system quietly checks in the background: “Does this operation meet our standards?”
Hooks block Claude: Claude cannot move to the next step until a hook completes. Claude Code currently supports 18+ different hook events — PreToolUse and PostToolUse alongside Notification, Stop, SubagentStop, SessionStart, SessionEnd, and more. In this article, we’ll focus on the two most critical ones: Pre and Post.
The default timeout for hooks is 10 minutes. If a hook doesn’t complete within that window, it gets skipped and Claude continues. This timeout is customizable per hook.
GitHub — karanb192/claude-code-hooks: 🪝 A growing collection of useful Claude Code hooks. Copy, paste, customize.
This repo contains pre-written hook scripts designed to make your Claude Code experience safer and more controlled.
Setup
Instead of writing everything from scratch, here’s a step-by-step walkthrough for installing and using the tools from this repo.
Step 1: Prerequisites
The hooks in this repo are written in Node.js. I’m sure you already have it installed.
Step 2: Download the Repo
You need to download these scripts to a permanent location Claude can access. The .claude folder is usually the cleanest spot.
Open your terminal and run these commands in order:
# 1. Navigate to the Claude settings folder
mkdir -p ~/.claude/hooks
cd ~/.claude/hooks
# 2. Clone the repo here
git clone https://github.com/karanb192/claude-code-hooks.git .
The scripts are now sitting at ~/.claude/hooks/ on your machine.
Step 3: Configure Claude’s Settings (settings.json)
Now we need to tell Claude Code: “Hey, check in with these scripts before you do anything.”
Open ~/.claude/settings.json (create it if it doesn’t exist).
Paste the following JSON block inside. This configuration activates the three most critical protections from the repo:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command":
"node ~/.claude/hooks/block-dangerous-commands.js"
}]
},
{
"matcher": "Read|Edit|Write|Bash",
"hooks": [{
"type": "command",
"command":
"node ~/.claude/hooks/protect-secrets.js"
}]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command":
"node ~/.claude/hooks/auto-stage.js"
}]
}
]
}
}
Note: When you clone the repo, sometimes nested folders can appear (like
hooks/hooks/). Double-check the exact path of your scripts (runls ~/.claude/hooksto verify). If the scripts are directly there, the paths above are correct.
Here’s what each of the three scripts does:
-
block-dangerous-commands.js(Danger Blocker) : If Claude accidentally tries to runrm -rf /,mkfs(disk format), or any command that could lock up your machine, this script steps in and blocks the operation. For you: it eliminates the fear of “what if it deletes my entire project?” -
protect-secrets.js(Secret File Protection) : If Claude tries to read or print sensitive files like.env,id_rsa(SSH keys), or AWS credential files to the terminal (e.g.,cat .env), this blocks it. For you: it prevents API keys from accidentally leaking into logs or chat history. -
auto-stage.js(Automatic Git Add) : When Claude modifies a file, this automatically runsgit add <file>as soon as the operation completes. When you rungit status, you’ll see changes already “staged” and ready — committing becomes effortless.
Final Step: Testing It
After the setup, launch Claude Code (claude) in your terminal and run this test:
You: “Show me the contents of my .env file.” (If no .env exists, say “create a dummy .env and read it.”)
Expected result: Normally Claude would read it instantly. Now the hook kicks in and Claude responds with something like: “Access denied by hook: protect-secrets.js prevented reading sensitive file.”
You: “Run the command rm -rf / in the terminal.”
Expected result: The hook steps in and says “This command is too dangerous, permission denied.”
Writing Your Own Engineering Reflexes
Every project has its own red lines. If you want to automate not just security but code quality as well, you’ll need to write your own hooks.
Anti-Pattern Detector (PreToolUse)
Claude sometimes takes the fastest route and punches through your project’s architectural rules. In a Next.js project, for example, it might forget the use client directive or try to use a library you’ve banned. We can catch this at the PreToolUse stage.
The following script scans the content when Claude tries to write a file and blocks the operation if it finds console.log:
// ~/.claude/hooks/check-patterns.js
const fs = require('fs');
// Read the data coming from Claude
const data = JSON.parse(fs.readFileSync(0, 'utf-8'));
const toolInput = data.tool_input;
// We only care about file write or edit operations
if (data.tool_name === 'Write' || data.tool_name === 'Edit') {
const content =
toolInput.content || toolInput.new_content || "";
// Rule: console.log is banned!
if (content.includes('console.log')) {
console.log(JSON.stringify({
decision: "block",
reason:
"⚠️ Standard Violation: console.log detected " +
"in code. Please use the project's logger service."
}));
process.exit(0);
}
}
console.log(JSON.stringify({ decision: "approve" }));
Linter & Formatter
Claude sometimes writes the code but misses the project’s formatting rules. Don’t waste time telling it “format the code” every single time. The moment Claude saves a file (PostToolUse), let’s run Prettier or ESLint in the background to bring the code in line with project standards.
Create a file at ~/.claude/hooks/auto-format.js and add this logic:
/**
* Auto-Format Hook: Runs every time Claude edits
* a file (PostToolUse).
*/
const { execSync } = require('child_process');
const fs = require('fs');
const chunks = [];
process.stdin.on('data', chunk => chunks.push(chunk));
process.stdin.on('end', () => {
const input = JSON.parse(Buffer.concat(chunks).toString());
const file =
input.tool_input.path || input.tool_input.file_path;
// Only run on relevant file types
if (
file &&
(file.endsWith('.ts') ||
file.endsWith('.tsx') ||
file.endsWith('.js'))
) {
try {
// Trigger prettier in the project directory
execSync(`npx prettier --write "${file}"`, {
stdio: 'ignore',
cwd: input.cwd
});
} catch (e) { /* Fail silently */ }
}
process.exit(0);
});
DevOps Guard (Production Protection)
Claude having terminal access is a superpower, but if it hallucinates and tries to push to the main branch uncontrolled, or accidentally runs a command that affects the production environment, things get messy fast.
This hook catches patterns like “prod,” “main,” and “DROP DATABASE,” stops Claude in its tracks, and asks for your explicit approval.
Create the file ~/.claude/hooks/production-guard.js:
/**
* DevOps Guard: Requests explicit "APPROVAL" from
* the user for dangerous commands.
*/
const chunks = [];
process.stdin.on('data', chunk => chunks.push(chunk));
process.stdin.on('end', () => {
const input = JSON.parse(Buffer.concat(chunks).toString());
const cmd = input.tool_input.command || "";
const dangerousPatterns = [
/git push.*(main|master)/i, // Push to main branch
/DROP DATABASE/i, // Database deletion
/kubectl.*delete.*prod/i // K8s prod deletion
];
if (dangerousPatterns.some(p => p.test(cmd))) {
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "ask", // Ask the user!
permissionDecisionReason:
"⚠️ CRITICAL WARNING: Command may affect " +
`Production or Main branch: '${cmd}'`
}
}));
} else {
process.exit(0);
}
});
Final Configuration: settings.json
To manage all these scripts from one place, update your ~/.claude/settings.json as follows. Order matters here: format the code first, then stage it.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command":
"node ~/.claude/hooks/block-dangerous-commands.js"
},
{
"type": "command",
"command":
"node ~/.claude/hooks/production-guard.js"
}
]
},
{
"matcher": "Read|Edit|Write|Bash",
"hooks": [{
"type": "command",
"command":
"node ~/.claude/hooks/protect-secrets.js"
}]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command":
"node ~/.claude/hooks/auto-format.js"
},
{
"type": "command",
"command":
"node ~/.claude/hooks/auto-stage.js"
}
]
}
]
}
}
Conclusion: Advice + Enforcement = Control
In this article, we covered two tools and saw how they complement each other.
CLAUDE.md answers the question “what should be done”: the project’s architecture, coding standards, red lines. But it’s advisory in nature — Claude sometimes listens, sometimes does its own thing.
Hooks answer the question “how do we enforce it”: no matter what Claude does, deterministic checks run in the background. Code gets formatted, dangerous commands get blocked, changes get automatically staged.
When you set up both together, what you get is a self-regulating system — one where you no longer need to say “do this too, check that too” every single time.
To get started: run /init, add a few rules, set up the three core hooks. The first time Claude makes a mistake, write that mistake into the file. Over time, CLAUDE.md becomes your team’s collective memory, and Hooks become its reflexes.
Which rule or hook are you adding to your workflow first — blocking dangerous commands, protecting .env files, or auto-formatting every edit? I'd love to hear how you're taming Claude Code in your own projects 🧠💬
🚀 Keep Exploring
If you found this deep-dive valuable, explore more Claude Code and AI engineering breakdowns:
- 📌 Claude Fable 5.2 Changed the Rules: 1,280+ Updates Just Broke Your Defaults — How shifting Claude defaults impact your agentic workflows and configuration baselines.
- 📌 Claude Code Ultraplan: Terminali Kilitleyen Plan Moduna Son (TR) — Offload agentic planning into the cloud while keeping local developer velocity intact.
- 📦 karanb192/claude-code-hooks on GitHub — Ready-to-use PreToolUse and PostToolUse Node.js hook scripts featured in this guide.
👋 About the Author
I'm Mustafa Morbel — Senior Frontend Engineer with over 17 years of experience building modern frontend architectures, WebGL/creative applications, and agentic developer workflows.
- Explore working repositories, hooks, and benchmarks on my GitHub (@mkare).
- Connect on LinkedIn and follow along on X / Twitter (@mustafamorbel) for ongoing engineering notes.
- Have questions or ideas on hook automation? Drop a comment below, and feel free to leave a few claps 👏 if this helped your setup!
Top comments (0)