CLAUDE.md: The Complete Guide to Configuring Claude Code

CLAUDE.md is the single file that determines whether Claude Code understands your project or starts from scratch every session. This guide covers file locations, what to include, templates for 4 project types, @imports, skills, /init, and how CLAUDE.md compares to .cursorrules.

March 4, 2026 · 2 min read

What CLAUDE.md Does

Every Claude Code session starts stateless. Claude has no memory of your project between conversations. CLAUDE.md bridges that gap. It loads into Claude's system prompt before your first message, giving it the context that code alone cannot communicate.

Build commands, naming conventions, architectural constraints, testing requirements, deployment quirks. Your codebase might follow conventions that Claude cannot infer from reading files. Maybe you use a custom ORM wrapper instead of raw SQL. Maybe your tests must run with a specific flag. Maybe there is a legacy module that should never be modified. CLAUDE.md is where those rules live.

200
Max recommended lines for reliable adherence
5
@import recursion depth limit
~50
Built-in system prompt instructions (leaves ~150 for you)

Without CLAUDE.md, you explain the same things every session. With it, Claude knows your project from the first message. Anthropic's official docs put it plainly: “CLAUDE.md is loaded every session, so only include things that apply broadly.”

Key Insight

CLAUDE.md survives compaction. When Claude's context window fills up and /compact runs, CLAUDE.md is re-read from disk and re-injected fresh. Instructions you type in chat do not survive compaction. This is the single strongest reason to put important rules in CLAUDE.md rather than repeating them in conversation.

File Locations: Global vs. Project vs. Local

Claude Code reads CLAUDE.md files from multiple locations. Each serves a different purpose. Understanding the hierarchy prevents conflicts and keeps your configuration clean.

LocationScopeVersion Control?
~/.claude/CLAUDE.mdAll projects, all machinesNo (personal)
./CLAUDE.md (project root)This project, all team membersYes (commit it)
./CLAUDE.local.mdThis project, just youNo (auto-gitignored)
Parent directoriesMonorepo: root + packageDepends on location
SubdirectoriesOn-demand when Claude reads that directoryDepends on location
/Library/Application Support/ClaudeCode/CLAUDE.mdManaged policy (org-wide, macOS)Managed by IT

The Global File

~/.claude/CLAUDE.md applies to every project on your machine. Put preferences here that you want everywhere: your preferred commit message format, your editor keybindings reference, your timezone convention, or a reminder to always run tests before committing.

~/.claude/CLAUDE.md (global)

# Personal Preferences

- Always run tests before committing
- Use conventional commits: feat:, fix:, chore:, docs:
- Prefer bun over npm when both are available
- TypeScript strict mode in all projects

The Project File

./CLAUDE.md at the project root is the main configuration. Commit it to version control. When a new team member clones the repo and runs Claude Code, they get the same context as everyone else.

The Local File

./CLAUDE.local.md is for personal project-specific preferences that should not be committed. Claude Code automatically adds it to .gitignore. Use it for things like “I prefer verbose test output” or “always explain your reasoning to me” that would not make sense for other team members.

Monorepo Hierarchy

In a monorepo, Claude walks up the directory tree from your working directory and loads every CLAUDE.md it finds. If you run Claude Code from packages/web/, it loads both root/CLAUDE.md and packages/web/CLAUDE.md. Subdirectory CLAUDE.md files below your working directory load on demand when Claude reads files there.

Monorepo structure

monorepo/
├── CLAUDE.md                  # Org-wide standards (loaded at launch)
├── packages/
│   ├── api/
│   │   ├── CLAUDE.md          # API-specific rules (loaded if CWD is api/)
│   │   └── src/
│   └── web/
│       ├── CLAUDE.md          # Web-specific rules (loaded if CWD is web/)
│       └── src/
└── .claude/
    └── rules/
        ├── testing.md         # Loaded at launch (no path filter)
        └── api-routes.md      # path: "src/api/**" — on demand

What to Include in CLAUDE.md

For each line in your CLAUDE.md, ask: “Would removing this cause Claude to make mistakes?” If the answer is no, cut it. The goal is maximum signal per line. Here are the categories that earn their place.

Build and Run Commands

Commands Claude cannot guess from package.json alone. Dev server ports, seed scripts, migration commands, environment-specific flags.

Code Conventions

Rules that differ from defaults. 'Use ES modules, not CommonJS.' 'Named exports only.' 'No default exports.' Things Claude would get wrong without guidance.

Testing Rules

Preferred test runner, how to run a single test, whether to mock or not, minimum coverage expectations. 'Run single tests for speed, not the full suite.'

Architectural Decisions

Patterns specific to your project. 'All API routes return { data, error }.' 'Use the UserService wrapper, never raw DB queries.' 'Auth is handled by middleware, not per-route.'

Repository Etiquette

Branch naming conventions, PR requirements, commit message format. 'Always create feature branches.' 'Squash merge only.'

Gotchas and Warnings

Non-obvious behaviors that cause bugs. 'The payments module uses legacy callbacks, not promises.' 'Never modify files in /generated — they are auto-generated.'

A practical CLAUDE.md (48 lines)

# Project: Invoice API

FastAPI REST API for invoice management. Python 3.12, PostgreSQL, Redis.

## Commands

- `uv run dev`: Start dev server (port 8000)
- `uv run test`: Run pytest suite
- `uv run test -k "test_name"`: Run single test
- `uv run lint`: Ruff check + format
- `uv run migrate`: Alembic migrations

## Code Style

- Type hints on all function signatures
- Use Pydantic v2 models for request/response
- Named exports from __init__.py, no star imports
- Async handlers by default

## Architecture

- /app/api/        → Route handlers (thin, delegate to services)
- /app/services/   → Business logic
- /app/models/     → SQLAlchemy models
- /app/schemas/    → Pydantic schemas
- /app/core/       → Config, deps, middleware

## Rules

- Handlers must not contain business logic. Delegate to services.
- All DB access through repository pattern in /app/repositories/
- Never use raw SQL. Use SQLAlchemy ORM.
- Redis is for caching only, not primary storage.
- All endpoints return { data, error, meta } shape.

## Testing

- Use pytest-asyncio for async tests
- Factory Boy for test data, not fixtures
- No mocking DB — use test database
- Run single tests during development, full suite before PR

## Gotchas

- The legacy billing module (/app/legacy/) uses sync code. Do not convert to async.
- Invoice PDFs are generated by a background worker, not the API handler.
- NEVER commit .env files. Use .env.example for reference.

What NOT to Include

Every unnecessary line dilutes the instructions that matter. Bloated CLAUDE.md files cause Claude to ignore your actual rules because they get lost in the noise.

IncludeExcludeWhy
Build commandsObvious commandsClaude can read package.json. Only add commands it cannot guess.
Non-default code styleStandard language conventionsClaude already knows PEP 8 and Prettier defaults.
Architecture constraintsFull API documentationLink to docs instead of embedding them.
Testing preferencesSelf-evident practices'Write clean code' wastes a line. Claude already tries to.
Project-specific gotchasInformation that changes oftenStale instructions are worse than no instructions.
Workflow rulesFile-by-file descriptionsClaude can read the directory structure itself.

Never Send an LLM to Do a Linter's Job

Code style rules like “use 2-space indentation” or “sort imports alphabetically” do not belong in CLAUDE.md. LLMs are comparatively expensive and unreliable at enforcing formatting rules. Use a linter (ESLint, Ruff, Biome) and configure a Claude Code hook to run it after every file edit. The hook is deterministic. CLAUDE.md instructions are advisory.

Hook instead of CLAUDE.md rule

// .claude/settings.json — runs ESLint after every file edit
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx eslint --fix $CLAUDE_FILE_PATH 2>/dev/null || true"
      }
    ]
  }
}

CLAUDE.md Templates

Four templates for common project types. Copy the one closest to your stack, then edit. Delete any lines that do not apply. A smaller, accurate file beats a comprehensive, generic one.

Next.js / React / TypeScript

CLAUDE.md — Next.js project

# Project: [Name]

Next.js 15 App Router, React 19, TypeScript, Tailwind CSS, Drizzle ORM.

## Commands

- `bun run dev`: Dev server (port 3000)
- `bun run build`: Production build
- `bun run test`: Vitest suite
- `bun run db:push`: Push Drizzle schema changes
- `bun run db:studio`: Open Drizzle Studio
- `bun run lint`: Next.js ESLint

## Code Style

- Server Components by default. Client components only for interactivity.
- Use ES modules (import/export), not CommonJS (require)
- Destructure imports: import { foo } from 'bar'
- No default exports except page.tsx and layout.tsx

## Architecture

- /src/app/          → App Router pages and layouts
- /src/components/   → Reusable React components
- /src/lib/          → Utilities, DB client, helpers
- /src/lib/db/       → Drizzle schema and migrations
- /src/actions/      → Server actions

## Rules

- Mutations through server actions, not API routes
- All DB access through Drizzle ORM in server components/actions
- Tailwind for styling. No CSS modules.
- Typecheck before committing: bun run typecheck

## Testing

- Vitest for unit tests, Playwright for e2e
- Run single tests during dev: bunx vitest run src/path/to/test.ts
- No mocking DB — use test database

Python / FastAPI

CLAUDE.md — Python FastAPI project

# Project: [Name]

FastAPI, Python 3.12, PostgreSQL, SQLAlchemy 2.0, Alembic, uv.

## Commands

- `uv run dev`: Dev server (port 8000)
- `uv run test`: pytest with asyncio
- `uv run test -k "test_name"`: Single test
- `uv run lint`: Ruff check + format
- `uv run migrate`: Run Alembic migrations

## Code Style

- Type hints on all functions
- Async handlers by default
- Pydantic v2 for all request/response models
- No star imports

## Architecture

- /app/api/v1/       → Route handlers (thin, delegate to services)
- /app/services/     → Business logic
- /app/models/       → SQLAlchemy models
- /app/schemas/      → Pydantic schemas
- /app/repositories/ → Data access layer

## Rules

- Handlers delegate to services. No business logic in routes.
- All DB access through repositories. No raw SQL.
- Return { data, error } shape from all endpoints.
- Use dependency injection for DB sessions.

Rust / Cargo

CLAUDE.md — Rust project

# Project: [Name]

Rust, Cargo workspace, Tokio async runtime, SQLx for database.

## Commands

- `cargo build`: Compile
- `cargo test`: Run all tests
- `cargo test test_name`: Single test
- `cargo clippy`: Lint
- `cargo fmt`: Format
- `cargo run --bin server`: Start server

## Code Style

- Use thiserror for error types, anyhow for application errors
- Prefer &str over String in function parameters
- Derive Clone, Debug on all public structs
- No unwrap() in production code. Use ? operator.

## Architecture

- /crates/core/    → Domain logic, no IO
- /crates/server/  → HTTP handlers (axum)
- /crates/db/      → SQLx queries and migrations
- /crates/cli/     → CLI binary

## Rules

- Core crate must not depend on server or db crates
- All async code uses tokio. No mixing runtimes.
- Database queries in /crates/db/ only. Never in handlers.
- Run clippy before committing. Zero warnings policy.

Monorepo (Turborepo / Nx)

CLAUDE.md — Monorepo root

# Monorepo: [Name]

Turborepo, pnpm workspaces. Frontend (Next.js) + API (Node/Express) + shared packages.

## Commands

- `pnpm dev`: Start all services
- `pnpm build`: Build all packages
- `pnpm test`: Run all tests
- `pnpm lint`: Lint all packages
- `turbo run test --filter=@app/api`: Test single package

## Structure

- /apps/web/       → Next.js frontend
- /apps/api/       → Express API server
- /packages/ui/    → Shared React components
- /packages/db/    → Drizzle schema, shared across apps
- /packages/types/ → Shared TypeScript types

## Rules

- Shared types go in @app/types. Never duplicate type definitions.
- UI components in @app/ui must be framework-agnostic.
- API changes require updating the OpenAPI spec in /docs/api.yaml.
- Each package has its own CLAUDE.md for package-specific context.

## Cross-Package

- Import shared packages by name: import { Button } from '@app/ui'
- Never use relative paths across package boundaries.
- DB schema changes require running migrations in both dev and test.

CLAUDE.md vs .cursorrules vs copilot-instructions.md

Three tools, three configuration formats. They serve similar purposes but differ in scope, loading behavior, and feature depth.

FeatureCLAUDE.md.cursorrulescopilot-instructions.md
ToolClaude CodeCursorGitHub Copilot
File formatMarkdownMarkdown / plain textMarkdown
LoadingHierarchical (global + project + subdirectory)Single file per projectSingle file per repo
Imports@path/to/file (5 levels deep)No importsNo imports
Path-scoped rules.claude/rules/ with glob patterns.cursor/rules/ with glob patternsNo
Best forMulti-file autonomous tasks, subagentsIDE-based editing, completionsOrg-wide baseline behavior
Local overridesCLAUDE.local.md (auto-gitignored)Not built-inNot built-in
Skills / commands.claude/skills/ and /commands/.cursor/ commandsNo
Hooks integrationPre/post tool hooks in settings.jsonNo hooksNo hooks

CLAUDE.md has the richest feature set: hierarchical loading, @imports, path-scoped rules, local overrides, and hooks integration. Cursor's .cursorrules is simpler but tightly integrated with IDE-based editing workflows. GitHub Copilot's .github/copilot-instructions.md is designed for org-wide standards across repos.

If you use multiple tools, do not copy the same rules file across formats. Each tool interprets instructions differently. Create one canonical standards document, then adapt it for each tool's format.

AGENTS.md

AGENTS.md is a cross-tool open standard adopted by OpenAI Codex, Cursor, GitHub Copilot, and Gemini CLI. Claude Code also reads AGENTS.md files. It uses a flat file model (one file per directory, 32 KiB cap) without the hierarchy and import features of CLAUDE.md. If you need one file that works across tools, AGENTS.md is the lowest common denominator. For Claude Code specifically, CLAUDE.md gives you more control.

@imports, Skills, and Custom Commands

@imports

CLAUDE.md files can reference other files with @path/to/file syntax. This keeps your root file lean while organizing detailed guidance into focused documents.

Using @imports in CLAUDE.md

# Project: MyApp

See @README.md for project overview.
See @docs/api-patterns.md for API conventions.
See @docs/testing-guide.md for test structure.

## Commands
- bun run dev
- bun run test

## Rules
- Git workflow: @docs/git-workflow.md
- Database patterns: @docs/db-patterns.md

Imports resolve recursively up to 5 levels deep. Use relative paths from the CLAUDE.md file's location. Referenced files load into Claude's context alongside the main CLAUDE.md content.

The .claude/rules/ Directory

For larger projects, split instructions across files in .claude/rules/. Rules without a paths frontmatter field load at session start. Rules with a paths field load on demand when Claude reads files matching the glob.

.claude/rules/react-components.md

---
paths:
  - "src/components/**/*.tsx"
  - "src/components/**/*.ts"
---

# React Component Rules

- All components use named exports
- Props interfaces named [Component]Props
- Use forwardRef for components that accept refs
- Colocate tests: Button.tsx → Button.test.tsx

Skills

Skills extend Claude's knowledge with reusable workflows and domain knowledge. Unlike CLAUDE.md, skills load on demand rather than every session. Create them in .claude/skills/.

.claude/skills/deploy/SKILL.md

---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
---

Deploy the application: $ARGUMENTS

1. Run the test suite: bun run test
2. Build for production: bun run build
3. Check for TypeScript errors: bun run typecheck
4. If all pass, deploy: bun run deploy
5. Verify the deployment is healthy: curl https://myapp.com/health

Invoke with /deploy staging. Skills with disable-model-invocation: true only run when you trigger them manually, preventing Claude from auto-invoking workflows with side effects.

Custom Commands

Store repetitive prompts as markdown files in .claude/commands/ for reuse as slash commands. These are simpler than skills, designed for prompt shortcuts.

.claude/commands/review.md

Review the current git diff for:
- Security vulnerabilities (injection, XSS, auth issues)
- Performance problems (N+1 queries, missing indexes)
- Logic errors and edge cases
- Consistency with existing patterns

Provide specific line references and suggested fixes.

Run /review in Claude Code to execute the prompt. Commands do not support $ARGUMENTS or YAML frontmatter.

The /init Command

The fastest way to start is /init. Run it inside Claude Code and it analyzes your codebase: package files, build configuration, test frameworks, directory structure, existing documentation. It generates a starter CLAUDE.md tailored to your project.

Using /init

$ cd your-project
$ claude
> /init

# Claude analyzes:
# - package.json / Cargo.toml / pyproject.toml
# - Existing README, docs, config files
# - Directory structure and code patterns
# - Build system and test framework
#
# Generates a CLAUDE.md in your project root

Treat the output as a starting point, not a finished product. The generated file tends to be too verbose. Go through it line by line and delete anything Claude can figure out from code alone. The best CLAUDE.md files are written through deletion, not addition.

The Deletion Rule

Start with /init output and subtract. Remove every line where Claude would do the right thing anyway. What remains is your CLAUDE.md: the rules Claude needs that it cannot infer.

Iterating Over Time

CLAUDE.md is not a one-time setup. When Claude makes a mistake that a CLAUDE.md rule would have prevented, add the rule. When Claude consistently does something correctly without a rule, remove the redundant instruction. Review your CLAUDE.md periodically the same way you review code. Some teams add “update CLAUDE.md” to their PR checklist.

Common Mistakes

The Kitchen Sink

A 400-line CLAUDE.md with every possible rule. Claude ignores half of it because important rules get lost in the noise. Fix: cut to under 200 lines. Use @imports for details.

Linting via LLM

Putting formatting rules in CLAUDE.md instead of using a linter. LLMs are slow and unreliable at enforcing indentation. Fix: use a linter + a Claude Code hook.

Stale Instructions

CLAUDE.md references patterns, files, or tools that no longer exist. Claude follows the outdated instructions and produces wrong code. Fix: review CLAUDE.md with every major refactor.

Code Snippets

Embedding code examples that become outdated. Fix: use @file:line references that point Claude to the authoritative source in your codebase.

Duplicate Instructions

The same rule appears in CLAUDE.md and in .claude/rules/ and in conversation. Claude gets confused about precedence. Fix: single source of truth.

Ignoring /init

Writing CLAUDE.md from scratch instead of starting with /init. Fix: always start with /init and subtract. It detects patterns you would forget to include.

FAQ

Can I use emphasis to make Claude follow a rule more strictly?

Yes. Adding “IMPORTANT” or “YOU MUST” before a rule improves adherence. Use this sparingly. If every rule is “IMPORTANT,” none of them are.

Is the filename case-sensitive?

Yes. It must be CLAUDE.md with uppercase CLAUDE. claude.md will not be detected.

Can teammates have different CLAUDE.md preferences?

Yes. The project CLAUDE.md is shared via version control. Each developer can add personal preferences to CLAUDE.local.md (auto-gitignored) or their global ~/.claude/CLAUDE.md.

How does CLAUDE.md relate to AGENTS.md?

AGENTS.md is a cross-tool standard that Claude Code also reads. If you have both, Claude loads both. CLAUDE.md takes precedence for Claude-specific configuration. Use AGENTS.md for instructions that should apply across Codex, Cursor, Copilot, and Claude Code. Use CLAUDE.md for Claude-specific features like @imports, skills, and hooks.

What happens if CLAUDE.md contradicts itself?

Claude uses its judgment to resolve conflicts. More specific rules tend to win over general ones. If you see inconsistent behavior, check for contradictions between your global file, project file, and any .claude/rules/ files.

How do I know if my CLAUDE.md is working?

Two signals. First, Claude stops asking questions that are answered in your file. Second, Claude follows your conventions without being reminded. If either fails, the file is either too long (rules get lost) or the phrasing is ambiguous.

Can Claude write its own CLAUDE.md updates?

Yes. Claude Code has an auto-memory system that writes to ~/.claude/projects/.../memory/MEMORY.md. This is separate from CLAUDE.md. You can also ask Claude to suggest additions to your CLAUDE.md based on patterns it discovers, then review and commit them yourself.

Build Faster with Claude Code + Morph

Morph accelerates Claude Code with subagent-native search. Your CLAUDE.md rules apply across all agents.