How to Write a CLAUDE.md File for Your Codebase
A complete guide to creating effective CLAUDE.md files that make Claude Code understand your project's structure, conventions, and workflows.
Code Summary Team
Author
You're using Claude Code. You ask it to add a feature. It generates code that looks reasonable, but uses patterns your codebase doesn't follow, imports from paths that don't exist, and ignores your established conventions.
Sound familiar?
The problem isn't Claude. The problem is context. Claude doesn't know your project's structure, your team's conventions, or how you've decided to organize things. It's working blind.
The solution is a CLAUDE.md file, a simple markdown document that gives Claude persistent context about your codebase. Write it once, and Claude understands your project in every session.
Here's how to write one that actually works.
What is CLAUDE.md?
CLAUDE.md is a special file that Claude Code automatically reads when starting a session. Think of it as a project constitution, the rules and context that govern how Claude interacts with your codebase.
When you launch Claude Code in a directory, it:
- Searches for CLAUDE.md files in your project
- Loads them into its context automatically
- Follows the instructions throughout the entire session
No manual setup. No remembering to include context. Just create the file and Claude uses it.
Where to Put Your CLAUDE.md
Claude Code discovers CLAUDE.md files hierarchically, starting from your current directory and climbing up the tree:
your-project/
├── CLAUDE.md # Project-level instructions
└── .claude/
└── rules/
├── code-style.md # Modular rules by topic
├── testing.md
└── api.mdFile locations and their purposes
Project root (./CLAUDE.md): Main project instructions. This is where most of your context belongs. Checked into git, shared with your team.
Claude directory (./.claude/CLAUDE.md): Alternative location, same purpose. Some teams prefer keeping Claude configuration in a dedicated directory.
Rules directory (./.claude/rules/*.md): Modular rule files organized by topic. All markdown files here are loaded automatically. Great for large projects with many conventions.
Home directory (~/.claude/CLAUDE.md): Personal preferences that apply to all your projects. Your preferred coding style, tools you always use, personal workflow preferences.
Local file (./CLAUDE.local.md): Private project-specific preferences. Automatically added to .gitignore. Useful for personal notes you don't want to share.
Priority order
When multiple files exist, more specific locations take priority:
Home (~/.claude/CLAUDE.md)
↓ overridden by
Project root (./CLAUDE.md)
↓ overridden by
Rules directory (./.claude/rules/*.md)
↓ overridden by
Local file (./CLAUDE.local.md)For most projects, a single CLAUDE.md in the project root is enough.
What to Include
A good CLAUDE.md is concise and practical. Every line should help Claude make better decisions.
The essential sections
Here's a template that covers the most important information:
# Project Name
One-line description of what this project does.
## Tech Stack
- **Language**: TypeScript 5.3
- **Framework**: Next.js 14 (App Router)
- **Styling**: Tailwind CSS
- **Database**: PostgreSQL with Prisma
- **Testing**: Vitest + Playwright
## Project Structuresrc/ ├── app/ # Next.js App Router pages ├── components/ # React components ├── lib/ # Utilities and helpers ├── server/ # Server-side code └── types/ # TypeScript type definitions
## Code Conventions
- Use functional components with hooks
- Prefer named exports over default exports
- Use `async/await`, never raw Promises
- Error handling: throw errors, don't return null
## Commands
- `pnpm dev` - Start development server
- `pnpm build` - Production build
- `pnpm test` - Run tests
- `pnpm lint` - Run ESLint
## Testing
- Unit tests in `__tests__/` directories
- E2E tests in `e2e/` directory
- Run `pnpm test` before committing
- Minimum 80% coverage for new codeSection by section breakdown
Project description: One line explaining what the project does. Helps Claude understand the domain.
Tech stack: List your key technologies with versions. Prevents Claude from suggesting incompatible code or outdated patterns.
Project structure: Show your directory layout. Tell Claude where different types of code belong.
Code conventions: Your team's rules. Naming conventions, patterns you follow, patterns you avoid.
Commands: Common development commands. Claude can run these when appropriate.
Testing: How you test, where tests live, what coverage you expect.
What to Avoid
Less is more. Bloated CLAUDE.md files waste context and bury important information.
Don't include
Obvious information: If a folder is named components, don't explain it contains components.
Long code examples: They go stale quickly. Reference file paths instead: "See src/lib/api-client.ts for the API pattern."
Historical information: Past decisions that no longer apply. Keep it current.
Sensitive data: API keys, passwords, internal URLs. Use environment variables.
Narrative prose: Keep it scannable. Bullet points beat paragraphs.
Keep it under 500 lines
Your actual code needs context space. A 2000-line CLAUDE.md eats into the context available for understanding your code.
Aim for under 500 lines. If you need more, split into multiple files in .claude/rules/.
Real Examples
Example 1: API Backend
# User Service API
FastAPI microservice for user management and authentication.
## Tech Stack
- Python 3.11 with FastAPI
- PostgreSQL with SQLAlchemy ORM
- Redis for session cache
- pytest for testing
## Project Structuresrc/ ├── api/ # Route handlers ├── models/ # SQLAlchemy models ├── schemas/ # Pydantic schemas ├── services/ # Business logic └── repositories/ # Database access
## Conventions
- Handlers parse requests and return responses (thin)
- Services contain business logic
- Repositories handle all database access
- Use Pydantic for all request/response validation
## API Patterns
```python
# Standard response format
{"success": True, "data": {...}}
{"success": False, "error": {"code": "NOT_FOUND", "message": "..."}}Database
- Always use SQLAlchemy ORM, never raw SQL
- Migrations with Alembic in
migrations/ - Run
alembic upgrade headafter pulling
Commands
uvicorn src.main:app --reload- Dev serverpytest- Run testsalembic revision --autogenerate -m "message"- Create migration
### Example 2: React Component Library
```markdown
# Design System
Shared React component library for dashboard applications.
## Tech Stack
- React 18 with TypeScript
- Vite for building
- Tailwind CSS for styling
- Storybook for documentation
- Vitest + Testing Library for tests
## Component Structure
Each component lives in `src/components/[Name]/`:
- `Name.tsx` - Component implementation
- `Name.test.tsx` - Tests
- `Name.stories.tsx` - Storybook stories
- `index.ts` - Exports
## Conventions
- Functional components only
- Props interface named `[Name]Props`
- Use `forwardRef` for components that wrap native elements
- All interactive components need keyboard support
## Styling
- Use Tailwind utilities exclusively
- Design tokens in `tailwind.config.js`
- No inline styles, no CSS modules
- Responsive: mobile-first with `sm:`, `md:`, `lg:` breakpoints
## Testing
- Test user behavior, not implementation
- Use `getByRole`, `getByLabelText` (accessible queries)
- Every component needs at least one test
- Run `pnpm test` before committing
## Commands
- `pnpm dev` - Storybook dev server
- `pnpm build` - Build library
- `pnpm test` - Run tests
- `pnpm lint` - ESLint + Prettier checkExample 3: Monorepo
# E-Commerce Platform
Monorepo containing web app, API, and shared packages.
## Structureapps/ ├── web/ # Next.js customer frontend ├── admin/ # Next.js admin dashboard └── api/ # Node.js API server packages/ ├── ui/ # Shared React components ├── utils/ # Shared utilities └── types/ # Shared TypeScript types
## Workspaces
Using pnpm workspaces. Run commands from root:
- `pnpm --filter web dev` - Start web app
- `pnpm --filter api dev` - Start API
- `pnpm build` - Build everything
## Cross-Package Imports
```typescript
// Import shared packages
import { Button } from '@acme/ui';
import { formatCurrency } from '@acme/utils';
import type { User } from '@acme/types';Conventions
- Shared code goes in
packages/ - App-specific code stays in
apps/ - Don't import from one app to another
- Types shared across apps go in
@acme/types
Database
- Single PostgreSQL database
- API is the only database accessor
- Web and admin call API, never database directly
## Advanced Features
### Import other files with @syntax
Reference external files instead of copying content:
```markdown
# Project Instructions
## Overview
@README.md
## API Documentation
@docs/api.md
## Contributing Guidelines
@CONTRIBUTING.mdImports are resolved dynamically. When the source file changes, Claude sees the updated content.
Scope rules to specific files
In .claude/rules/, you can scope rules to specific file patterns:
---
paths:
- "src/components/**/*.tsx"
- "src/components/**/*.ts"
---
# React Component Rules
- Use functional components
- Props must have TypeScript interfaces
- Include JSDoc comments for public componentsThese rules only apply when Claude is working with matching files.
Use the # shortcut while coding
During a Claude Code session, press # followed by an instruction to add it to your CLAUDE.md:
# Always run tests before suggesting a commitThis builds your CLAUDE.md organically as you work. Over time, it captures the conventions you actually care about.
Generate a starter with /init
Run /init in Claude Code to auto-generate a CLAUDE.md based on your project:
/initClaude analyzes your codebase (package files, config, directory structure) and generates a starting point. Review it, refine it, and commit.
The Connection to AI Context
CLAUDE.md doesn't just help Claude Code. The same principles apply to other AI tools:
- Cursor uses
.cursorrulesfiles - GitHub Copilot reads from documentation and comments
- Other AI assistants benefit from clear project documentation
The information you put in CLAUDE.md (project structure, conventions, patterns) is exactly what all AI tools need to generate better code.
This is why tools like Code Summary generate AI context files automatically. They analyze your codebase and create documentation specifically structured for AI consumption. Your CLAUDE.md can reference these generated files:
## AI Context
@.agent/overview.md
@.agent/patterns.mdNow Claude has deep context about your codebase without you manually writing it.
Getting Started
You don't need a perfect CLAUDE.md on day one. Start small and iterate.
Today:
- Create a CLAUDE.md in your project root
- Add your tech stack and project structure
- Include your most important conventions (3-5 rules)
- List your common commands
This week:
- Use the
#shortcut when Claude misses a convention - Add sections as you notice gaps
- Reference key files instead of copying content
Ongoing:
- Review and prune quarterly
- Delete outdated information
- Keep it under 500 lines
Your CLAUDE.md will grow organically into a document that captures how your team actually works. And every Claude Code session will benefit from that accumulated knowledge.