Skip to content

How to Write CLAUDE.md: The Complete Guide to Project Context Files for AI Coding

The Problem: What Led to This Question

Every Claude Code session started the same way. I’d open my project, describe what I wanted, and watch Claude make decisions that contradicted what I’d asked for in previous sessions.

The Session Amnesia Pattern
Session 1: "Use functional components with hooks"
Session 2: Claude creates class components
Me: "I told you to use functional components"
Session 2: "Sorry, I'll fix that"
Session 3: Claude uses class components again
Me: "Why are you using class components?"
Session 3: "I don't have context from previous sessions"

This wasn’t just about component style. The same problems repeated across every aspect of development:

Problems Without CLAUDE.md
Session Amnesia: Claude forgets decisions from last session
Style Drift: Code style changes unpredictably between files
Architecture Confusion: Claude doesn't understand the project structure
Workflow Gaps: Claude skips steps I always want performed
Repetitive Explanations: I explain the same preferences over and over

I found a Reddit thread where developers shared the same frustration. One comment stood out: “What changed everything for me was writing really detailed CLAUDE.md specs with architecture decisions and constraints.”

The key insight: A CLAUDE.md file serializes your project’s architecture decisions, coding preferences, and workflows into persistent context that Claude Code reads every session.

The Solution: Comprehensive CLAUDE.md Configuration

Core Structure of a CLAUDE.md

A comprehensive CLAUDE.md has distinct sections, each serving a specific purpose:

CLAUDE.md Structure Overview
# Project Overview
[Brief description of what this project does]
# Architecture Decisions
[Decisions that affect all code]
# Coding Standards
[Style rules and patterns]
# Development Workflow
[How to develop, test, and release]
# Constraints
[Hard limits that must never be violated]
# Agent Instructions
[How Claude should behave in this project]

Each section is optional but recommended for complex projects. The more specific you are, the less Claude has to guess.

What to Include (Priority Order)

Not all sections are equally important. Here’s the priority order based on what provides the most value:

PrioritySectionImpactExample Content
1Architecture DecisionsHighTech stack, patterns, folder structure
2ConstraintsHighFile size limits, no CDN, immutability rules
3Workflow StepsMediumTest requirements, commit conventions
4Code PatternsMediumAPI response format, error handling
5Agent InstructionsMediumTrigger-action rules, behavior modifiers
6Project OverviewLowBrief description, context

Architecture decisions and constraints have the highest impact because they affect every line of code Claude writes. Start with these.

Minimal CLAUDE.md vs Comprehensive CLAUDE.md

Here’s what most people write (and why it fails):

Minimal CLAUDE.md (NOT ENOUGH)
# Project Instructions
This is a Flask blog management app.
Use clean code practices.
Write tests for everything.

This file is too vague. “Clean code” is subjective. “Tests for everything” doesn’t specify coverage thresholds or test types. The architecture decisions are missing entirely.

Here’s what actually works:

Comprehensive CLAUDE.md (WHAT WORKS)
# Blog Management App
## Architecture Decisions
### Tech Stack
- Backend: Python Flask with SQLAlchemy ORM
- Frontend: HTML + Alpine.js + Tailwind (local assets, no CDN)
- Database: PostgreSQL
- Intelligence: LangGraph + MCP servers
### Folder Structure
/backend
/models # SQLAlchemy models
/routes # Flask blueprints
/services # Business logic
/repositories # Database access layer
/frontend
/static # CSS, JS (no CDN)
/templates # Jinja2 templates
/mcp_servers # MCP server implementations
### Patterns
- Repository pattern for all database access
- Service layer for business logic
- API responses follow standard format
## Constraints
### Hard Limits
- Maximum 400 lines per file
- No remote CDN dependencies
- No direct database queries in routes
- All user input must be validated with Zod schemas
### Style Rules
- Use immutable patterns (no mutation)
- Functions under 50 lines
- No nesting deeper than 4 levels
- No console.log in production code
## Development Workflow
### Test Requirements
- Minimum 80% coverage
- Unit tests for utilities and services
- Integration tests for routes
- E2E tests for critical user flows
### Commit Conventions
- Format: `<type>: <description>`
- Types: feat, fix, refactor, docs, test, chore
- Create new commits, never amend existing
## Code Patterns
### API Response Format
{
"success": boolean,
"data": T | null,
"error": string | null,
"meta": { total, page, limit } | null
}
### Error Handling Pattern
try {
result = await riskyOperation()
return result
} catch (error) {
console.error('Operation failed:', error)
throw new Error('User-friendly message')
}
## Agent Instructions
### Before Making Changes
1. Read CLAUDE.md
2. Check existing patterns in codebase
3. Verify constraints are satisfied
### When Implementing Features
1. Create tests first
2. Implement minimum to pass tests
3. Refactor within constraints
4. Verify coverage >= 80%

The comprehensive version eliminates ambiguity. Claude knows exactly what patterns to use, what limits to respect, and what workflow to follow.

Why This Matters

The difference between minimal and comprehensive CLAUDE.md is dramatic:

Without vs With Comprehensive CLAUDE.md
WITHOUT COMPREHENSIVE CLAUDE.MD:
─────────────────────────────────────────────────────────────────────
Session 1:
Me: "Create a user model"
Claude: [Creates class-based model, no validation, no tests]
Session 2:
Me: "Add a post model"
Claude: [Creates functional model, missing repository pattern]
Session 3:
Me: "Fix the user model to match the post model style"
Claude: "I don't have context from Session 1"
Result: Inconsistent codebase, wasted time re-explaining
WITH COMPREHENSIVE CLAUDE.MD:
─────────────────────────────────────────────────────────────────────
Session 1:
Me: "Create a user model"
Claude: [Reads CLAUDE.md]
Claude: [Creates repository pattern model with validation, tests]
Session 2:
Me: "Add a post model"
Claude: [Reads CLAUDE.md]
Claude: [Creates matching repository pattern, consistent style]
Session 3:
Me: "Fix the user model"
Claude: [Reads CLAUDE.md, sees pattern]
Claude: "User model already matches the repository pattern specified"
Result: Consistent codebase, no repeated explanations

The Reddit thread confirmed this pattern: “CLAUDE.md helps maintain context and consistent decisions across large codebase.”

Common Mistakes

MistakeWhy It FailsHow to Fix
Vague descriptions”Clean code” is subjectiveSpecify exact rules: “Functions under 50 lines”
Missing architectureClaude makes inconsistent decisionsDocument tech stack, patterns, folder structure
No constraintsClaude violates project limitsList hard limits: “Max 400 lines per file”
Copy-paste rulesRules don’t match project needsWrite rules specific to your project
No workflowClaude skips important stepsDefine test, commit, and release workflows
Forgetting patternsClaude reinvents patterns each timeDocument API formats, error handling patterns
Not updating CLAUDE.mdRules become staleUpdate when architecture changes

CLAUDE.md Hierarchy

CLAUDE.md files can exist at multiple levels, each with different scope:

CLAUDE.md Hierarchy Diagram
┌─────────────────────────────────────────────────────────────────────┐
│ ~/.claude/CLAUDE.md │
│ (Global Rules) │
│ │
│ Applies to: ALL projects │
│ Contains: General preferences, safety rules, global patterns │
│ Example: "Never commit secrets", "Always validate inputs" │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ project/CLAUDE.md │
│ (Project Rules) │
│ │
│ Applies to: THIS project only │
│ Contains: Architecture, tech stack, constraints, patterns │
│ Example: "Use Flask + SQLAlchemy", "Repository pattern required" │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ project/.claude/rules/ │
│ (Specialized Rules) │
│ │
│ coding-style.md → Style conventions │
│ testing.md → Test requirements │
│ git-workflow.md → Commit conventions, PR process │
│ security.md → Security checks │
│ performance.md → Performance guidelines │
│ │
│ These are imported by main CLAUDE.md for organization │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ project/.claude/skills/ │
│ (Reusable Skills) │
│ │
│ planner.md → Implementation planning │
│ code-reviewer.md → Code review specialist │
│ tdd-guide.md → Test-driven development guide │
│ │
│ Skills can be invoked as needed for specific tasks │
└─────────────────────────────────────────────────────────────────────┘

Resolution Order:

When Claude Code starts, it reads files in this order:

  1. ~/.claude/CLAUDE.md (global rules)
  2. project/CLAUDE.md (project rules, overrides global)
  3. project/.claude/rules/*.md (specialized rules, referenced by CLAUDE.md)

This hierarchy allows you to have consistent global preferences while customizing per project.

Practical Example: Starting Fresh

When I start a new project, I create CLAUDE.md before writing any code:

New Project CLAUDE.md Template
# [Project Name]
## Architecture Decisions
### Tech Stack
[Specify exact versions and libraries]
### Patterns
[Document architectural patterns]
## Constraints
[Hard limits that must never be violated]
## Workflow
### Development
[How to develop features]
### Testing
[Testing requirements]
### Commits
[Commit message format and rules]
## Code Patterns
[Reusable patterns for this project]

I fill in each section before asking Claude to write code. This investment pays off immediately:

ROI of CLAUDE.md Investment
Time spent writing CLAUDE.md: 30 minutes
Time saved per session: 10 minutes (no re-explaining)
Number of sessions: 50+
Total time saved: 500+ minutes (8+ hours)
Break-even: After just 3 sessions

Summary

A comprehensive CLAUDE.md file transforms Claude Code from a forgetful assistant into a consistent team member. The key principles:

  1. Be specific: “Functions under 50 lines” instead of “write clean code”
  2. Document architecture: Tech stack, patterns, folder structure
  3. Define constraints: Hard limits that Claude must respect
  4. Specify workflow: Test, commit, and release procedures
  5. Show patterns: Code examples for common operations
  6. Update regularly: Keep CLAUDE.md in sync with project evolution

As one Reddit user put it: “Tell Claude about project architecture, code styles, dev/test/release workflows explicitly with CLAUDE.md.” Each of your coding preferences should be serialized to CLAUDE.md.

Final Words + More Resources

My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!

Comments