What CLAUDE.md Actually Does
Claude Code is stateless. Every session starts from zero -- no memory of your last conversation, your project conventions, or your preferred patterns. CLAUDE.md solves this by injecting your project instructions into every session automatically.
According to Anthropic's best practices documentation, CLAUDE.md files turn Claude Code from a general-purpose assistant into a tool configured specifically for your codebase. The filename is case-sensitive -- it must be exactly CLAUDE.md (uppercase CLAUDE, lowercase .md).
Without CLAUDE.md
- ✕Repeat conventions every session
- ✕Claude guesses your build commands
- ✕Inconsistent code style across sessions
- ✕Repeats mistakes you already solved
With CLAUDE.md
- ✓Instructions loaded automatically
- ✓Exact commands, zero guessing
- ✓Consistent patterns every time
- ✓Known pitfalls documented once
Where CLAUDE.md Files Live: The 3-Level Hierarchy
Claude Code loads CLAUDE.md files from three locations, each with a different scope. The most specific file takes precedence when instructions overlap. Understanding this hierarchy is critical for multi-project setups and monorepos.
~/.claude/CLAUDE.md
User-level preferences that apply to every project. Put your personal style preferences here -- things like "always use TypeScript strict mode" or "prefer functional components." Loaded on every session regardless of project.
./CLAUDE.md (project root)
Project-specific instructions checked into version control. This is your primary file -- build commands, architecture decisions, coding conventions. Your entire team shares this file and it evolves with the codebase.
./src/components/CLAUDE.md (nested)
Directory-specific overrides loaded on demand. When Claude works with files in a subdirectory, it pulls in that directory's CLAUDE.md automatically. Use this for folder-specific conventions like "all components in this directory use CSS Modules."
~/.claude/CLAUDE.md # Your personal defaults
project-root/
CLAUDE.md # Project instructions (checked in)
.claude/
settings.json # Permissions + hooks
rules/ # Modular rule files
testing.md
security.md
src/
components/
CLAUDE.md # Component-specific rules
api/
CLAUDE.md # API-specific rulesGetting Started: /init vs Writing From Scratch
The fastest way to create a CLAUDE.md is the /init command. Run it in your project directory and Claude Code analyzes your package.json, tsconfig, Dockerfile, and directory structure to generate a starter file. But there is a catch.
The /init output is generic. It detects your stack but misses the context that actually matters -- the architectural decisions, the known pitfalls, the workflows your team uses. According to HumanLayer's analysis of CLAUDE.md effectiveness, manually curated files outperform auto-generated ones because they capture institutional knowledge that no scanner can infer.
Use /init when...
- ●Starting a brand new project
- ●You want a scaffold to edit
- ●The project has standard tooling
Write from scratch when...
- ●You have strong opinions on patterns
- ●The project has unusual architecture
- ●You know the pitfalls already
Our recommendation
Run /init, then delete 80% of what it generates. Replace the generic output with specific instructions that would cause real mistakes if missing. A 30-line curated file beats a 150-line auto-generated one every time.
The 6 Essential Sections Every CLAUDE.md Needs
After maintaining CLAUDE.md files across 12+ projects, these are the sections that consistently prevent mistakes and save time. Anthropic's documentation recommends keeping the total file under 200 lines -- each section below targets 15-30 lines.
Project Context (2-3 lines)
One sentence describing what the project is and what stack it uses. Claude reads your package.json, but a plain-English summary orients it faster than file scanning.
# Project
React Router 7 + Tailwind CSS blog and SaaS platform.
Deployed on Vercel. TypeScript strict mode.Build, Test, and Lint Commands
The exact commands, not just tool names. Include flags, environment variables, and the order they should run. Claude will use these exact strings when it needs to build or test.
## Commands
- Build: npm run build
- Dev server: npm run dev (port 5173)
- Lint: npm run lint
- Type check: npx tsc --noEmit
- Test single file: npx vitest run path/to/test.ts
- Full test suite: npm testArchitecture Decisions
Decisions that affect how code should be written. These are the conventions Claude cannot infer from reading your source files. Focus on the "why" behind unusual choices.
## Architecture
- File-based routing via React Router 7
- Blog posts are TSX components, NOT markdown
- Each route must be registered in app/routes.ts
- No SSR -- all pages are client-rendered
- Tailwind only -- no CSS modules, no styled-componentsCoding Conventions
Specific patterns Claude should follow. "Use 2-space indentation" works. "Format code nicely" does not. Claude follows concrete instructions far better than abstract goals.
## Code Style
- Use hyphens (-) not em-dashes. Em-dashes break tooling.
- Import types with `import type { X }` syntax
- Prefer named exports over default exports
- No prose Tailwind classes -- use explicit utility classes
- Max 2-3 sentences per paragraph in blog postsKnown Pitfalls
The mistakes that cost you hours. This is the highest-value section of any CLAUDE.md file -- it prevents Claude from repeating errors your team already solved. Be specific about what happened and why.
## Pitfalls
- Blog posts MUST be added to app/routes.ts or they 404
- Never include trailing newlines in env var values
(breaks Vercel deployments)
- The Edit tool fails on em-dashes -- always use hyphens
- Run npm run build before committing -- type errors
are not caught by the dev serverWorkflow Rules
How Claude should approach tasks in this project. These are process instructions, not code style rules. They shape Claude's behavior at a higher level.
## Workflow
- Read files before modifying them
- Run build after every significant change
- Prefer editing existing files over creating new ones
- Ask before any external action (API calls, emails)
- Use trash instead of rm for file deletionA Real Production CLAUDE.md (Annotated)
Here is an actual CLAUDE.md from a production React Router 7 project. At 45 lines, it covers everything Claude needs without bloating the context window. Each section earns its place by preventing a specific class of mistakes.
# KaiShips.com
React Router 7 + Tailwind CSS blog and SaaS platform.
Deployed on Vercel. TypeScript strict mode.
## Commands
- Build: npm run build
- Dev: npm run dev (port 5173)
- Type check: npx tsc --noEmit
- Deploy: git push (Vercel auto-deploys from main)
## Architecture
- File-based routing: app/routes.ts defines all routes
- Blog posts: TSX components in app/routes/blog.*.tsx
- Each new blog post MUST be added to:
1. app/routes.ts (route registration)
2. app/routes/blog.tsx (posts array)
## Code Style
- No em-dashes anywhere (use hyphens or double hyphens)
- Import types: import type { Route } from "./+types/..."
- No Tailwind prose classes -- use explicit utility classes
- Blog posts use card-based component layout
- Max 2-3 sentences per paragraph
## Pitfalls
- Trailing newlines in env vars break Vercel deployments
- The Edit tool breaks on em-dash characters
- Blog routes 404 if not added to routes.ts
- Build must pass before committing (type errors are silent in dev)
## Workflow
- Read files before editing them
- Run npm run build before committing
- Prefer editing existing files over creating new ones
- Use trash instead of rm
- Ask before external actions (API calls, emails, tweets)Notice what is not in this file: no explanation of what React Router is, no TypeScript tutorial, no Tailwind documentation. Claude already knows those. The file only contains what Claude cannot infer from the codebase itself.
The .claude/rules/ Directory: Modular Instructions
When your CLAUDE.md grows past 200 lines, the answer is not to keep stuffing it. Claude Code supports a .claude/rules/ directory where you place modular rule files. Every markdown file in this directory is automatically loaded with the same priority as your main CLAUDE.md.
The key advantage: rule files support paths: frontmatter that scopes rules to specific directories. A rule about API error handling only loads when Claude works on files in your API directory -- keeping irrelevant instructions out of context.
# .claude/rules/testing.md
---
paths:
- "src/**/*.test.ts"
- "src/**/*.test.tsx"
---
## Testing Rules
- Use Vitest, not Jest
- Co-locate test files next to source files
- Mock external APIs, never mock internal modules
- Every test file needs at least one integration test# .claude/rules/security.md
---
paths:
- "src/api/**"
- "src/auth/**"
---
## Security Rules
- Validate all user input at API boundaries
- Never log sensitive data (tokens, passwords, PII)
- Use parameterized queries -- no string concatenation
- Rate limit all public endpointsAuto-loaded
No import syntax needed. Every .md file in the directory is picked up automatically.
Path-scoped
Rules only activate when Claude touches matching file paths. Keeps context lean.
Version-controlled
Check these into git. Your team shares the same rules without manual setup.
CLAUDE.md vs settings.json: Guidance vs Enforcement
One of the most common mistakes is putting enforcement rules in CLAUDE.md. The distinction matters: CLAUDE.md is guidance that Claude interprets. settings.json is enforcement that the Claude Code runtime executes deterministically. If you want something to always happen, it belongs in settings.json.
| Rule Type | Put In | Example |
|---|---|---|
| Code style preference | CLAUDE.md | "Prefer functional components" |
| Auto-format on save | settings.json | PostToolUse hook runs prettier |
| Architecture decision | CLAUDE.md | "Use React Router for routing" |
| Block dangerous commands | settings.json | permissions.deny blocks rm -rf |
| Run tests after edits | settings.json | PostToolUse hook runs vitest |
| Known pitfall warning | CLAUDE.md | "Trailing newlines break deploys" |
The rule of thumb: if Claude ignoring the instruction would cause a real problem, it belongs in settings.json as a hook or permission rule. CLAUDE.md instructions are best-effort -- Claude follows them most of the time, but not 100%.
7 CLAUDE.md Mistakes That Waste Your Time
We learned these the hard way over months of daily Claude Code usage. Each mistake below cost us at least a full day of debugging before we identified the root cause.
Dumping your entire style guide
A 500-line CLAUDE.md with every ESLint rule listed individually. LLMs reliably follow 150-200 instructions (Anthropic, 2026). Beyond that, instruction-following degrades exponentially. Put style enforcement in your linter, not your CLAUDE.md.
Explaining what Claude already knows
Writing "React is a UI library" or "TypeScript adds static typing." Claude knows what React and TypeScript are. Your CLAUDE.md should only contain information Claude cannot infer from the codebase or its training data.
Vague instructions
"Write clean code" or "follow best practices" gives Claude nothing actionable. Specific: "Use 2-space indentation, named exports, and import type for type-only imports." The more concrete your instruction, the more reliably Claude follows it.
Putting enforcement in markdown
Writing "always run tests before committing" in CLAUDE.md does not guarantee tests run. Claude may forget or skip it under context pressure. Move critical enforcement to settings.json hooks where the runtime executes them deterministically.
Stale instructions after refactors
Your CLAUDE.md says "use the UserService class" but you refactored to a functional pattern last month. Stale instructions cause Claude to generate code that does not match your current architecture. Update CLAUDE.md in the same PR as major refactors.
Conflicting instructions
Your CLAUDE.md says "always use default exports" but a nested CLAUDE.md says "use named exports." Claude gets confused and alternates between patterns. Audit for contradictions across your file hierarchy.
Never updating after /init
Running /init once and never touching the file again. Your project evolves -- new patterns, new pitfalls, new team conventions. Schedule a quarterly CLAUDE.md review. Anthropic recommends refreshing project context every 8-12 weeks for optimal AI performance.
Advanced Patterns: @imports, Conditional Rules, and Team Setups
Once you have the basics working, these patterns help you scale CLAUDE.md across larger projects and teams. Each pattern solves a specific scaling problem that emerges as your project grows.
@imports for Shared Rules
Reference external markdown files to keep your CLAUDE.md lean. Useful for shared rule sets across multiple projects or for pulling in team-wide standards from a central location.
# In your CLAUDE.md
@~/.claude/shared-rules.md
@./docs/api-conventions.mdMonorepo Pattern
For monorepos, use a root CLAUDE.md for shared conventions and package-level CLAUDE.md files for package-specific instructions. Claude loads the most specific file when working in a subdirectory.
monorepo/
CLAUDE.md # Shared: TypeScript, git conventions
packages/
api/
CLAUDE.md # API: Express, Prisma, error handling
web/
CLAUDE.md # Web: React, Tailwind, component rules
shared/
CLAUDE.md # Shared: utility function patternsTeam Setup: Personal + Project
Each developer keeps personal preferences in ~/.claude/CLAUDE.md while sharing project conventions via the repo-level file. This separates individual style from team standards without conflicts.
# ~/.claude/CLAUDE.md (personal, not committed)
- I prefer verbose variable names
- Always explain your reasoning before making changes
- Use vim keybindings in examples
# ./CLAUDE.md (project, committed to git)
- 2-space indentation
- Functional components only
- All API routes in src/api/Connecting CLAUDE.md to Hooks and Settings
CLAUDE.md works best as part of a complete configuration stack. Your CLAUDE.md says what Claude should do. Your settings.json enforces what must happen. Together they create a reliable development environment. Here is how they connect.
// .claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "npx prettier --write $TOOL_INPUT_FILE_PATH"
}
],
"PreCommit": [
{
"command": "npm run lint && npm run build"
}
]
},
"permissions": {
"deny": [
"rm -rf",
"git push --force"
]
}
}The pattern: CLAUDE.md handles the subjective ("prefer functional components"), settings.json handles the objective ("run prettier after every edit"). This division means Claude's code follows your style preferences while the runtime guarantees formatting and safety -- even if Claude's instruction-following is imperfect.
CLAUDE.md handles
- ●Architecture decisions
- ●Coding preferences
- ●Known pitfalls
- ●Workflow guidance
settings.json handles
- ●Auto-formatting hooks
- ●Permission restrictions
- ●Pre-commit validation
- ●Model configuration
How to Know If Your CLAUDE.md Is Working
A good CLAUDE.md reduces the number of times you correct Claude per session. Track these signals to know whether your file is pulling its weight or just adding context bloat.
Working Well
- ✓Claude uses correct build commands first try
- ✓Generated code matches your patterns
- ✓Known pitfalls are avoided without reminding
- ✓New sessions feel like continuing old ones
Needs Work
- ✕You repeat the same correction 3+ times
- ✕Claude ignores most of your instructions
- ✕Context token usage is unusually high
- ✕Claude generates code using deprecated patterns
Pro tip: Use the /context command
Run /context in Claude Code to see how many tokens your CLAUDE.md and rules files consume. If your project instructions take more than 2,000 tokens, consider trimming or moving content to .claude/rules/ with path scoping.
Quick Start Template: Copy and Customize
Start with this template and fill in your project's specifics. It covers the 6 essential sections in under 40 lines. Every placeholder maps to a real decision you need to make about your project.
# [Project Name]
[One-sentence description of what this project is and its stack.]
## Commands
- Build: [your build command]
- Dev: [your dev server command]
- Test: [your test command]
- Lint: [your lint command]
- Deploy: [your deploy command or "manual"]
## Architecture
- [Routing approach and file structure]
- [Database/API patterns]
- [Key architectural decisions + WHY]
## Code Style
- [Indentation and formatting]
- [Import conventions]
- [Naming patterns]
- [Component patterns (if frontend)]
## Pitfalls
- [Bug or mistake that cost you time]
- [Environment-specific gotcha]
- [Tooling quirk Claude should know about]
## Workflow
- [How Claude should approach changes]
- [What to run before committing]
- [What requires human approval]The complete playbook
Get every config, template, and production-tested pattern in the full KaiShips Guide to Claude Code.
This post covers CLAUDE.md setup. The guide covers hooks, subagents, memory systems, MCP servers, worktrees, and 6 more chapters of battle-tested configurations.
Get the KaiShips Guide to Claude Code -- $29Frequently Asked Questions
What is CLAUDE.md in Claude Code?
CLAUDE.md is a markdown file that Claude Code reads at the start of every session. It contains project-specific instructions like build commands, coding conventions, architecture decisions, and workflow rules. Think of it as onboarding documentation that Claude reads automatically so you never repeat yourself.
Where should I put my CLAUDE.md file?
Place your main CLAUDE.md in the project root directory. Claude Code also supports a user-level file at ~/.claude/CLAUDE.md for global preferences, and nested CLAUDE.md files in subdirectories for folder-specific instructions. The most specific file takes precedence when Claude works in that directory.
How long should CLAUDE.md be?
Keep your CLAUDE.md under 200 lines. According to Anthropic's best practices documentation, frontier LLMs reliably follow 150-200 instructions. Beyond that, instruction-following degrades. Move detailed topic-specific guidance into .claude/rules/ files or separate markdown files referenced with @imports.
Should I use /init to generate CLAUDE.md?
Use /init as a starting point, not a finished product. The /init command analyzes your project structure and generates a basic CLAUDE.md, but it produces generic output. You should edit the result to add project-specific conventions, known pitfalls, and the exact commands your team uses. The auto-generated version misses the context that makes CLAUDE.md valuable.
What is the difference between CLAUDE.md and settings.json?
CLAUDE.md contains guidance -- coding conventions, architecture decisions, and workflow preferences that Claude interprets. settings.json contains enforcement -- permission rules, hook commands, and model configuration that the Claude Code runtime executes deterministically. Use CLAUDE.md for 'prefer functional components' and settings.json for 'run eslint after every file edit.'
Related Guides
Claude Code Hooks Guide
Automate workflows with lifecycle events -- the settings.json companion to your CLAUDE.md.
Claude Code Setup Guide
Install Claude Code, pick the right model, and run your first task from zero.
Claude Code Subagents Tutorial
Delegate tasks, run parallel operations, and cut context bloat by 60%.
Best Configuration Guide
Complete settings guide for performance tuning and optimization.