Back to Claude Code
Claude CodeIntermediate10 min read

CLAUDE.md Mastery — Your Project's AI Brain

How to write an effective CLAUDE.md that transforms Claude Code from a generic assistant into a project-aware expert

claude-mdconfigurationproject-setup

Official References: Claude Code Overview · CLAUDE.md Guide · Configuration

Curriculum path

  1. CLAUDE.md Mastery — repo memory, conventions, architecture ← You are here
  2. Effective Prompting — communicate tasks clearly
  3. MCP Power Tools — connect tools and data
  4. Multi-Agent Workflows — delegate and parallelize
  5. Hooks Automation — automate guardrails locally
  6. GitHub Actions Workflows — move repeatable work into team automation

Official docs used in this guide

Why CLAUDE.md Matters

CLAUDE.md is the single most impactful file you can create for Claude Code. It's automatically loaded into every conversation, giving Claude persistent context about your project.

Think of it as the difference between hiring a contractor who reads your project wiki vs. one who walks in blind.

The Anatomy of a Great CLAUDE.md

1. Project Context (What)

# MyProject
 
A real-time analytics dashboard built with Next.js 16 and PostgreSQL.
Monorepo with turborepo: apps/web, apps/api, packages/shared.

Keep it factual. Claude can read your code — don't repeat what's obvious from package.json.

2. Conventions (How)

## Conventions
- Use kebab-case for file names, PascalCase for components
- All API routes return `{ data, error }` shape
- Tests co-located: `foo.ts``foo.test.ts`
- Commits follow Conventional Commits

This is where most people under-invest. Every convention you document saves Claude from guessing wrong.

3. Architecture Decisions (Why)

## Architecture Decisions
- Using Server Components by default, 'use client' only for interactivity
- PostgreSQL over MongoDB — relational data with complex joins
- No ORM — raw SQL with typed queries via pgtyped

The "why" prevents Claude from suggesting alternatives you've already evaluated and rejected.

4. Forbidden Patterns (Don't)

## Don't
- Don't use `any` type — use `unknown` and narrow
- Don't add barrel exports (index.ts re-exports)
- Don't mock database in tests — use test containers

Negative instructions are powerful. Claude respects explicit boundaries.

Pro Tips

Layer Your CLAUDE.md Files

Claude Code supports CLAUDE.md files at multiple levels:

  • Root: Project-wide rules
  • Subdirectory: Domain-specific context (e.g., apps/api/CLAUDE.md)
project/
├── CLAUDE.md              # Global conventions
├── apps/
│   ├── web/CLAUDE.md      # Frontend-specific
│   └── api/CLAUDE.md      # Backend-specific
└── packages/
    └── shared/CLAUDE.md   # Shared library rules

Keep It Under 200 Lines

Long CLAUDE.md files dilute important context. If you need more detail, link to docs:

## API Design
Follow our API style guide: see `docs/api-style.md`

Version Control It

CLAUDE.md should be committed. It's a shared team resource — when one engineer discovers a pattern that helps Claude, everyone benefits.

Common Mistakes

Mistake Why It Hurts Fix
Too vague ("write clean code") Doesn't constrain behavior Be specific: "max 20 lines per function"
Too long (500+ lines) Context dilution Prioritize, link to docs
Not updated Stale rules confuse Claude Review monthly
Duplicating package.json Wastes context tokens Only add what's not obvious

Team Collaboration Patterns

CLAUDE.md isn't just a personal productivity tool — it's team infrastructure. A well-maintained CLAUDE.md aligns how the entire team uses AI, consistently.

Onboarding automation When a new teammate opens Claude Code on day one, CLAUDE.md already carries the project context. They spend less time asking "how is this project structured?" and more time contributing.

Consistent AI output across the team Without CLAUDE.md, each developer gets slightly different code from Claude — one uses any types, another doesn't. CLAUDE.md eliminates that drift by making conventions explicit and shared.

Fewer "why did Claude do this?" moments in PR review If that question keeps coming up in code review, it's a signal that the relevant convention is missing from CLAUDE.md. Add it when you find the gap, and review friction drops over time.

Starter Template

If you're writing your first CLAUDE.md, copy this and adapt it to your project:

# [Project Name]
 
[One-line description: what it does, what technologies it uses]
 
## Conventions
- [File naming rule, e.g. kebab-case]
- [Code style, e.g. max 20 lines per function]
- [Testing rule, e.g. co-locate test files with source]
 
## Architecture
- [Key technical decision and why]
- [Alternatives you considered and rejected]
 
## Don't
- [Forbidden pattern 1]
- [Forbidden pattern 2]
 
## Common Commands
- Test: `npm test`
- Build: `npm run build`
- Lint: `npm run lint`

Advanced Patterns

Conditional Instructions

You can apply different rules depending on what kind of file is being edited:

## Context-Specific Rules
- When editing frontend files: Tailwind CSS classes only, no inline styles
- When editing API routes: always include error handling, return typed responses
- When editing test files: use describe/it pattern, descriptive test names

Claude knows the path of the file it's working on, so conditional instructions like these work naturally.

External Document Reference Pattern

Don't try to put everything into CLAUDE.md. Keep it lean by referencing separate files for details:

## Reference Docs
- API design principles: see `docs/api-style.md`
- Database schema: see `docs/schema.md`
- Deployment procedure: see `docs/deploy.md`

Claude reads those files only when relevant. This keeps CLAUDE.md short while making detailed context always accessible.

How to Evolve Your CLAUDE.md Over Time

It doesn't need to be perfect from the start. Starting small is actually the right approach:

  1. Start minimal: Begin with 5–10 lines — a one-sentence project description and 2–3 core conventions
  2. Add rules when Claude gets it wrong: When Claude generates something unexpected, add the missing convention right then
  3. Monthly review: Once a month, scan for rules that are now obvious or no longer relevant — remove them
  4. The "why did Claude do that?" test: If you can't explain Claude's reasoning, that reasoning belongs in CLAUDE.md

The .claude/ Directory (Going Deeper)

Beyond CLAUDE.md, the entire .claude/ directory is your project's AI configuration space:

  • .claude/settings.json — project-wide settings, committed to version control
  • .claude/settings.local.json — personal settings and API keys (add to .gitignore)
  • .claude/commands/ — define custom slash commands for your team

For example, create .claude/commands/review.md and every team member can run /review to trigger the same code review workflow. If CLAUDE.md defines "what Claude should know," .claude/ defines "how Claude should behave."

Settings Hierarchy

Claude Code has a four-tier settings priority system. Higher tiers override lower ones:

Priority Level Location Managed By
1 (highest) Enterprise Policy Org admin dashboard IT / Security team
2 User Settings ~/.claude/settings.json Individual
3 Project Settings .claude/settings.json Team (committed to git)
4 (lowest) Local Settings .claude/settings.local.json Individual (gitignored)

Here's how a real team might use each level:

// Enterprise Policy — set by org admins, cannot be overridden
{
  "disallowedTools": ["Bash"],        // Block Bash execution for security
  "blockedCommands": ["rm -rf"]       // Block dangerous commands
}
 
// User Settings (~/.claude/settings.json) — personal global preferences
{
  "preferredModel": "sonnet",         // Default model preference
  "mcpServers": {
    "my-notes": { "command": "notes-mcp" }  // Personal MCP server
  }
}
 
// Project Settings (.claude/settings.json) — shared, git-tracked
{
  "allowedTools": ["Read", "Write", "Edit", "Bash"],
  "hooks": {
    "PreToolUse": [{ "matcher": "Write", "command": "lint-check.sh" }]
  }
}
 
// Local Settings (.claude/settings.local.json) — personal, gitignored
{
  "env": {
    "API_KEY": "sk-local-dev-key-..."   // Personal API key
  }
}

The key takeaway: put team rules in Project Settings, personal environment in Local Settings. If your org has Enterprise Policy, security settings cannot be bypassed by individuals.

Custom Slash Commands Deep Dive

The .claude/commands/ directory lets you create team-specific slash commands. The process is straightforward:

  1. Create a markdown file in .claude/commands/
  2. The filename becomes the command name (e.g., review.md/project:review)
  3. The file content becomes the prompt template sent to Claude
  4. Use the $ARGUMENTS placeholder to accept user input

Example 1: Code Review

<!-- .claude/commands/review.md -->
Review the following file against our team code standards: $ARGUMENTS
 
Checklist:
- Type safety: check for `any` usage
- Error handling: all async functions have try/catch
- Tests: new functions have corresponding tests
- Naming: kebab-case filenames, PascalCase components
 
Suggest fix code for each issue found.

Usage: /project:review src/api/users.ts

Example 2: Database Migration Checklist

<!-- .claude/commands/migrate.md -->
Review the following database migration: $ARGUMENTS
 
Verify:
- Is the migration reversible?
- Are lock times minimized for large tables?
- Are index additions using CONCURRENTLY?
- Is backward compatibility with existing data maintained?

Example 3: Pre-Deployment Verification

<!-- .claude/commands/deploy-check.md -->
Run pre-deployment verification:
 
1. Verify build succeeds (`npm run build`)
2. Verify tests pass (`npm test`)
3. Check for missing env vars against `.env.example`
4. Check for pending migrations
5. Verify CHANGELOG.md is updated

Usage: /project:deploy-check

Commit your custom commands to git. The entire team gets access to the same workflows.

CLAUDE.md Performance Tips

Every line in CLAUDE.md consumes context tokens in every conversation. Here's how to manage it efficiently:

Hide Metadata with HTML Comments

HTML comments (<!-- -->) are hidden from Claude Code's auto-injection but still visible via the Read tool:

# MyProject
 
<!-- version: 2.1.0 -->
<!-- last-review: 2026-03-15 -->
<!-- agent-count: 12 -->
 
Real-time analytics dashboard built with Next.js 16.

Use HTML comments for metadata, checksums, and validation tags to save tokens.

Separate Reference Docs

Don't put everything in CLAUDE.md. Move detailed content to separate files and reference them:

## API Design
Follow our API style guide: see `docs/api-style.md`

Claude reads referenced files when they become relevant. This keeps CLAUDE.md lightweight while keeping deep context accessible.

Token Budget Awareness

Practical rules:

  • Target under 200 lines — beyond this, context dilution starts
  • Don't repeat what's already in package.json or tsconfig.json
  • Review CLAUDE.md regularly and remove rules that are no longer needed
  • Keep only actionable instructions — move background explanations to separate docs

Monorepo CLAUDE.md Strategy

In a monorepo, a three-tier CLAUDE.md hierarchy works powerfully:

monorepo/
├── CLAUDE.md                    # Level 1: Org-wide conventions
├── apps/
│   ├── web/
│   │   └── CLAUDE.md            # Level 2: Frontend rules
│   ├── api/
│   │   └── CLAUDE.md            # Level 2: Backend rules
│   └── mobile/
│       └── CLAUDE.md            # Level 2: Mobile rules
└── packages/
    ├── shared/
    │   └── CLAUDE.md            # Level 3: Shared package rules
    └── ui/
        └── CLAUDE.md            # Level 3: UI package rules

Level 1: Root CLAUDE.md (Org-Wide)

# MyCompany Monorepo
 
Turborepo monorepo. All packages use TypeScript strict mode.
 
## Shared Conventions
- Conventional Commits required
- PRs must include tests
- Shared types defined in `packages/shared/types/`

Level 2: App-Level CLAUDE.md

# apps/web
 
Next.js 16 frontend. Uses App Router.
 
## Rules
- Server Components by default, 'use client' only for interactivity
- Styles: Tailwind CSS only
- Deployment: Vercel (preview branches auto-deploy)

Level 3: Package-Level CLAUDE.md

# packages/shared
 
Shared utilities and types used across multiple apps.
 
## API Contract
- All exports must have JSDoc documentation
- Breaking changes require major version bump
- Apps consuming this package: web, api, mobile

Key tip: Subdirectory CLAUDE.md files are only loaded when Claude works in that directory. Put domain-specific rules at levels 2 and 3, and keep shared conventions at the root.

Connection: GPT Codex Comparison

GPT Codex uses AGENTS.md and codex.md for similar purposes, but with key differences:

  • Codex reads instructions once at task start (no live reload)
  • Codex runs in a sandbox — file path conventions matter more
  • See the Codex Instructions Guide for details

Connected Guides