Introduction
CLAUDE.md is Claude Code's context engineering system. It lets you tell Claude about your project - the architecture, conventions, constraints, and preferences that should guide its work.
Context Engineering: The practice of crafting the right information to give an LLM so it can perform tasks effectively. CLAUDE.md is a structured approach to context engineering for coding agents.
What is CLAUDE.md
CLAUDE.md is a markdown file that Claude Code reads automatically. It contains instructions, guidelines, and context that shape how Claude works on your project.
Why CLAUDE.md?
- Persistent: Instructions stay across sessions
- Version controlled: Lives in your repo with your code
- Shareable: Team members get the same context
- Hierarchical: Different levels for different scopes
Without vs With CLAUDE.md
📝comparison.txt
1Without CLAUDE.md:
2$ claude "Add a new API endpoint"
3→ Creates endpoint in random location
4→ Uses different naming conventions
5→ Forgets to add tests
6→ Uses deprecated patterns
7
8With CLAUDE.md:
9$ claude "Add a new API endpoint"
10→ Creates endpoint in src/api/routes/
11→ Follows camelCase naming convention
12→ Creates test in tests/api/
13→ Uses current auth middleware patternThe CLAUDE.md Hierarchy
CLAUDE.md files can exist at multiple levels, with more specific files taking precedence:
📝hierarchy.txt
1Priority (highest to lowest):
2
31. ~/.claude/CLAUDE.md # Personal global preferences
42. ~/CLAUDE.md # Home directory defaults
53. ./CLAUDE.md # Project root (most common)
64. ./src/CLAUDE.md # Subdirectory-specific
75. ./src/components/CLAUDE.md # Even more specificUse Cases for Each Level
| Level | Location | Use Case |
|---|---|---|
| Global | ~/.claude/CLAUDE.md | Personal preferences, API keys patterns |
| Home | ~/CLAUDE.md | Default coding style, common tools |
| Project | ./CLAUDE.md | Project architecture, conventions, constraints |
| Subdirectory | ./src/api/CLAUDE.md | Specific module patterns |
Start at Project Level
Most projects only need one CLAUDE.md at the project root. Only add subdirectory files if you have significantly different patterns in different areas.
Effective Structure
A well-structured CLAUDE.md has distinct sections:
📝CLAUDE.md
1# Project Guidelines for Claude
2
3## Overview
4Brief description of what this project is and does.
5
6## Architecture
7How the codebase is organized:
8- /src/api - API routes and handlers
9- /src/components - React components
10- /src/utils - Utility functions
11- /tests - Test files
12
13## Tech Stack
14- Next.js 14 with App Router
15- TypeScript strict mode
16- Prisma ORM with PostgreSQL
17- Tailwind CSS for styling
18
19## Code Conventions
20- Use functional components with hooks
21- Prefer named exports over default exports
22- camelCase for variables and functions
23- PascalCase for components and types
24- Keep files under 300 lines
25
26## Testing Requirements
27- All new features need tests
28- Use React Testing Library, not Enzyme
29- Tests go in __tests__ folder next to source
30- Run: npm test
31
32## What NOT to Do
33- Never modify /generated directory
34- Don't use any CSS-in-JS libraries
35- Don't add new dependencies without asking
36- Never commit .env files
37
38## Common Tasks
39### Adding a new API route:
401. Create handler in src/api/routes/
412. Add types in src/types/api.ts
423. Create test in tests/api/
434. Update API documentation
44
45### Creating a new component:
461. Create in src/components/
472. Add stories in src/stories/
483. Export from src/components/index.tsReal-World Examples
Backend API Project
📝api_project_claude.md
1# Backend API Guidelines
2
3## Authentication
4All endpoints except /health and /auth/* require JWT authentication.
5Use the withAuth middleware from src/middleware/auth.ts
6
7## Database
8- Use Prisma for all database operations
9- Never write raw SQL
10- Migrations: npx prisma migrate dev
11
12## Error Handling
13Always use the ApiError class from src/errors.ts:
14```typescript
15throw new ApiError(404, 'Resource not found');
16```
17
18## Response Format
19All responses follow this structure:
20```json
21{
22 "success": true,
23 "data": { ... },
24 "error": null
25}
26```
27
28## Validation
29Use zod for request validation:
30```typescript
31const schema = z.object({
32 email: z.string().email(),
33 password: z.string().min(8),
34});
35```React Component Library
📝component_library_claude.md
1# Component Library Guidelines
2
3## Component Structure
4Every component follows this pattern:
5```
6src/components/ComponentName/
7 index.ts # Re-export
8 ComponentName.tsx # Main component
9 ComponentName.types.ts # Types
10 ComponentName.stories.tsx # Storybook
11 ComponentName.test.tsx # Tests
12```
13
14## Props Naming
15- isX for boolean states: isOpen, isLoading
16- onX for callbacks: onClick, onSubmit
17- xProps for forwarded props: buttonProps, inputProps
18
19## Styling
20Use Tailwind with cn() helper for conditional classes:
21```tsx
22className={cn(
23 "base-classes",
24 variant === "primary" && "primary-classes",
25 disabled && "opacity-50"
26)}
27```
28
29## Accessibility
30- All interactive elements need aria labels
31- Support keyboard navigation
32- Test with screen readersBest Practices
1. Be Specific, Not General
📝specific_vs_general.md
1# ❌ Too general:
2Write good code and follow best practices.
3
4# ✅ Specific:
5- Use TypeScript strict mode (all flags enabled)
6- Functions should be under 50 lines
7- Extract complex logic into utility functions
8- Name booleans with is/has/should prefixes2. Include Examples
📝include_examples.md
1# Creating API routes
2
3Follow this pattern for all new routes:
4
5```typescript
6// src/api/routes/users.ts
7import { Router } from 'express';
8import { withAuth } from '../middleware/auth';
9import { validate } from '../middleware/validate';
10import { createUserSchema } from '../schemas/user';
11
12const router = Router();
13
14router.post('/',
15 withAuth,
16 validate(createUserSchema),
17 async (req, res) => {
18 // Handler logic
19 }
20);
21
22export default router;
23```3. Explain Why, Not Just What
📝explain_why.md
1# ❌ Just what:
2Don't use class components.
3
4# ✅ What and why:
5Don't use class components because:
6- The codebase uses hooks exclusively
7- Class components don't work with our state management
8- We want consistency for code reviews4. Keep It Updated
- Review CLAUDE.md when conventions change
- Add new patterns as they emerge
- Remove outdated guidance
- Include it in code review discussions
5. Don't Overdo It
CLAUDE.md isn't documentation. Keep it focused on what Claude needs to know to work effectively:
- Include: Architecture, conventions, constraints, common patterns
- Exclude: Detailed API docs, user guides, historical context
Balance is Key
Too little context leads to inconsistent code. Too much context wastes tokens and can confuse the model. Aim for essential information only.
Summary
CLAUDE.md context engineering:
- What: Markdown file with project context for Claude
- Where: Hierarchical - global, home, project, subdirectory
- Structure: Overview, architecture, conventions, examples
- Best practices: Be specific, include examples, explain why
- Maintain: Keep updated as project evolves
Next: Let's explore the feedback loop pattern that lets Claude Code learn from its actions and improve over time.