- Prompting
- Claude Md
What is CLAUDE.md?
The CLAUDE.md file is the persistent context of your project. Claude Code reads it automatically at the start of every session and uses it as a foundation for all its responses. It's your most effective way to transform Claude from a generalist assistant into a team member who knows your project inside and out.
Generating a CLAUDE.md with /init
The fastest way to create a CLAUDE.md is to use the built-in /init command. It automatically analyzes your project and generates a tailored file.
# In your terminal, launch Claude Code at the project rootclaude# Then type the /init command> /init
Automatic analysis
Claude scans your codebase: package.json, tsconfig.json, folder structure, configuration files, installed dependencies.
CLAUDE.md generation
Claude generates a CLAUDE.md file at the root of your project with the relevant sections: stack, commands, architecture, conventions.
Customization
Review the generated file and adjust it. Add your specific conventions, remove what's not relevant, and fill in any missing sections.
Recommended structure
An effective CLAUDE.md follows a 6-section structure. The order matters: the most important information goes first, since Claude gives it more weight.
Section 1: Project overview
# CLAUDE.mdNext.js 14 documentation site (App Router), strict TypeScript, Tailwind CSS, MDX.Deployed via Docker (Nginx Alpine). 100% static (SSG), no SSR or API routes.URL: https://my-site.com
This section gives Claude the minimal context to understand which project it's working on. Keep it brief: 2-3 lines is enough.
Section 2: Commands
## Commands- `npm run dev`: Dev server (port 3000)- `npm run build`: Production build- `npm run lint`: ESLint + Prettier- `npm run type-check`: TypeScript verification- `npm run test`: Vitest in watch mode- `npm run test:coverage`: Test coverage
Claude uses these commands to run necessary checks. List every command Claude might need to use.
Section 3: Architecture
## Architecture/app -> Pages and layouts (App Router)/components/ui -> Reusable components/components/layout -> Header, Footer, Sidebar/lib -> Utilities and helpers/content -> MDX files/public -> Static assets
This section helps Claude navigate your codebase and create files in the right location.
Section 4: Code style
## Code style- Strict TypeScript, never `any`- Named exports only, no default exports (except Next.js pages)- Functional components with hooks, no React classes- Tailwind CSS only, no custom CSS- Files < 400 lines, functions < 50 lines- Immutability: always create new objects, never mutate
These are the rules Claude must always follow in this project. Be explicit.
Section 5: Content and writing
## Content- All content is in English- Tone: approachable, enthusiastic, never condescending- Use concrete analogies for technical concepts- Code blocks with language specified for syntax highlighting
If your project contains documentation or editorial content, these rules ensure consistency.
Section 6: Important rules
## Important rules- NEVER put secrets, API keys, or .env in the repo- Accessibility: WCAG 2.1 AA minimum- Images in WebP with lazy loading- Target Lighthouse score: > 90 on all 4 metrics
Critical rules that must never be violated. Claude treats them as priority constraints.
Real-world example of a well-written CLAUDE.md
Here's a complete CLAUDE.md for a typical SaaS project.
# CLAUDE.mdMyApp: Project management SaaS. pnpm monorepo.Stack: Next.js 14 (App Router), TypeScript, Tailwind CSS, Prisma, PostgreSQL.API: tRPC. Auth: NextAuth.js v5. Deployment: Vercel.## Commands- `pnpm dev`: Dev (turbo)- `pnpm build`: Production build- `pnpm lint`: ESLint- `pnpm type-check`: TypeScript- `pnpm test`: Vitest- `pnpm db:push`: Push Prisma schema- `pnpm db:seed`: Seed test data## Architectureapps/web/ -> Next.js frontendapps/api/ -> tRPC APIpackages/ui/ -> Shared design systempackages/db/ -> Prisma schema + clientpackages/config/ -> ESLint, TypeScript, Tailwind configs## Code style- Strict TypeScript (no any, no as unknown)- Mandatory immutability- Feature-based: src/features/[feature]/{components,hooks,utils}- Repository pattern for data access- Errors handled with Result<T, E> (no throw)## Conventions- Commits: feat:, fix:, refactor:, test:, docs:- PR: detailed description + test plan- Tests: mandatory TDD, coverage > 80%- API responses: { success, data, error, meta }## Security- No hardcoded secrets (.env only)- Inputs validated with Zod at all boundaries- Parameterized Prisma queries- Rate limiting on public endpoints
This CLAUDE.md is about 50 lines. It covers the essentials without overloading the context.
The 3 levels of CLAUDE.md
Claude Code supports CLAUDE.md files at multiple levels, from global to specific.
Level 1: Global
Path: ~/.claude/CLAUDE.md
Your personal preferences applied to all your projects: preferred language, commit style, personal conventions. This file is read first.
Level 2: Project
Path: ./CLAUDE.md (project root)
The project-specific context: stack, architecture, team conventions. This is the most important file. It's shared with the team via the repo.
Level 3: Module
Path: ./src/features/auth/CLAUDE.md
Ultra-specific context for a module: data schema, business constraints, external APIs. Use it for complex modules that have their own rules.
The hierarchy works through accumulation: all three levels combine, with the most specific level taking priority in case of conflict.
How Claude loads CLAUDE.md files
Creating the files is just the first step. What matters is knowing which ones Claude loads, and when. There are two distinct mechanisms at play.
Loading upward (ancestor loading)
At startup, Claude walks up the directory tree from your current working directory all the way to the filesystem root. Every CLAUDE.md it finds along the way gets loaded, from farthest to closest. The closest one wins in case of conflict.
/ ← CLAUDE.md loaded 1st
home/
you/
projects/
myapp/ ← cwd at startup
CLAUDE.md ← loaded 2nd (takes priority)
src/
CLAUDE.md ← not loaded yet
If you launch Claude from /myapp, only the CLAUDE.md files in /myapp and its parent directories are loaded. The one inside src/ is not touched yet.
Loading downward (descendant loading)
Claude loads CLAUDE.md files in subdirectories lazily: only when it touches a file inside that folder. If src/components/CLAUDE.md exists and Claude opens a file in src/components/, it loads that CLAUDE.md at that point.
Concrete example: with this file tree...
/project/
CLAUDE.md ← loaded at startup
src/
CLAUDE.md ← loaded at startup (cwd = /project)
auth/
CLAUDE.md ← loaded when Claude reads src/auth/
payments/
CLAUDE.md ← loaded when Claude reads src/payments/
...if the cwd is /project, the first two files load immediately. The other two wait until Claude enters their respective folders.
CLAUDE.md vs settings.json vs .claude/rules/
These three files have different, complementary roles. Here's how to use them.
| File | Role | Scope | Content |
|---|---|---|---|
| CLAUDE.md | Project context | Read every session | Stack, architecture, conventions, commands |
| settings.json | Technical configuration | Claude behavior | Model, permissions, allowed tools |
| .claude/rules/ | Thematic rules | Loaded by topic | Security, tests, performance, git |
# Complete Claude Code configuration structureproject/CLAUDE.md # Project context (committed).claude/settings.json # Technical config (committed or not)commands/ # Project Skillsreview-pr.mddeploy.mdrules/ # Thematic rules (committed)security.mdtesting.mdperformance.md~/.claude/CLAUDE.md # Global preferencessettings.json # Global configcommands/ # Personal Skillsrules/ # Global rules
.claude/rules/: splitting instructions into thematic files
When your CLAUDE.md starts pushing past 150 lines, some sections probably deserve their own file. The .claude/rules/ folder is built for this: Claude automatically loads every file in it at startup.
.claude/
rules/
code-style.md ← TypeScript conventions, naming, structure
testing.md ← test strategy, coverage requirements, mocks
security.md ← security rules, secrets handling
deployment.md ← deployment process, pre-prod checklist
Each file focuses on a single topic. When you update your testing rules, you edit testing.md without touching anything else. This makes things easier to maintain and simpler to review in pull requests.
Conditional directives with <important>
Some rules only apply in specific contexts. The <important if="..."> tag ensures Claude doesn't overlook them when the condition is met, even if the rest of the CLAUDE.md is dense.
<important if="editing auth code">Always check permissions before modifying files in src/auth/.Never store tokens in plain text in the code.Any change to the auth middleware must be covered by a test.</important><important if="writing database migrations">Test the migration against a production data dump before validating.Always write the reverse migration (down migration).Never drop a column without a deprecation period.</important>
This is stronger than an ordinary Markdown comment: Claude understands that these instructions carry high priority whenever the condition is met.
Agent memory
When you use sub-agents (agents launched by a parent agent), each one can have its own persistent memory, separate from the CLAUDE.md. There are three levels:
| Type | Storage | Scope |
|---|---|---|
memory: user | ~/.claude/agent-memory/ | Cross-project, personal |
memory: project | .claude/agent-memory/ | Shared with the team |
memory: local | .claude/agent-memory-local/ | Personal, on this project |
The first 200 lines of the corresponding MEMORY.md file are automatically injected at agent startup. This is useful for specialized agents that need to remember past decisions: a code review agent that retains your preferences, a documentation agent that knows the project's editorial style, and so on.
Best practices
What to put in CLAUDE.md
- The tech stack and important versions
- Build, test, and lint commands
- The project tree (simplified)
- Non-standard coding conventions
- Architectural patterns in use
- Naming rules
What NOT to put in it
- Secrets, tokens, or passwords (use
.env) - Code or snippets that are too long (use rules)
- Contradictory instructions
- Information that changes often (put it in rules)
- More than 200 lines of content
Updating CLAUDE.md
Update your CLAUDE.md when:
- You add a new technology to the stack
- You change a coding convention
- You adopt a new architectural pattern
- A new team member joins (add team conventions)
- You notice Claude keeps making the same mistakes (add the corresponding rule)
A simple habit: after fixing a recurring mistake, ask Claude directly to update the CLAUDE.md to reflect the new rule. It does this well, and it saves you from having the same conversation again later.
Deterministic behavior: settings.json over CLAUDE.md
Some behaviors shouldn't depend on how Claude interprets a line of text. For those, settings.json is more reliable than CLAUDE.md:
- Blocking specific tools (e.g.,
Bashfor security reasons) - Configuring read/write permissions
- Forcing a specific model for an agent
- Managing commit attribution
CLAUDE.md is text that Claude interprets. settings.json is configuration that Claude obeys.
Next steps
Your CLAUDE.md is now in place. Explore related topics.
- Advanced prompting and multi-agents: Advanced techniques for leveraging context
- Create a custom Skill: Turn your workflows into slash commands
- Understanding agents: Configure agents in your CLAUDE.md
- Claude Code configurator: Interactive tool to generate your configuration