AI Claude Code CLAUDE.md coding rules developer tools token optimization Skills memory management 2026

How to Write a CLAUDE.md File: The Complete 2026 Guide (Q2 Updated with Official Best Practices)

The Prompt Shelf ·

If you use Claude Code, the single most impactful thing you can do is write a good CLAUDE.md file. It is the system prompt for your codebase. Every time Claude Code reads your project, it reads CLAUDE.md first, and everything it does afterward is shaped by what it finds there.

This guide covers what CLAUDE.md is, why it matters, how to structure it, and what patterns the best open-source projects use. Every example here comes from real repositories.

What Is CLAUDE.md?

CLAUDE.md is a Markdown file placed at the root of your repository (or in subdirectories) that gives Claude Code persistent instructions about your project. Think of it as a README that is written for your AI coding assistant instead of for human developers.

When you run Claude Code in a directory that contains a CLAUDE.md file, Claude reads it automatically at the start of every session. Unlike conversation context that disappears, CLAUDE.md persists. It is always there, always loaded, always influencing how Claude behaves.

Anthropic introduced CLAUDE.md as part of Claude Code’s agentic coding workflow. It has since become one of the most widely adopted standards for AI coding configuration, alongside .cursorrules and AGENTS.md.

Why CLAUDE.md Matters

Without a CLAUDE.md, Claude Code makes reasonable guesses about your project. With one, it can follow your exact conventions, avoid patterns you dislike, and produce code that fits your codebase on the first try.

Here is what a well-written CLAUDE.md eliminates:

  • Repeated corrections. If you keep telling Claude “use single quotes” or “don’t use classes,” that belongs in CLAUDE.md.
  • Style inconsistencies. Your CLAUDE.md can specify formatting conventions, naming patterns, and import ordering that Claude follows automatically.
  • Wrong architectural decisions. Tell Claude which patterns to prefer (e.g., server components over client components) and it will default to them.
  • Wasted context window. Instead of spending tokens re-explaining your project every session, CLAUDE.md handles it once.

The Vercel Next.js CLAUDE.md (138K stars) is a perfect example. It specifies everything from the monorepo structure to the preferred testing framework, and contributors report dramatically fewer review cycles when Claude follows it.

File Placement and Hierarchy

CLAUDE.md files can live at multiple levels:

  • Repository root (/CLAUDE.md) — Loaded for every session in the project. This is where project-wide rules go.
  • Subdirectories (/packages/api/CLAUDE.md) — Loaded only when Claude is working in that directory. Use this for package-specific rules in monorepos.
  • User-level (~/.claude/CLAUDE.md) — Loaded for every project you work on. Good for personal preferences like editor settings or formatting habits.

Claude reads them in order: user-level first, then root, then subdirectory. More specific files take precedence.

Structure of an Effective CLAUDE.md

After analyzing dozens of CLAUDE.md files from top repositories on The Prompt Shelf , a clear pattern emerges. The best files share these sections:

1. Project Overview

Start with a brief description of what the project is and its tech stack. This gives Claude the context it needs to make architecture decisions.

# Project

This is a Next.js 14 application using the App Router, TypeScript,
Tailwind CSS, and Drizzle ORM with PostgreSQL.

The LangChain CLAUDE.md opens with a clear description of the project’s purpose and its core abstractions, so Claude understands the domain before writing any code.

2. Code Style and Conventions

This is the section that saves you the most time. Be specific and prescriptive.

## Code Style

- Use functional components with arrow functions
- Prefer named exports over default exports
- Use TypeScript strict mode; no `any` types
- Imports: React first, then third-party, then local (with blank lines between groups)
- File naming: kebab-case for files, PascalCase for components

The Excalidraw CLAUDE.md is particularly thorough here, specifying not just formatting but architectural preferences like component composition patterns and state management approaches.

3. Architecture and Patterns

Tell Claude which patterns to prefer and which to avoid.

## Architecture

- Server Components by default; only use 'use client' when necessary
- Data fetching happens in Server Components, never in client components
- Use Server Actions for mutations
- Keep components small; extract to separate files at ~50 lines

The Dan Abramov / Overreacted CLAUDE.md demonstrates how to encode strong architectural opinions that keep the codebase consistent.

4. Project-Specific Commands

If your project has unusual build steps, test commands, or development workflows, document them.

## Commands

- `pnpm dev` — Start development server
- `pnpm test` — Run Vitest in watch mode
- `pnpm lint` — ESLint + Prettier check
- `pnpm db:push` — Push schema changes to database

The Deno CLAUDE.md includes detailed build and test instructions because the project has a non-standard build system that Claude would not know about otherwise.

5. What NOT to Do

Negative instructions are surprisingly effective. Telling Claude what to avoid is often more impactful than telling it what to do.

## Do NOT

- Do not use `class` components
- Do not use `any` type
- Do not add dependencies without asking
- Do not modify the database schema directly
- Do not use inline styles

The CockroachDB CLAUDE.md includes explicit constraints about which subsystems Claude should not modify and which testing patterns to avoid.

6. File Organization

In larger projects, tell Claude where things live.

## File Structure

- `src/components/` — Reusable UI components
- `src/app/` — Next.js App Router pages
- `src/lib/` — Utility functions and shared logic
- `src/db/` — Database schema and migrations

7. Testing Expectations

Specify how and when tests should be written.

## Testing

- Every new component needs a test file in __tests__/
- Use Testing Library for component tests
- Use Vitest, not Jest
- Integration tests go in tests/integration/
- Run `pnpm test:unit` before committing

Real-World Examples Worth Studying

Here are CLAUDE.md files from notable projects, all available on The Prompt Shelf:

Vercel Next.js — The gold standard for monorepo CLAUDE.md files. Covers the entire Next.js framework codebase with detailed testing and contribution guidelines. 138K stars.

LangChain — Shows how to document a complex Python library with multiple packages. Strong focus on import conventions and testing patterns. 128K stars.

Excalidraw — A great example for React applications. Specifies component patterns, state management, and UI conventions. 118K stars.

Deno — Demonstrates CLAUDE.md for a Rust-based runtime. Covers build system quirks and cross-platform considerations. 106K stars.

Zed Editor — Shows how to document a Rust application using the GPUI framework. Includes detailed instructions about the custom UI framework. 76K stars.

Anthropic’s Official Guide — Anthropic’s own recommendations for writing CLAUDE.md. Concise and principled.

Freek Van der Herten / Spatie Laravel — An excellent example for PHP/Laravel projects. Shows that CLAUDE.md works well beyond the JavaScript ecosystem.

Best Practices

After reviewing hundreds of CLAUDE.md files, these patterns consistently produce better results:

Be specific, not abstract. “Use Tailwind CSS for styling” is better than “Follow modern CSS practices.” “Use cn() from @/lib/utils for conditional classes” is better still.

Keep it under 500 lines. Claude reads the entire file every session. If it is too long, the important rules get diluted. Move detailed documentation to separate files and reference them.

Use examples. Show Claude what good code looks like in your project. A 5-line code example is worth 50 lines of description.

Update it regularly. Your CLAUDE.md should evolve with your codebase. If you find yourself repeatedly correcting Claude about something, add it to the file.

Test your rules. After changing CLAUDE.md, start a fresh Claude session and ask it to perform a common task. Verify it follows the new rules.

Do not duplicate your README. CLAUDE.md is for AI-specific instructions. Setup steps that a human developer needs but Claude does not should stay in README.md.

Use subdirectory files for monorepos. A single massive CLAUDE.md for a monorepo with 20 packages will be less effective than a root file with shared rules plus package-specific files.

CLAUDE.md vs Other Formats

CLAUDE.md is specific to Claude Code. If your team uses multiple AI tools, you may also need:

The good news is that these formats are similar enough that you can maintain one source of truth and adapt it. See our comparison guide for a detailed breakdown.

Token Cost: Why Size Matters (2026 Q2 Update)

The single most-cited mistake in CLAUDE.md authoring is over-specification. Anthropic’s official best-practices guide puts it bluntly: “Bloated CLAUDE.md files cause Claude to ignore your actual instructions!”

Three numbers to internalize:

NumberMeaning
Every sessionCLAUDE.md is loaded into context at the start of every Claude Code session. There is no opt-out and no “skip if not needed” branch — it is always paid for.
~50 instructionsThe Claude Code system prompt itself contains roughly 50 individual instructions, consuming about a third of practical instruction capacity before your CLAUDE.md adds a single line.
150-200 instructionsEmpirical work from production teams (notably HumanLayer) puts the realistic ceiling of frontier-model instruction-following at ~150-200 simultaneous instructions. Past that ceiling, adherence collapses and rules near the bottom of the file get silently ignored.

This is why the HumanLayer guide recommends under 300 lines as a soft cap and notes their own production root CLAUDE.md is under 60 lines. The leverage works both ways: a good line lifts every session, a bad line poisons every session.

If you suspect bloat, run a simple test: ask Claude Code to summarize your CLAUDE.md back to you in one paragraph. The parts it omits or paraphrases away are the parts the model is already de-prioritizing.

The Anthropic Official Include/Exclude Table

Anthropic’s official best-practices documentation ships a decision table for what belongs in CLAUDE.md. It is the most opinionated public statement Anthropic has made on the question, and it captures most edge cases:

✅ Include❌ Exclude
Bash commands Claude can’t guessAnything Claude can figure out by reading code
Code style rules that differ from defaultsStandard language conventions Claude already knows
Testing instructions and preferred test runnersDetailed API documentation (link to docs instead)
Repository etiquette (branch naming, PR conventions)Information that changes frequently
Architectural decisions specific to your projectLong explanations or tutorials
Developer environment quirks (required env vars)File-by-file descriptions of the codebase
Common gotchas or non-obvious behaviorsSelf-evident practices like “write clean code”

The Include column is grounded in the same principle: only write what Claude cannot derive from reading the code. If a line could be replaced by npm run lint --help, delete the line. If it could be replaced by a linter rule, delete the line and write the rule. “Never send an LLM to do a linter’s job” — HumanLayer’s variant of the same idea — captures the asymmetry.

For tuning adherence on the rules you do keep, Anthropic suggests adding emphasis tokens: “IMPORTANT” or “YOU MUST” in front of high-stakes rules measurably improves how often Claude obeys them. Reserve these for genuinely high-stakes rules; if every rule is “IMPORTANT,” none are.

The @import Pattern: Modular CLAUDE.md

A single monolithic CLAUDE.md is the wrong shape for any project beyond toy size. Claude Code supports @path/to/import syntax inside CLAUDE.md, letting you compose a small root file from multiple targeted files:

# Project Root CLAUDE.md
See @README.md for overview and @package.json for npm commands.

# Code style
- Use TypeScript strict mode
- See @docs/style-guide.md for full conventions

# Workflow
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.md

The imports are resolved at session start. Several practical wins:

  • Pin large docs out of the root — keep the root CLAUDE.md to under 60-100 lines for instant scanning, push detail into imports
  • Per-developer overrides@~/.claude/my-project-instructions.md lets each developer add personal preferences without polluting the team’s shared file
  • Monorepo composition — root CLAUDE.md imports from each package’s own packages/foo/CLAUDE.md
  • Skill-adjacent persistence — keep workflow specs in importable files that can be referenced from both CLAUDE.md and ad-hoc prompts

Combine @import with the placement rules below (home / project root / .local.md / parent / child) for fine-grained context control.

CLAUDE.md vs Skills: When to Use Each

Since v2.0 of Claude Code, Skills are the recommended place for domain knowledge and reusable workflows. The decision rule from Anthropic’s docs:

“CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use skills instead. Claude loads them on demand without bloating every conversation.”

Concrete examples:

Belongs in CLAUDE.md (always relevant)Belongs in .claude/skills/ (sometimes relevant)
“Use pnpm not npm""How to add a new GraphQL resolver"
"Run typecheck after edits""Database migration runbook"
"Don’t write to migrations/ without asking""API endpoint authoring conventions"
"Branch naming: feat/, fix/, chore/""Stripe webhook debugging guide"
"Production env vars live in .envrc.local""Sentry investigation playbook”

The rule of thumb: if you’d want this loaded into context every single session, it belongs in CLAUDE.md. If it’s only relevant when the user explicitly invokes a workflow or asks about a topic, it belongs in a Skill. For our full guide on the Skills system see 15 Best Claude Code Skills You Should Install in 2026.

Treating CLAUDE.md as Code

Anthropic’s docs are explicit: “Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude’s behavior actually shifts.” This implies a maintenance cycle most teams skip:

Review: If Claude keeps doing something you don’t want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Both are signals to prune or rephrase, not to add more rules.

Prune: Quarterly, walk the file line by line and ask: “Would removing this cause Claude to make mistakes?” If not, cut it. Most teams accumulate 30-50% dead weight within six months of starting a CLAUDE.md — old commands, old style rules, old gotchas that no longer apply.

Test: Treat behavior changes like a deploy. Make a CLAUDE.md edit, then run a representative task and watch whether Claude’s behavior actually shifted in the intended direction. If not, the edit didn’t take — usually because the rule got lost in volume or the wording was ambiguous.

Version: Check CLAUDE.md into git. Use PR review for changes, just like code. A team-shared CLAUDE.md gains value over time as people contribute project-specific gotchas.

Common Anti-Patterns from 2026 Production Teams

These are the patterns Anthropic and high-volume Claude Code shops (HumanLayer, etc.) flag most often:

  1. The kitchen-sink CLAUDE.md — Everything ever known about the project is dumped in. Length crosses 500 lines. Claude ignores the bottom third. Fix: ruthless pruning + @import for detail files.
  2. Linter rules disguised as instructions"Use 2-space indent" belongs in .prettierrc, not CLAUDE.md. Every line that could be enforced by tooling should be enforced by tooling.
  3. Frequently-changing facts"The current sprint is sprint 47" will be wrong in a week. CLAUDE.md should only contain semi-permanent context.
  4. Defensive over-specification — “Don’t break the build”, “Don’t introduce security vulnerabilities”. These are self-evident. They take space without adding signal.
  5. Hotfix lingering — A rule was added to fix yesterday’s bug. The bug is fixed. The rule is now noise. Hotfixes should be temporary; move them to commit messages or remove them once the underlying issue is resolved.
  6. Per-file documentation"auth.tshandles login,user.ts handles user data" — Claude can read those files itself. Per-file docs in CLAUDE.md is almost always wasted tokens.
  7. /init-generated files left as-is/init produces a starter, not a finished product. Teams that ship the /init output unedited end up with bloated, generic files. Use /init as scaffolding, then ruthlessly prune.

Getting Started

If you do not have a CLAUDE.md yet, start small:

  1. Create a CLAUDE.md file at your project root.
  2. Add a one-paragraph project description.
  3. List your 5 most important coding conventions (only those that differ from defaults).
  4. Add 3 things Claude should never do (only non-obvious ones).
  5. Include your most common development commands (only those Claude can’t guess).

That is enough to see a noticeable improvement. Aim for under 60-100 lines at the root. Expand the file with @import modules as you discover patterns that need documentation. Re-read it every quarter and cut what no longer earns its place.

Browse our full collection of CLAUDE.md files for inspiration, or check the complete rules gallery to see how other projects configure their AI coding assistants.

FAQ

How long should my CLAUDE.md be?

There is no hard limit, but under 300 lines is a useful soft cap, with under 60-100 lines being the sweet spot for the root file. HumanLayer’s own production root CLAUDE.md sits under 60 lines and they recommend the same to others. Past 300 lines you risk hitting the ~150-200 frontier-model instruction-following ceiling and seeing rules near the end of the file get silently ignored. For larger projects, use @import to split detail into composable modules.

What’s the difference between CLAUDE.md and Skills?

CLAUDE.md is loaded into context at the start of every session, so it should only contain rules that apply broadly. Skills (.claude/skills/<name>/SKILL.md) are loaded on demand — when Claude judges them relevant to the current task, or when you invoke them explicitly with /skill-name. Use CLAUDE.md for always-relevant project rules (commands, style, gotchas) and Skills for sometimes-relevant domain knowledge (how to add a resolver, migration runbook, etc.).

Where can I place a CLAUDE.md file?

Five canonical locations, all loaded automatically when relevant: (1) home folder ~/.claude/CLAUDE.md (applies to all sessions across all projects), (2) project root ./CLAUDE.md (checked into git, shared with team), (3) project root ./CLAUDE.local.md (personal, gitignored), (4) parent directories for monorepos, (5) child directories loaded on demand when working with files in those directories.

How does the @import syntax work?

Inside any CLAUDE.md you can write @path/to/file.md to inline that file’s contents at session start. Imports can be relative paths (@docs/style-guide.md), absolute paths (@/Users/me/.claude/overrides.md), or home-relative (@~/.claude/my-project-instructions.md). The pattern lets you keep the root CLAUDE.md short and modular while pulling in detail on a per-concern basis.

Should I use “IMPORTANT” or “YOU MUST” in my CLAUDE.md?

Yes for genuinely high-stakes rules. Anthropic’s docs note that emphasis tokens like IMPORTANT or YOU MUST measurably improve adherence — but only when reserved for rules that actually matter. If every rule is “IMPORTANT,” none are. Use them for security boundaries, destructive-operation prevention, and irreversible-action guardrails; not for stylistic preferences.

Should I include the /init output in my CLAUDE.md?

Use /init as a starting point, then ruthlessly prune. The /init command analyzes your codebase and generates a plausible starter file, but it errs toward verbosity and tends to include per-file descriptions and standard conventions Claude could derive from the code itself. Teams that ship the /init output unedited end up with bloated files. HumanLayer explicitly recommends against using /init output as-is.

Does CLAUDE.md work with non-Claude tools?

CLAUDE.md is Claude Code-specific. For multi-tool teams, the cross-tool standards are AGENTS.md (used by Codex, Claude Code, and a growing list of agents — see our AGENTS.md vs CLAUDE.md guide), .cursor/rules/ (Cursor), .windsurf/rules/ (Windsurf), and .github/copilot-instructions.md (Copilot). The content overlap is high enough that one source of truth can be adapted, and tools like Caveman.MD drop compression rules into all of them simultaneously.

How often should I update my CLAUDE.md?

Quarterly review minimum. Specifically: (1) when Claude repeatedly does something a rule was supposed to prevent — the rule is probably lost in noise, prune or rephrase, (2) when Claude asks questions the file already answers — the phrasing is ambiguous, rewrite, (3) when project conventions change — add the new convention and remove the old one in the same edit, (4) every quarter walk the file line by line and ask “Would removing this cause Claude to make mistakes?” — if not, cut.

External References

Related Articles

Explore the collection

Browse all AI coding rules — CLAUDE.md, .cursorrules, AGENTS.md, and more.

Browse Rules