Disclosure: AgentPlix may earn a commission when you sign up through our affiliate links. This never influences our recommendations — we only cover tools we'd use ourselves.
- CLAUDE.md is Claude Code's persistent memory — without it, every session starts from zero
- A well-structured CLAUDE.md can cut back-and-forth correction loops by 60% or more
- Five production-ready CLAUDE.md templates for solo devs, teams, and API projects
- The #1 mistake developers make with CLAUDE.md files (and how to avoid it)
The Best CLAUDE.md Files for Claude Code: Templates That Actually Work
If you have been using Claude Code without a CLAUDE.md file, you are leaving an enormous amount of capability on the table. The best Claude Code users treat CLAUDE.md less like documentation and more like a co-worker onboarding doc. Get it right, and Claude walks into every session already knowing your stack, your conventions, and your quirks. Get it wrong, or skip it entirely, and you are constantly re-explaining the same context.
This guide breaks down what makes the best CLAUDE.md files work, gives you five ready-to-steal templates, and explains the specific patterns that separate useful configuration files from bloated boilerplate that Claude ignores anyway.
What CLAUDE.md Actually Does (and What It Doesn’t)
Before diving into templates, it helps to understand the mechanics. Claude Code automatically reads any CLAUDE.md file it finds in:
- The project root (most common, applies to that project only)
~/.claude/CLAUDE.md(global, applies to every session across all projects)- Subdirectories (Claude picks these up when working in those directories)
When Claude Code starts, it loads the contents of CLAUDE.md as persistent context. This is not a system prompt in the API sense, but it functions similarly. You can put almost anything in here: architecture notes, coding style rules, common commands, gotchas, and explicit instructions about how you want Claude to behave.
CLAUDE.md is read fresh every session. It does not persist between sessions on its own — it IS the persistence mechanism. If you want Claude to always follow a rule, it goes in CLAUDE.md.
What it does not do: it does not give Claude live access to your codebase. Claude still needs to read files explicitly. Think of CLAUDE.md as the briefing doc your new developer reads on day one, not a live database.
The Anatomy of a Great CLAUDE.md File
The best CLAUDE.md files share a consistent structure. They are skimmable, specific, and written as if briefing a capable developer who has never seen the project before.
A high-performing CLAUDE.md typically includes:
- Project identity — what this thing is and what it does in 2-3 sentences
- Tech stack — languages, frameworks, key libraries, and versions
- Common commands — how to build, test, run, and deploy
- Architecture overview — where things live and how they connect
- Coding conventions — style rules Claude should enforce without being asked
- Known gotchas — things that have caused pain before
- Explicit behavioral rules — do this, never do that
Length matters. The sweet spot is 150-400 lines. Under 100 lines and you are probably leaving too much unsaid. Over 600 lines and Claude starts treating it as background noise rather than active instruction.
Template 1: The Solo Developer Standard
This is the best starting point for a single developer working on a web or API project. It covers the essentials without over-engineering.
# Project: [Your App Name]
## What This Is
[One sentence description.] Built with [stack]. Deployed on [platform].
## Tech Stack
- **Frontend:** Next.js 14 (App Router), TypeScript, Tailwind CSS
- **Backend:** Node.js, tRPC, Zod for validation
- **Database:** PostgreSQL via Prisma ORM
- **Auth:** Clerk
- **Infra:** Vercel (frontend), Railway (database)
## Common Commands
- `pnpm dev` — start dev server on port 3000
- `pnpm test` — run Vitest unit tests
- `pnpm db:push` — sync Prisma schema to dev DB
- `pnpm db:studio` — open Prisma Studio
- `pnpm build` — production build (check this before PRs)
## Architecture
- App routes live in `/app`
- Server components default; client components marked with `"use client"`
- All API logic in `/server/routers/`
- Shared types in `/types/`
- Environment variables validated in `/env.ts` using t3-env
## Code Style
- Functional components only — no class components
- Named exports for components, default exports for pages
- Prefer `const` arrow functions for utilities
- Error handling: always use the `AppError` class from `/lib/errors.ts`
- Do not use `any` — use `unknown` and narrow it
## Do Not
- Do not write raw SQL — use Prisma queries
- Do not import from `@/server` in client components
- Do not commit `.env.local`
- Do not use `console.log` in production paths — use the `/lib/logger.ts` wrapper
This template works because it tells Claude exactly where things live and what patterns it should follow. When you ask Claude to “add a new API endpoint,” it knows to work in /server/routers/, use Zod, and follow the existing error pattern without you spelling it out each time.
Template 2: The Team Project CLAUDE.md
When multiple developers are working on the same codebase, the CLAUDE.md needs to encode team conventions that might otherwise live only in someone’s head. This template is designed to be committed to the repo so every team member gets the same Claude behavior.
# Project: [Team App Name]
## Purpose
[What the product does and who it serves — 2-3 sentences max.]
## Team Conventions (IMPORTANT — follow these strictly)
- Branch naming: `feat/`, `fix/`, `chore/` prefixes required
- PR descriptions must include a "Testing" section
- All components go through design review before merge to main
- Feature flags live in `/config/flags.ts` — never hardcode feature state
## Tech Stack
- React 18, TypeScript 5.3, Vite
- Zustand for global state, React Query for server state
- Storybook for component development
- Playwright for E2E tests, Vitest for unit tests
- Sentry for error tracking (DSN in env vars)
## Critical Architecture Rules
1. State management: local state first, Zustand second, never Context for frequently-updated data
2. Data fetching: React Query hooks only — do not fetch in components directly
3. Styling: CSS Modules + design tokens from `/design-system/tokens.ts`
4. All external API calls go through `/api/client.ts` — this handles auth headers and error normalization
## Testing Requirements
- New features: unit tests required
- Bug fixes: regression test required
- Components: Storybook story required for any public component
- Do not delete existing tests when implementing changes
## Common Pitfalls We Have Hit
- The `useUser` hook is async — always handle the loading state
- Vite's import.meta.env is not available in Node scripts — use dotenv there
- Sentry sourcemaps upload during CI — do not manually upload
If you have a team, add a "Common Pitfalls" section to your CLAUDE.md. This is the highest-ROI section in a team project — it encodes institutional knowledge that normally lives only in Slack history.
If you have been struggling with Claude drifting from your team’s established patterns, this structure is the fix. For more on keeping Claude’s behavior consistent across sessions, see how I made my Claude setup more consistent.
Template 3: The Python / Data Science CLAUDE.md
Python projects have their own conventions and a distinct ecosystem. This template is tuned for data science, ML, and scripting projects.
# Project: [ML / Data Project Name]
## What This Does
[Description.] Python 3.11, runs locally and on Modal for heavy compute jobs.
## Environment
- Python 3.11 via pyenv
- Dependencies managed with `uv` (not pip directly)
- `uv sync` to install, `uv run python script.py` to execute
- Virtual env lives at `.venv/` — activate with `source .venv/bin/activate`
## Key Libraries
- pandas 2.x, polars for large datasets
- scikit-learn, XGBoost for modeling
- FastAPI for serving endpoints
- pydantic v2 for data validation
- ruff for linting (replaces black + flake8)
## Code Style
- Type hints on all function signatures — no exceptions
- Docstrings in Google format
- No mutable default arguments
- Prefer polars over pandas for datasets over 100K rows
## Project Structure
- `/src/` — all source code
- `/notebooks/` — exploratory work only; cleaned notebooks committed, raw ones gitignored
- `/data/raw/` — gitignored, never commit data files
- `/models/` — serialized model artifacts
## Running Things
- `make train` — run training pipeline
- `make serve` — start FastAPI dev server
- `make test` — pytest with coverage
- `make lint` — ruff check + mypy
## Never Do
- Do not use `print()` for logging — use the `logging` module with the configured logger
- Do not load entire datasets into memory — use chunked reads or polars lazy frames
- Do not hardcode file paths — use `pathlib.Path` and the config in `/src/config.py`
Template 4: The Minimal Global CLAUDE.md
This one lives at ~/.claude/CLAUDE.md and applies to every project. It should not contain project-specific details. Instead, it encodes your personal preferences as a developer so you never have to repeat them.
# My Global Preferences
## How I Work
- I prefer concise responses — skip lengthy preamble
- When you are unsure, ask one clarifying question rather than making assumptions
- If you see a better approach than what I asked for, implement what I asked and mention the alternative briefly
## Code Defaults
- TypeScript over JavaScript unless I specify otherwise
- Functional patterns over OOP where practical
- Always add error handling — never leave bare try/catch with empty catch blocks
- Prefer explicit over clever — readable code beats smart code
## Response Format
- For code: give me the full file when it is under 100 lines, otherwise give me the diff
- For explanations: bullet points over paragraphs when listing multiple things
- Do not apologize or pad responses with "Great question!" or similar
## Things I Care About
- Performance: flag obvious performance issues even if I didn't ask
- Security: call out security concerns immediately
- Tests: remind me to write tests if I have not mentioned them
A lean global CLAUDE.md like this pays off daily. It handles the micro-friction of Claude’s default verbosity and tendency to make assumptions, without interfering with project-specific configurations. This is one of the most effective ways to stop Claude from being lazy or passive in your workflow.
Template 5: The Claude API Project CLAUDE.md
If you are building with the Claude API itself, your CLAUDE.md needs to reflect that context, including how you structure prompts, which models you use, and how you handle costs.
# Project: [Claude-Powered App Name]
## What This Is
An application that uses the Anthropic Claude API to [do X]. Primary model: claude-3-5-sonnet-20241022.
## API Setup
- Anthropic Python SDK installed via `uv`
- API key in `ANTHROPIC_API_KEY` env var (never hardcode)
- Client initialized in `/src/llm/client.py` — import from there, do not re-initialize
## Model Usage Policy
- claude-3-5-sonnet-20241022 for primary user-facing tasks
- claude-3-haiku-20240307 for classification, routing, and cheap batch tasks
- claude-3-opus-20240229 for complex reasoning — used sparingly, flag usage to me
## Prompt Engineering Conventions
- System prompts live in `/src/prompts/` as `.txt` files — not hardcoded in Python
- Use f-strings with named variables for dynamic prompts, not .format()
- Always set `max_tokens` explicitly
- Include a `temperature` argument (0.0 for deterministic, 1.0 for creative)
## Cost Management
- Log token usage on every API call using the `usage` field in the response
- Batch jobs use the Batch API when >100 requests
- Cache frequently-used prompts using prompt caching headers
## Error Handling
- Wrap all API calls in the retry decorator from `/src/llm/retry.py`
- Handle `anthropic.RateLimitError` specifically — exponential backoff
- Log all API errors to Sentry with the prompt (redacted if it contains PII)
For more on building with the Claude API and how it compares to other providers, the Claude API vs OpenAI API comparison is worth reading before you commit to a stack.
What Separates Good CLAUDE.md Files From Bad Ones
Here is a comparison of the patterns that work versus the ones that waste tokens and dilute Claude’s attention:
| Pattern | Works | Doesn’t Work |
|---|---|---|
| Specificity | “Use Prisma, never raw SQL” | “Follow best practices for database access” |
| Commands | pnpm test runs Vitest |
“Run tests before committing” |
| File locations | API clients live in /lib/api/ |
“Keep things organized” |
| Explicit prohibitions | “Never use any in TypeScript” |
“Write clean code” |
| Stack versions | Next.js 14 App Router | “Modern Next.js” |
| Error patterns | “Use AppError from /lib/errors.ts” |
“Handle errors properly” |
The single biggest mistake developers make with CLAUDE.md is writing it like README documentation. Documentation explains what something is. CLAUDE.md should instruct Claude on what to do and, more importantly, what not to do.
Pros of a Well-Structured CLAUDE.md
- Claude follows your conventions without reminders
- Fewer correction loops during development
- New team members get consistent Claude behavior immediately
- Catches common mistakes before they happen
- Reduces token waste on re-explaining context
Cons and Tradeoffs
- Needs to be updated as the project evolves
- Overly long CLAUDE.md files can dilute instruction weight
- Global preferences can conflict with project-specific rules
- Does not replace good code documentation for human readers
Maintaining Your CLAUDE.md Over Time
A CLAUDE.md file is not a write-once artifact. The best setups treat it as a living document. When you notice Claude making the same mistake twice, that mistake belongs in CLAUDE.md under a “Do Not” section. When you add a major new library or change your database layer, update the stack section.
A useful practice: at the end of a long coding session, ask Claude to review what it learned about the project and suggest additions to CLAUDE.md. Claude can often surface patterns it picked up during the session that you haven’t explicitly documented yet.
For Claude Code users who also use other tools like Cursor, it’s worth knowing that Cursor has its own .cursorrules file which plays a similar role. The Cursor vs GitHub Copilot comparison gets into how these tools differ in their approach to project context.
Every time Claude does something wrong twice in a row, add a rule to CLAUDE.md. Every time it does something right automatically that you didn't ask for, that's a sign your CLAUDE.md is working.
The Global vs Project CLAUDE.md Stack
You can and should use both. Think of it as inheritance: your global ~/.claude/CLAUDE.md sets your personal defaults, and project-level CLAUDE.md files override and extend those defaults for specific codebases.
When there is a conflict, project-level instructions take precedence. This means you can set “prefer TypeScript” globally and then override it in a Python project’s CLAUDE.md without touching your global preferences.
The layered approach is especially powerful if you work across multiple clients or projects with different conventions. Your personal preferences travel with you globally; the project-specific rules stay in the repo.
A well-maintained CLAUDE.md file is the highest-leverage configuration change you can make to Claude Code — it compounds every session and pays off more as your project grows in complexity.
Start With This Today
You do not need a perfect CLAUDE.md on day one. Start with this minimal version and add to it over the next week:
# [Project Name]
## Stack
[Your main languages and frameworks]
## Run Commands
- [how to start dev]
- [how to run tests]
- [how to build]
## Most Important Rules
1. [Your #1 coding rule]
2. [Your #1 "never do this" rule]
3. [Where shared utilities live]
Ship that today, and let real sessions reveal what else needs to be there. Within a few days, you will have a CLAUDE.md that genuinely reflects how your project works, not just how you imagined it would.
For a deeper look at how behavioral instructions affect Claude’s output beyond just configuration files, what Claude says vs what Claude actually thinks is a useful read on the internal model.
Ready to level up your Claude Code setup? Start with Template 1 above and adapt it to your stack. Drop your project’s tech details in and commit it to your root directory. The difference in Claude’s behavior from the very next session will be noticeable. If you want to go deeper on customization, Cursor uses a similar configuration-driven approach and is worth benchmarking against your Claude Code workflow. Both tools run on top of Anthropic’s Claude API: if you’re building your own AI-powered dev tools or want to extend Claude Code’s capabilities programmatically, the API is your entry point.
Disclosure: This article contains affiliate and referral links to Cursor and Anthropic. We earn a commission when you sign up through these links at no cost to you.