Coding

The CLAUDE.md File: A Practical Guide With Examples

What a CLAUDE.md file is, where Claude Code looks for it, what to write and cut, how AGENTS.md fits in, and a full example file to copy.

Robert Youssef15 min
The CLAUDE.md File: A Practical Guide With Examples
On this page

A CLAUDE.md file is a plain markdown file that Claude Code reads at the start of every session. It holds what Claude can't work out from your code: the exact test command, the convention your team agreed on in a meeting, the folder that looks dead but isn't. Write it once, commit it, and every new session starts with that context already loaded.

This guide covers where Claude Code looks for the file, what earns a line in it, how imports and .claude/rules/ work, how it relates to AGENTS.md, and three example files you can copy. Every behavior described here comes from Anthropic's memory documentation and its best practices page, both checked on December 1, 2026.

What CLAUDE.md Does

Each Claude Code session begins with a fresh context window. CLAUDE.md is the part of the bridge between sessions that you control (the other part, auto memory, is covered in the FAQ). Claude Code loads it before your first prompt, so the commands and rules in it are present on every task.

Two things are worth knowing before you write a single line.

It's context, and Claude treats it that way. Anthropic's docs say the file arrives as a user message after the system prompt, and Claude tries to follow it, but "there's no guarantee of strict compliance", especially for vague or conflicting lines. A rule that has to hold every single time belongs in a permission rule or a hook. More on that below.

Every line also costs attention. The file loads into every session whether today's task needs it or not, so a short file that's all signal beats a long one Claude has to wade through. Anthropic's target is under 200 lines per CLAUDE.md file, and longer files "reduce adherence".

Where Claude Code Looks for CLAUDE.md

There are four places a CLAUDE.md file can live, and each reaches a different set of sessions:

Scope Location Who it applies to
Managed policy macOS: /Library/Application Support/ClaudeCode/CLAUDE.md; Linux and WSL: /etc/claude-code/CLAUDE.md; Windows: C:\Program Files\ClaudeCode\CLAUDE.md Everyone on the machine, set by IT
User ~/.claude/CLAUDE.md You, in every project
Project ./CLAUDE.md or ./.claude/CLAUDE.md Your team, shared through git
Local ./CLAUDE.local.md You, in this project only (add it to .gitignore)

The files don't override each other. Claude Code concatenates them, broadest first: managed, then user, then every CLAUDE.md from the filesystem root down to the folder where you launched Claude. Within each folder, CLAUDE.local.md comes after CLAUDE.md. So the instructions closest to your working directory are the last thing Claude reads. If two lines disagree, though, Claude may follow either one, so fix the conflict and don't count on the order.

To see what loaded, run /context all in a session and check the list under Memory files. Use /memory to open any of these files in your editor; picking one that doesn't exist yet creates it.

Nested CLAUDE.md files in subfolders

CLAUDE.md files above your working directory load at launch. Files in subfolders below it load on demand, the first time Claude reads, writes or edits a file in that folder. In a monorepo, packages/billing/CLAUDE.md costs nothing until Claude opens something in packages/billing/.

That's also why a nested file is missing from /context all at the start of a session. When it loads, the terminal prints a Loaded line with its path. If other teams' files in a large monorepo keep getting picked up, the claudeMdExcludes setting skips them by path or glob pattern.

Diagram of where Claude Code looks for CLAUDE.md: managed policy, user, project and local files load at launch in that order, and subfolder files load when Claude opens a file there
Load order runs top to bottom. Everything is concatenated, and nothing overrides anything else.

Create Your First File With /init

Run /init in your project. Claude analyzes the codebase and writes a starting CLAUDE.md with the build commands, test instructions and conventions it finds. If a CLAUDE.md already exists, /init suggests improvements and leaves the file in place.

It also reads instruction files written for other tools: Cursor rules in .cursor/rules/ or .cursorrules, and Copilot's .github/copilot-instructions.md. If it finds OpenAI Codex or Google Gemini CLI configuration on your machine, it offers to carry that over with /import.

For a guided version, start Claude Code with an environment variable set and then run /init:

CLAUDE_CODE_NEW_INIT=1 claude

With it set, /init asks which things to set up (CLAUDE.md files, skills, hooks), explores the codebase with a subagent, asks you follow-up questions, and shows a proposal you can review before it writes any file.

Treat whatever /init writes as a first draft. Anthropic's best practices page is blunt about what comes next: "the work is mostly removing lines." Two built-in checks help with that. /doctor proposes cuts for anything Claude can derive from the codebase, like directory layouts and dependency lists. /doctor prompt-audit (Claude Code v2.1.283 or later) flags instructions written for older models, references to files that no longer exist, and files that contradict each other. Nothing changes until you tell Claude to apply the fixes.

If you'd rather draft the file from a prompt, our CLAUDE.md generator prompt builds a structured first version from a description of your project. Its output includes an architecture map, so trim that part with the same test as everything else.

What to Put in CLAUDE.md, and What to Leave Out

The core of Anthropic's CLAUDE.md best practices is a two-question test for any line. Could Claude find this by reading the code? Would it actually go and look? If both answers are yes, leave it out.

Lines that pass:

  • The commands that prove work is done. The exact test, typecheck and lint commands, plus how to run a single test file. If your file has one line, make it this one: Claude uses it to check its own work as it goes.
  • Places where the code misleads. An old pattern that's everywhere but mustn't be copied into new code. A directory that looks unused and isn't.
  • Decisions that never made it into the repo. Which error helper the team settled on, how deploys work, what needs a migration review.
  • Anything you've had to correct twice. The memory docs list the same triggers: Claude repeats a mistake, a code review catches something Claude should have known, or you type a correction you already typed last session.

Lines that don't:

  • Architecture overviews and file trees. Anthropic lists "describe your architecture and file layout" under advice you can stop following. Claude reads the repo itself.
  • Rules nobody can verify. "Format code properly" gives Claude nothing to act on. "Use 2-space indentation" does.
  • IMPORTANT and ALL CAPS. Current models follow a plainly worded line, and piled-on emphasis mostly makes Claude over-apply the rule. When a line keeps getting missed, either the file is too long or the rule should be a hook.
  • Long procedures and narrow rules. A ten-step release checklist belongs in a skill. A rule that only matters in src/api/ belongs in a path-scoped rule (next section).
  • Your personal taste in a shared file. Put it in CLAUDE.local.md or ~/.claude/CLAUDE.md.

One more category deserves care: hard "never" rules. A line like Never read .env works almost every time. When almost isn't good enough, move it into configuration that Claude Code enforces on its own, such as a deny rule in .claude/settings.json:

{
  "permissions": {
    "deny": ["Read(./.env)", "Read(./.env.local)", "Read(./secrets/**)"]
  }
}

Deny rules hold in every permission mode. Steps that must always happen, like running a formatter after each edit, are a job for Claude Code hooks.

Imports and .claude/rules

A single CLAUDE.md gets crowded fast. Claude Code gives you two ways to split it, and they behave very differently on context.

Pull other files in with @path

Write @path/to/file anywhere in a CLAUDE.md and that file is imported. Relative paths resolve from the file that contains the import. Imported files can import others, up to four hops deep.

See @README.md for the project overview and @package.json for available scripts.

# Team workflow
- Git conventions: @docs/git-workflow.md
- My own notes for this repo: @~/.claude/my-project-notes.md

Two catches. Imports organize a file but don't shrink it: an imported file loads together with the CLAUDE.md that imports it, every session. And an import that points outside the project, like the home-folder one above, triggers a one-time approval dialog the first time Claude Code sees it. To mention a path without importing it, wrap it in backticks.

Scope rules to files with .claude/rules

For instructions that only matter in part of the codebase, use .claude/rules/. Put one markdown file per topic there, such as testing.md or api-design.md; subfolders work too. A rule file without frontmatter loads at launch, just like .claude/CLAUDE.md. Add a paths field and it only loads when Claude reads or edits a matching file:

---
paths:
  - "src/api/**/*.ts"
---

# API rules
- Validate request bodies with the schemas in src/api/schemas/
- Every new endpoint needs an entry in openapi.yaml

This is the mechanism that saves context. A path-scoped rule costs nothing while Claude works on the frontend. Personal rules that should apply in every project go in ~/.claude/rules/, and the folder accepts symlinks if you want one set of rules shared across repositories.

Multi-step procedures are a third option. A skill saved at .claude/skills/<name>/SKILL.md shows Claude only its name and description until a task calls for it. More in our guide to Claude Code skills.

CLAUDE.md vs AGENTS.md

AGENTS.md is an open format for instructions to coding agents. The agents.md site lists OpenAI's Codex, Cursor, Google's Gemini CLI and GitHub Copilot's coding agent among the tools that read it. Since Claude Code v2.1.277, Claude reads it too, with one condition: only when you have no CLAUDE.md.

Your repository has Claude Code reads
An AGENTS.md, and no CLAUDE.md or CLAUDE.local.md in your working directory or above it The AGENTS.md
An AGENTS.md and a CLAUDE.md or CLAUDE.local.md Only the CLAUDE.md files
A CLAUDE.md that imports @AGENTS.md The CLAUDE.md, with AGENTS.md included through the import

Watch the second row. CLAUDE.local.md counts as a CLAUDE.md here, so creating one for your private notes quietly stops Claude from reading the team's AGENTS.md. Your user-level ~/.claude/CLAUDE.md and .claude/rules/ files don't count and load alongside it.

If your team runs several agents, the tidy setup is one shared AGENTS.md plus a small CLAUDE.md next to it that imports it and adds anything Claude-specific. Anthropic's docs show this pattern:

@AGENTS.md

## Claude Code

Use plan mode for changes under `src/billing/`.

A symlink (ln -s AGENTS.md CLAUDE.md) also works when there's nothing Claude-specific to add. Skip it if anyone clones the repo on Windows: unless core.symlinks is enabled there, Git checks the link out as a one-line text file. To change the default altogether, open /config and set Project instructions to claude-md-and-agents-md (read both), claude-md or managed-only. For a comparison of the agents themselves, see Codex vs Claude Code.

Three Example CLAUDE.md Files

The first example is a complete file for a repository of reports and scripts. The other two are short starting points for an app and a service. Use them as templates, and adapt all three to your project first.

A worked example, explained line by line

# reports-workspace

Research reports built from data pulls, audits and written deliverables.
Scripts run locally. Nothing in this repo deploys anywhere.

## Read first
[STATUS.md](STATUS.md): one line per active report and where it stands.

## Where things go
reports/<name>/     one report per folder
  NOTES.md          state: what's done, what's verified, next step
  data/             raw exports that every number in the report comes from
methods/            how each type of job is done. Start at methods/README.md
scripts/            pulls, measurements, document builds

## Where lessons go
- A lesson about one report goes in reports/<name>/NOTES.md
- A lesson for every report goes in rules/ (a ban or a required step)
  or methods/ (how to do it). A lesson left only in chat is lost.

## Who you're working with
- The person running sessions isn't a developer. When a step needs them,
  give one command in a bash block, then check the result yourself.
- Their decisions only: money, access, what gets sent out.

## Environment
- Data API is read-only. How to pull: methods/data/pull.md
- Keys live in .env (gitignored). The maps key is MAPS_KEY_PROD,
  not MAPS_API_KEY, so a grep for the usual name finds nothing.
- No ImageMagick or LibreOffice here: resize images with Python Pillow,
  build .docx with scripts/build_docx.py
- macOS sed has no \b. Do word replacements in Python.

## Privacy
- Backups go to a private repository. It never becomes public.
- .env and credential files never enter git.

## Rules (loaded every session)
@rules/analysis.md
@rules/data.md
@rules/writing.md
Annotated CLAUDE.md example with eight numbered callouts: purpose, read-first link, folder conventions, where lessons go, who you're working with, environment gotchas, privacy lines and rule imports
The same file with its eight parts numbered. Each number matches a note below.

What each part is doing:

  1. Two lines of purpose, including what's out of scope. "Nothing in this repo deploys anywhere" saves Claude from hunting for a deploy step that doesn't exist.
  2. A link to the status file, not an import. Claude opens STATUS.md when it needs it. Writing @STATUS.md would load the whole file into every session, including the ones that have nothing to do with it.
  3. Conventions, not a file tree. The section doesn't describe code Claude can read. It says what each folder is for and where new things go, which no file in the repo states.
  4. A routing rule for lessons. This decision lives nowhere else, and it keeps CLAUDE.md short by sending detail into per-report notes and rule files.
  5. A working agreement for the whole team. Personal preferences would go in CLAUDE.local.md.
  6. Gotchas Claude would otherwise rediscover every session. The odd key name, the missing tools, the sed quirk on macOS.
  7. Privacy lines as guidance. .gitignore does the real enforcing here. A deny rule or a pre-commit hook would make the "never" absolute.
  8. Imports for rules every task needs. They still load every session, so the split is for the people maintaining them. Rules needed in only one folder would move to .claude/rules/ with a paths field.

Under 50 lines in total.

A Next.js app

A short file for a TypeScript web app, with the commands first and the traps last:

# Commands
- Install: pnpm install
- Dev server: pnpm dev
- One test file: pnpm vitest run path/to/file.test.ts
- Typecheck: pnpm tsc --noEmit
- Lint: pnpm lint --fix

# Conventions
- Server-only code lives in app/api/. Client components never import from it.
- Use the fetch wrapper in src/lib/http.ts, not raw fetch.
- src/legacy/ is still live. Don't copy its patterns into new code.

# Gotchas
- E2E tests need seed data: run pnpm db:seed first.
- Every variable is listed in .env.example. Never commit .env.

A Python service

The same three sections for a backend service, where most of the value sits in the conventions:

# Commands
- Setup: uv sync
- Tests: uv run pytest -q (one file: uv run pytest tests/test_orders.py -q)
- Types: uv run mypy src/
- Format and lint: uv run ruff format . && uv run ruff check --fix .

# Conventions
- All database access goes through src/repo/. Handlers never import the ORM directly.
- Raise errors from src/errors.py, never a bare Exception.
- After autogenerating a migration, read it before committing.

# Gotchas
- Integration tests need local Postgres: docker compose up db
- workers/ ships on a separate deploy. Changes there need a note in the PR.

Before and After: Trimming a Bloated CLAUDE.md

Here's the kind of file that grows when every fix gets a new line and nothing gets removed:

# Project Overview
This is a Next.js application using TypeScript, Tailwind and Prisma.
It is a SaaS dashboard for managing invoices.

## Directory Structure
- app/ - Next.js app router pages
- components/ - React components
- lib/ - utilities
- prisma/ - database schema

## IMPORTANT RULES
- ALWAYS write clean, maintainable code
- NEVER use any
- IMPORTANT: Run tests before committing!!!
- Follow best practices

## Release process
1. Bump the version in package.json
2. Update CHANGELOG.md
3. Tag the release and push the tag
4. Watch CI publish the package

And the same project after a trim:

# Commands
- Tests: pnpm test (one file: pnpm vitest run <path>)
- Typecheck: pnpm tsc --noEmit

# Conventions
- No `any`. Use `unknown` and narrow it.
- A sent invoice is never edited. Issue a credit note.

# Gotchas
- After editing prisma/schema.prisma, run pnpm db:generate before the dev server.

What changed, line by line:

  • Overview and directory structure: cut. Claude reads package.json and the folders on its own.
  • "Clean, maintainable code" and "follow best practices": cut. Nothing there can be checked.
  • The capital letters: gone. "NEVER use any" became a convention with the alternative spelled out.
  • "Run tests before committing": replaced by the test command. If tests must pass every time, a Stop hook or a pre-commit hook enforces it.
  • The release process: moved to a skill. Saved as .claude/skills/release/SKILL.md with disable-model-invocation: true, it only runs when you type /release.
  • Three lines added. The typecheck command, the step after a schema edit that Claude can't guess, and the rule about sent invoices, a business decision that isn't visible in the code.
Before and after comparison of a CLAUDE.md file: overview, directory tree and capitalized rules marked as cut, release steps marked as moved to a skill, and the short trimmed file on the right with three new lines marked
Most of the trim is deletion. The three new lines are a command, a gotcha and a business rule.

FAQ

What is in your CLAUDE.md file?

Usually four kinds of lines: the commands that build, test and lint the project, conventions that differ from what Claude would assume, gotchas, and decisions that aren't written down anywhere else. The three examples above show what that looks like in practice. Preferences that follow you everywhere, like how you want commit messages worded, belong in your personal ~/.claude/CLAUDE.md.

Why is Claude ignoring my CLAUDE.md?

Start with /context all. If the file isn't listed under Memory files, Claude never saw it, so check its location. If it did load, the line is probably vague, contradicts another file, or is buried in a long one. Rewrite it as something checkable. If the instruction is about commits or pull requests, it may be competing with Claude Code's built-in git guidance, which the includeGitInstructions setting turns off. And anything that must happen at a fixed moment, like before every commit, should be a hook.

Does CLAUDE.md survive /compact?

The project-root file does. After compaction, Claude Code re-reads it from disk. Nested files and path-scoped rules come back the next time Claude touches a matching file. What gets lost is anything you only said in chat.

How is CLAUDE.md different from auto memory?

You write CLAUDE.md. Claude writes auto memory: notes about your corrections and preferences, stored in ~/.claude/projects/<project>/memory/, with only the first 200 lines or 25KB of its MEMORY.md index loaded at startup. Asking Claude to "remember" something saves it to auto memory. Say "add this to CLAUDE.md" when you want it in the file.

Can I leave notes in CLAUDE.md that Claude won't read?

Yes. Block-level HTML comments, like <!-- why this rule exists -->, are stripped before the file reaches Claude, so they cost no context. Comments inside code blocks are kept.

Should CLAUDE.md be committed to git?

Yes for the project file, since committing it is how the rest of your team gets the same instructions in their sessions. Keep CLAUDE.local.md out with .gitignore.

Your First Version

Run /init, delete whatever Claude could read for itself, and add the one command that tells Claude whether its work passes. That's a better start than a long file nobody trims. When Claude gets something wrong twice, add a line, and check /context all now and then to see what's loading.

For the habits around the file (planning, checks, permission modes, running Claude unattended), read our Claude Code best practices. New to the tool itself? Start with the Claude Code tutorial.

Get set up faster: the free Claude Code Starter Guide covers the five layers of a Claude Code setup (CLAUDE.md, MCP, skills, subagents and hooks), why your quota burns and how to save it, plus ten prompts that work on a real repo.

Now with NjectAI

Get the right answer from AI the first time

It knows you, your work and your voice before you type a word. Save your context once in NjectAI and ChatGPT, Claude and Gemini start from there.

  • Nothing to pay for 7 days
  • Cancel anytime
  • Set up in 2 minutes

Prompts for this topic

Put this article to work with ready-to-use prompts from the God of Prompt library.

Keep reading

The best of the blog, in your inbox

One email when notable prompts, tools, and model updates land. No spam, unsubscribe anytime.

Join 100,000+ subscribers. One email a week, real prompts, tools, and model updates. Unsubscribe anytime.