CLAUDE.md best practices with 5 tested templates

CLAUDE.md Best Practices (2026): What to Put In, What to Leave Out, 5 Tested Templates

CLAUDE.md best practices come down to one test: write only what Claude can’t work out by reading your code. That means the commands that prove a change works, the misleading corners of the codebase, and team decisions that live nowhere in the repo. Keep it short (the official docs say under 200 lines), put hard rules in hooks or permission rules, and leave out secrets, architecture tours and anything your linter enforces.

To check this, I ran the same claude -p prompt on a small Python project with and without a CLAUDE.md. I also ran /init and used a logging hook in a sample monorepo to see when each file loads. The results and five templates are below.

Tested on: Claude Code 2.1.326, macOS (Apple Silicon), 2026-11-17. Every command below was run for this guide and the outputs are copied from that run. Drafted with AI assistance (Claude) and checked against the official docs linked in the text.

CLAUDE.md best practices in 60 seconds

  • Lead with commands: install, run one test, run all tests, type check, lint. The best-practices docs call the command that checks your work “the single most useful line” in the file.
  • Write down what the code hides: legacy patterns not to copy, env vars the tests need, decisions made in meetings.
  • Make every line checkable: “Run npm test before committing”, not “test your changes”.
  • Stay well under 200 lines. Split by folder (one CLAUDE.md per package) or by file type (.claude/rules/ with paths:).
  • Put rules with zero exceptions in hooks or permissions.deny. Capital letters don’t make a rule stick. (For Bash commands, the sandbox decides what still needs approval; see my test of the sandbox auto-allow setting.)
  • Keep personal preferences out of the team file. They go in CLAUDE.local.md or ~/.claude/CLAUDE.md.
  • Confirm the file loaded with /context all.

Where CLAUDE.md files live and how they load

Claude Code reads CLAUDE.md files from four places. This is the load order from the official memory docs, broadest scope first:

Scope Location Use it for In git?
Managed policy macOS: /Library/Application Support/ClaudeCode/CLAUDE.md
Linux/WSL: /etc/claude-code/CLAUDE.md
Windows: C:\Program Files\ClaudeCode\CLAUDE.md
Company-wide guidance from IT No (pushed out by IT, for example with MDM)
User ~/.claude/CLAUDE.md Your preferences in every project No
Project ./CLAUDE.md or ./.claude/CLAUDE.md Team rules for the repo Yes
Local ./CLAUDE.local.md Your own notes for this repo No, add it to .gitignore
  • Nothing overrides anything. All the files are joined together, with the root of the filesystem first and your working directory last. If two of them disagree, the docs say Claude “may pick one arbitrarily”.
  • Files in parent folders load at launch. Files in subfolders load on demand, when Claude reads, writes or edits a file in that subfolder.
  • It’s context, not config. Claude Code sends CLAUDE.md as a user message after the system prompt, and the docs promise “no guarantee of strict compliance”.

To check the on-demand loading, I added an InstructionsLoaded hook that logs every instruction file as it loads. The test monorepo had a root CLAUDE.md, a CLAUDE.local.md, an @docs/conventions.md import, and its own CLAUDE.md in each of packages/api and packages/web. I started at the root and asked Claude to read packages/api/app.py. The log, with paths shortened:

{"load_reason":"session_start","memory_type":"Local","file_path":".../acme/CLAUDE.local.md"}
{"load_reason":"session_start","memory_type":"Project","file_path":".../acme/CLAUDE.md"}
{"load_reason":"include","memory_type":"Project","file_path":".../acme/docs/conventions.md","parent_file_path":".../acme/CLAUDE.md"}
{"load_reason":"nested_traversal","memory_type":"Project","file_path":".../acme/packages/api/CLAUDE.md","trigger_file_path":".../acme/packages/api/app.py"}

packages/web/CLAUDE.md never loaded, because Claude never touched that folder. That’s why splitting a large monorepo file into per-package files works: the web rules cost nothing while you’re working on the API.

/init, /memory, /context and the missing # shortcut

  • /init writes a starter CLAUDE.md from your codebase. If one already exists, it suggests changes instead of overwriting it. Set CLAUDE_CODE_NEW_INIT=1 for an interactive version that also offers skills and hooks.
  • /memory lists your CLAUDE.md files, opens them in your editor and turns auto memory on or off. It’s interactive, so I didn’t test it here.
  • /context all lists every loaded instruction file and its token count. It also works as claude -p "/context all", which reported 0 turns and $0 in every one of my runs.
  • The # quick-add shortcut is gone. According to the changelog, v2.0.70 “Removed # shortcut for quick memory entry (tell Claude to edit your CLAUDE.md instead)”.

The test: same prompt, with and without CLAUDE.md

The sample project, tipcalc, has seven files. tipcalc/money.py has a cash-register rounding helper, round_half_up(), while the legacy add_tip() still uses Python’s round(). The tests refuse to run unless TIPCALC_ENV=test is set, and scripts/test.sh sets that variable:

$ python3 -m unittest discover -s tests -t .
...
RuntimeError: TIPCALC_ENV is not set
FAILED (errors=1)

This is the 15-line CLAUDE.md I wrote for it:

# tipcalc

## Commands
- Run all tests: `./scripts/test.sh`
- Run one test module: `./scripts/test.sh tests.test_core`
- Plain `pytest` or `python3 -m unittest` fails: tests need TIPCALC_ENV=test, which the script sets.

## Conventions
- Round money with `round_half_up()` from `tipcalc/money.py`. Never use built-in `round()`:
  it rounds half to even, so `round(0.125, 2)` gives 0.12 and customers get short-changed.
- `add_tip()` in `tipcalc/core.py` is legacy and still uses `round()`. Don't copy that pattern.
- Test method names: `test_<function>_<scenario>`, e.g. `test_split_bill_uneven_total`.

## Gotchas
- Standard library only (Python 3.9+). Don't add dependencies.

I ran the same prompt in two identical copies of the repo, one with this file and one without:

claude -p "Add a function split_bill(total, people) to tipcalc/core.py that returns each person's share rounded to 2 decimal places. Add a unit test for it, run the test suite, and finish with one line: the exact test command you ran." \
  --model sonnet --setting-sources project,local --strict-mcp-config \
  --no-session-persistence --permission-mode acceptEdits \
  --allowedTools "Bash" "Read" "Edit" "Write" "Glob" "Grep" --max-budget-usd 0.75

--setting-sources project,local kept my personal settings and plugins out of the runs, and using Sonnet kept the cost down.

With CLAUDE.md Without CLAUDE.md
Test command ./scripts/test.sh sh scripts/test.sh
Rounding round_half_up() round_half_up()
Before editing Opened the 3 relevant files directly 3 Bash calls (cat, ls) to find the script and helper
Tests written Uneven split (100/3 = 33.33) and the half-up case (0.25/2 = 0.13) Uneven split, even split, zero people raises
Turns / cost / time 9 / $0.060 / 13.6 s 7 / $0.060 / 14.8 s

Honestly, in a seven-file repo Claude found the test script and the rounding helper without any help. The CLAUDE.md made almost no difference to the code. What it did change was the tests: only the run that was told why round() is wrong tested the half-cent case, which is the test that would catch a regression:

    def test_split_bill_rounds_half_up(self):
        self.assertEqual(split_bill(0.25, 2), 0.13)

Both runs named their tests test_split_bill_* on their own, so my naming rule was a wasted line.

Next I added a Git rule to the CLAUDE.md copy (Commit subject: <area>: <lowercase imperative>, example money: reject negative amounts) and sent both repos “Commit the current changes.”:

with CLAUDE.md:    core: add split_bill with half-up rounding
without CLAUDE.md: Add split_bill to divide a total among people

Here the file paid off. Nothing in the repo shows the commit format, so without the file Claude used its own style. With the file, Claude also tried to run ./scripts/test.sh before committing (my allowlist for this run permitted only git, so the call was denied). The run without the file didn’t try to test at all. So a line in CLAUDE.md is worth having when it tells Claude something it can’t find in the repo.

What to put in CLAUDE.md

  1. How to confirm work: the exact test, type-check and lint commands, and how to run a single test file.
  2. Places where the code misleads: an old pattern that’s everywhere but mustn’t be copied, or a folder that looks unused but isn’t.
  3. Decisions that aren’t in the repo: which error helper the team picked, how deploys work, your commit and PR format.
  4. Anything you’ve had to correct twice.
  5. Environment gotchas: env vars the tests need, or services that have to be running.

The first four come from the best-practices page. The fifth is my addition, though the docs’ own example file includes one (“Integration tests need DATABASE_URL set”). Write rules you can check, such as “Use 2-space indentation” rather than “format code properly”. And drop IMPORTANT and ALL CAPS: the same page now lists emphasis as old advice, because current models “follow a plainly worded line” and extra emphasis “mostly makes Claude over-apply the rule”.

What to leave out of CLAUDE.md

  • Secrets. The project file is committed to git, and every CLAUDE.md that loads is sent to the model. To keep Claude out of .env, use a permissions.deny rule such as Read(./.env), which the docs say holds in every permission mode.
  • Huge style guides. A 600-line guide costs context on every task. An @ import doesn’t help, because imported files load along with the file that imports them. Use a path-scoped rule in .claude/rules/, which loads only for matching files. A skill also works, or a plain path in backticks that Claude can open when it needs the guide.
  • Stale information: renamed folders, retired commands, workarounds for older models. /doctor prompt-audit (v2.1.283+) flags references to files or commands that no longer exist, and files that contradict each other.
  • Anything a linter enforces. If ruff, ESLint or Prettier already enforces a rule, CLAUDE.md only needs the command that runs the tool. If formatting must happen after every edit, use a PostToolUse hook.
  • Architecture tours and file lists. The best-practices page lists “Describe your architecture and file layout in CLAUDE.md” as old advice, because “Claude reads the repo itself.”
  • Tool setup. You add MCP servers with claude mcp add. Describing them in CLAUDE.md doesn’t connect them. See how to add an MCP server to Claude Code.
  • Rules with zero exceptions. “Never edit migrations/” belongs in a PreToolUse hook. CLAUDE.md holds guidelines, “and Claude is allowed to decide a guideline doesn’t apply.”

How long should CLAUDE.md be?

The official target is under 200 lines per file, because longer files “consume more context and reduce adherence”. Claude Code warns you at startup and in /status when a file goes over the recommended length. There are hard limits too. A file over 4 MiB is skipped entirely, and on a 200K context window, files that load on demand get cut off after 40,000 characters.

My rule of thumb (not an official number): start under 50 lines, and if you pass 100, look for rules that belong in a rule file, a skill or a hook. My test file was 15 lines (19 after I added the Git rule). The templates below run from 9 to 30 lines.

A free trick: HTML comments are stripped before Claude sees the file. I added <!-- Maintainer note: the codeword is PELICAN. This comment should never reach Claude. --> to a root CLAUDE.md. /context all showed 88 tokens for the file whether or not the comment was there. When I asked whether PELICAN appeared anywhere in its instructions, Claude answered “No.”

/init: a good first draft, then delete lines

claude -p "/init" on a fresh copy of tipcalc took 10.5 seconds, cost $0.044 on Sonnet and wrote 16 lines (trimmed here):

## Commands
- Run all tests: `scripts/test.sh` (sets `TIPCALC_ENV=test`, then runs `unittest discover -s tests -t .`). Prefer this over calling `unittest` directly so the env var is set.

## Architecture
- `tipcalc/core.py`: tip calculation (`add_tip`), which currently uses the built-in `round`.
- `tipcalc/money.py`: `round_half_up`, a Decimal-based cash-register rounding helper (0.125 -> 0.13). ... use `round_half_up` for any money rounding.

It found the TIPCALC_ENV gotcha and the rounding rule just by reading the code. I’d delete the bullets that only describe files and add what /init can’t know, such as the commit format. The docs make the same point: after /init, “the work is mostly removing lines.”

Imports, CLAUDE.local.md and AGENTS.md

  • @path imports pull another file in. Relative paths resolve from the importing file, and imports can nest up to four hops deep. A path in backticks isn’t imported, and spaces in a path need a backslash before each one.
  • CLAUDE.local.md is still supported. It loads right after the CLAUDE.md in the same folder.
  • AGENTS.md has been read natively since v2.1.277, but by default only when there’s no CLAUDE.md or CLAUDE.local.md in your working directory or above it.
Files in my test repo What /context all listed
AGENTS.md only AGENTS.md
AGENTS.md + a separate CLAUDE.md CLAUDE.md only
CLAUDE.md starting with @AGENTS.md Both

If your team uses several coding agents, keep the shared rules in AGENTS.md and import it at the top of CLAUDE.md, with Claude-only rules below.

5 copy-paste CLAUDE.md templates

These use only documented behavior: Markdown, @ imports, HTML comments and subfolder files. The commands are examples, so swap in your own and delete any line Claude could work out from your repo. I loaded each one in Claude Code 2.1.326, and /context all listed it under Memory files with the expected type.

1. Python / FastAPI service

# orders-api (FastAPI, Python 3.12)

<!-- Template from exploreday.in. HTML comments like this one are stripped before Claude sees the file. Replace every command with your real one. -->

## Commands
- Install: `uv sync`
- Dev server: `uv run fastapi dev app/main.py`
- All tests: `uv run pytest -q`
- One test: `uv run pytest tests/test_orders.py::test_create_order -q`
- Lint and format check: `uv run ruff check . && uv run ruff format --check .`
- Type check: `uv run mypy app`
- New migration: `uv run alembic revision --autogenerate -m "<what changed>"`, then read the generated file before committing

## How to confirm a change
- Run the test file for the code you touched first, then the full suite before you say you're done.
- Tests need Postgres: `docker compose up -d db`. "Connection refused" in tests means it isn't running.

## Conventions the code doesn't make obvious
- Request and response models live in `app/schemas/`. Routes never return ORM objects.
- Services raise `AppError` subclasses from `app/errors.py`. Only routes deal with HTTP status codes.
- Use the async session from `get_session()` in `app/db.py`. `app/legacy_db.py` is sync and only serves the nightly reports job; don't copy its patterns.
- Money is `Decimal`, stored as `NUMERIC(12, 2)`. Never `float`.
- Datetimes are timezone-aware UTC.

## Don't
- Don't edit a migration that has merged to `main`. Add a new one.
- Don't add a dependency without telling me why it's needed.

## Git
- Branch: `feat/<ticket>-short-name`. Commit subject: `<area>: <imperative summary>`, e.g. `orders: validate coupon expiry`.

2. Next.js / TypeScript app

# storefront (Next.js App Router, TypeScript)

<!-- Template from exploreday.in. Replace commands and paths with your own. -->

## Commands
- Install: `pnpm install` (pnpm only; never create package-lock.json or yarn.lock)
- Dev: `pnpm dev`
- Type check: `pnpm tsc --noEmit`
- Lint: `pnpm lint`
- Unit tests: `pnpm vitest run`. One file: `pnpm vitest run src/lib/price.test.ts`
- E2E tests are slow; run `pnpm playwright test` only when I ask.

## How to confirm a change
- Run the type check and the unit test file next to the code you changed.
- For UI changes, tell me which route to open so I can check it in the browser.

## Conventions the code doesn't make obvious
- App Router only. `src/pages/` holds one legacy redirect; don't add files there.
- Server Components by default. Add `"use client"` only for state, effects or browser APIs.
- Data fetching goes through the helpers in `src/lib/api/`, which add auth headers and retries. No raw `fetch` in components.
- Server env vars are read through `src/env.ts` (validated with zod). Only `NEXT_PUBLIC_*` values may reach the browser.
- Styling is Tailwind. Shared variants live in `src/components/ui/`. Don't add new CSS files.
- Named exports for components. Default exports only where Next.js requires them (`page.tsx`, `layout.tsx`).

## Gotchas
- `pnpm build` fails when `src/env.ts` validation fails. Copy `.env.example` to `.env.local` first.
- Remote images need their host in `images.remotePatterns` in `next.config.ts`.

## Git
- Conventional commits: `feat(cart): ...`, `fix(checkout): ...`. One logical change per commit.

3. Monorepo root plus a package file

Root CLAUDE.md:

# acme monorepo (pnpm workspaces + uv)

<!-- Root file: rules that hold in every package. Each package has its own CLAUDE.md, which loads when Claude reads or edits a file in that package. -->
<!-- If you start Claude from inside a package, the @docs import below points outside the working directory and counts as an external import that needs a one-time approval. -->

Packages:
- `packages/web`: Next.js storefront
- `packages/api`: FastAPI backend
- `packages/shared`: TypeScript types generated from the API's OpenAPI spec

## Rules for every package
- Run package scripts from the package directory, not the repo root.
- Never edit files under `packages/*/generated/`. Regenerate with `pnpm codegen` from the repo root.
- A change to an API response shape needs `pnpm codegen` and the matching change in `packages/web` in the same PR.
- CI runs `pnpm -r test` and `uv run --directory packages/api pytest`. Both must pass.

## Decisions that live outside the code
- Architecture decisions are in `docs/adr/`. Read the relevant ADR before you change auth, billing or data retention.
- Shared API conventions (naming, pagination, error shape): @docs/api-conventions.md

## Git
- Commit subject: `<package>: <summary>`, e.g. `api: add rate limiting`.
- One package per commit unless the change is a codegen round trip.

packages/api/CLAUDE.md:

# packages/api

<!-- Save as packages/api/CLAUDE.md. It loads at launch if you start Claude in packages/api, or on demand when Claude touches a file here from the repo root. -->

- Setup: copy `.env.example` to `.env` first. Tests and the dev server fail without it.
- Tests: `uv run pytest -q` from `packages/api`. One test: `uv run pytest tests/test_users.py::test_signup -q`
- Queries use SQLAlchemy 2.0 `select()` style. No raw SQL strings in route handlers.
- Never edit a migration after it has merged. Add a new one.
- After you change a response model, run `pnpm codegen` from the repo root and commit the generated types.

4. Personal ~/.claude/CLAUDE.md

I didn’t touch my real user file. I pointed CLAUDE_CONFIG_DIR at a throwaway folder, and /context all listed the template as type “User”. If you keep notes in Obsidian, this file is a good place to tell Claude where your vault lives (see connecting Claude Code to Obsidian).

# Personal preferences (every project)

<!-- Save as ~/.claude/CLAUDE.md. It loads in every project, before the project's own CLAUDE.md. Files don't override each other, so keep anything a project might contradict out of this file. -->

## About me
- Backend developer. Strong in Python and Go, weaker in TypeScript and CSS: explain frontend changes in a bit more detail.
- I review diffs in the terminal, so keep unrelated reformatting out of them.

## How to work with me
- Ask before anything that deploys, pushes, publishes, or deletes data outside the repo.
- If a request is ambiguous, ask one short question instead of guessing.
- For changes that touch more than 3 files, show a short plan first.
- When you finish, tell me what changed, how you checked it, and anything I still need to do.

## Code preferences (when the project has no rule of its own)
- Small functions, early returns, no clever one-liners.
- Comments explain why, not what.
- Don't add a dependency without telling me why.

## My machine
- macOS, zsh, Homebrew. Use BSD-compatible flags (`sed -i ''`, not `sed -i`).
- Python: use `uv` unless the repo already uses pip or Poetry.
- Node: use `pnpm` unless the repo has a `package-lock.json` or `yarn.lock`.
- `gh` is installed and logged in for GitHub work.

## Writing
- Plain English, short sentences, no marketing words.
- Dates in docs as YYYY-MM-DD.

5. Docs or writing repo

# product docs (MkDocs Material)

<!-- Template from exploreday.in. The full style guide stays in docs/STYLE.md as a plain pointer, not an @import, so it doesn't load into every session. -->

## Commands
- Preview: `mkdocs serve` (http://127.0.0.1:8000)
- Build exactly like CI: `mkdocs build --strict` (warnings, such as broken internal links, fail the build)
- Prose lint: `vale docs/`. Fix errors; warnings are judgment calls.

## Before you call a page done
- `mkdocs build --strict` passes.
- New pages are listed under `nav:` in `mkdocs.yml`.
- Every command, setting name and UI label was checked against the product, or marked `<!-- TODO: verify -->`.

## Audience and voice (what Vale doesn't check)
- Readers are admins setting up the product for a team. They know DNS and SSO basics.
- Second person, present tense, active voice. Sentence-case headings.
- The first paragraph says what the reader will have done by the end of the page.
- One procedure per page. Numbered steps start with a verb and hold one action each.
- UI labels in **bold**, spelled exactly as on screen. Code, paths and values in backticks.
- Don't promise roadmap items or dates. Don't write "simply", "just" or "easy".

## Structure
- Pages live in `docs/<area>/`. Screenshots go in `docs/<area>/img/` as PNG.
- Reused text lives in `docs/_snippets/` and is pulled in with `--8<--`. Edit the snippet, not the copies.
- When you move a page, add a redirect under the `redirects` plugin's `redirect_maps` in `mkdocs.yml`.
- Full house style guide: `docs/STYLE.md`. Read it before writing a new page from scratch.

CLAUDE.md checklist

  • It opens with exact commands: install, test one file, test all, type-check, lint.
  • You could tell whether Claude followed each rule.
  • Nothing describes what Claude can see by opening the files.
  • No secrets or internal URLs you wouldn’t commit.
  • Nothing your linter, formatter or CI already enforces.
  • Rules with no exceptions are hooks or deny rules.
  • Under 200 lines (the docs’ limit). Under 50 is better (my rule of thumb).
  • /context all lists it under Memory files.

What didn’t work / gotchas

  • In a small repo, CLAUDE.md barely matters for facts Claude can find on its own. Don’t pad the file to look thorough.
  • Root imports vanished when I started inside a package. From packages/api, /context all listed both CLAUDE.md files but not the root’s @docs/... import. The docs say an import that resolves outside your working directory counts as “external” and needs a one-time approval. In print mode there was no approval dialog, so the import simply didn’t load. Start Claude from the root, or approve the import once in an interactive session.
  • Your allowlist can block your own CLAUDE.md. Claude tried the test command from the file, but --allowedTools "Bash(git *)" denied it.
  • A CLAUDE.local.md stops Claude from reading AGENTS.md. This comes from the docs; I didn’t test it. To read both, set Project instructions in /config to claude-md-and-agents-md.
  • Old advice is everywhere. The # shortcut is gone, and Anthropic’s original engineering post on Claude Code best practices now returns a 308 redirect to the docs page. That page lists “add IMPORTANT or ALL CAPS” as advice to drop.

FAQ

Where should CLAUDE.md be located?

Team rules go in CLAUDE.md or .claude/CLAUDE.md at the repo root, committed to git. Put personal rules for all projects in ~/.claude/CLAUDE.md, and personal rules for one repo in a gitignored CLAUDE.local.md. Rules for one package go in that package’s folder.

Does Claude Code read AGENTS.md?

Yes, from v2.1.277, but by default only when there’s no CLAUDE.md. To use both files, import @AGENTS.md from your CLAUDE.md or change Project instructions in /config.

Is CLAUDE.local.md deprecated?

No. The current docs list it as the “Local instructions” scope, and in my test it loaded at session start as type “Local”.

How do I know Claude is using my CLAUDE.md?

Run /context all and check the Memory files list. Subfolder files only show up after they load on demand. To see exactly when each file loads, log it with an InstructionsLoaded hook.

Can I still press # to add a memory?

No, it was removed in v2.0.70. Ask Claude to “add this to CLAUDE.md”, or edit the file through /memory. If you ask Claude to “remember” something, it saves the note to auto memory instead.

Sources

Similar Posts