·SuperBuilder Team

What is CLAUDE.md and How to Write One That Actually Works

claude codeclaude.mdbest practicesconfigurationdeveloper tools

What is CLAUDE.md and How to Write One That Actually Works

CLAUDE.md Best Practices Hero
CLAUDE.md Best Practices Hero

You installed Claude Code. You ran a few prompts. The results were... fine. Maybe it suggested installing a package you already have. Maybe it used CommonJS when your whole project is ESM. Maybe it wrote tests in Mocha when you use Vitest.

The problem is not Claude Code. The problem is that Claude Code knows nothing about your project until you tell it.

That is what CLAUDE.md is for. It is a plain markdown file that sits in your repository root and gives Claude Code the context it needs to work effectively in your specific codebase. Think of it as onboarding documentation -- not for a new hire, but for an AI that can read your entire codebase in seconds but still needs to know the unwritten rules.

This guide covers everything: what CLAUDE.md is, how to structure one that actually works, real examples for different project types, mistakes to avoid, and how to iterate on it over time.

Table of Contents


What is CLAUDE.md?

CLAUDE.md is a configuration file for Claude Code -- Anthropic's AI coding agent that runs in your terminal. When Claude Code starts a session in a directory, it automatically reads the CLAUDE.md file at the project root to understand your codebase conventions, architecture, and preferences.

It is not a rigid configuration format. There is no schema, no required fields, no validation. It is plain markdown. You write whatever context would help an intelligent agent work more effectively in your project.

Here is a minimal example:

# Project: Invoice API

Node.js REST API using Express + TypeScript + Prisma.

## Commands
- `npm run dev` -- start dev server on port 3001
- `npm test` -- run Vitest tests
- `npm run lint` -- ESLint + Prettier check

## Conventions
- All API routes go in `src/routes/`
- Business logic goes in `src/services/`, not in route handlers
- Use Zod for request validation
- Tests live next to source files (`*.test.ts`)

That is 12 lines. It takes two minutes to write. And it prevents dozens of wrong assumptions.

CLAUDE.md file in a code editor
CLAUDE.md file in a code editor

Where CLAUDE.md Files Live

Claude Code reads CLAUDE.md files from multiple locations, merged in order of precedence:

  1. ~/.claude/CLAUDE.md -- Global preferences that apply to all projects (your personal coding style, preferred tools)
  2. CLAUDE.md in the project root -- Project-level conventions shared by the team
  3. CLAUDE.md in subdirectories -- Scoped instructions for specific parts of a monorepo or codebase

This layered approach means you can set global defaults and override them per project or per directory.


Why CLAUDE.md Matters More Than You Think

Claude Code is powerful. It can read files, run commands, edit code, and execute multi-step plans. But power without context leads to plausible-looking code that misses the mark.

Without a CLAUDE.md, Claude Code will:

With a well-written CLAUDE.md, Claude Code becomes a team member who actually read the onboarding docs. It follows your patterns, uses your preferred libraries, and understands the architecture.

The difference is dramatic. Teams that maintain a good CLAUDE.md report that Claude Code gets things right on the first try 2-3x more often compared to prompting without one.


Anatomy of a Good CLAUDE.md

After reviewing hundreds of CLAUDE.md files from open-source projects and our own users, a clear structure emerges. The best files share these sections:

1. Project Overview (2-3 lines)

State what the project is and the core technology stack. Be specific about versions when it matters.

# SuperWidget

React 19 + TypeScript dashboard app. Vite 6 for builds, Tailwind CSS v4 for styling. 
Deployed on Vercel. Monorepo managed with Turborepo.

2. Key Commands

List the commands a developer (or AI) needs to build, test, lint, and run the project. This is the single highest-value section because it prevents Claude Code from guessing.

## Commands
- `pnpm dev` -- start dev server
- `pnpm test` -- run all Vitest tests
- `pnpm test:e2e` -- Playwright end-to-end tests
- `pnpm lint` -- ESLint check
- `pnpm typecheck` -- TypeScript strict check
- `pnpm db:migrate` -- run Drizzle migrations
- `pnpm db:generate` -- regenerate Drizzle schema types

3. Architecture and File Layout

Describe where things live. This saves Claude Code from scanning your entire tree to understand the structure.

## Architecture
- `src/app/` -- Next.js App Router pages and layouts
- `src/components/` -- Shared React components
- `src/lib/` -- Utility functions and shared logic
- `src/server/` -- Server-only code (API routes, DB queries)
- `src/server/routers/` -- tRPC router definitions
- `prisma/schema.prisma` -- Database schema (PostgreSQL)

4. Coding Conventions

This is where you encode the unwritten rules. The things a new team member learns in their first week.

## Conventions
- Use named exports, not default exports
- Prefer `interface` over `type` for object shapes
- Error handling: wrap async route handlers in `tryCatch()` from `src/lib/utils`
- All database access goes through `src/server/db/` -- never import Prisma client directly in components
- CSS: use Tailwind utility classes, no custom CSS files except `globals.css`
- Imports: use `@/` path alias (maps to `src/`)

5. Important Constraints

Things Claude Code should never do, or must always do.

## Important
- NEVER modify `src/generated/` -- these files are auto-generated by `pnpm db:generate`
- NEVER use `any` type -- use `unknown` and narrow with type guards
- Always add Zod validation for new API endpoints
- Run `pnpm typecheck` after making changes to verify no type errors
- This project uses strict TypeScript -- no implicit any, no unused variables

6. Testing Patterns

If your testing setup has specific conventions, spell them out.

## Testing
- Unit tests use Vitest with `@testing-library/react`
- Test files: `__tests__/ComponentName.test.tsx` (co-located)
- Mock API calls with MSW (Mock Service Worker), not jest.mock
- E2E tests in `tests/e2e/` using Playwright
- Run single test: `pnpm test -- --run src/path/to/test.test.ts`

Anatomy of a good CLAUDE.md file
Anatomy of a good CLAUDE.md file


Real Examples by Project Type

Theory is fine, but you need something you can copy and adapt. Here are five CLAUDE.md files for common project types, based on patterns from real-world projects.

Example 1: React + TypeScript App

# TaskFlow

React 19 + TypeScript task management app. Vite 6 for bundling, Zustand for state, 
React Query v5 for server state. Deployed on Vercel.

## Commands
- `npm run dev` -- start dev server (port 5173)
- `npm test` -- Vitest in watch mode
- `npm run test:run` -- single Vitest run (CI)
- `npm run build` -- production build
- `npm run lint` -- ESLint + Prettier

## Architecture
- `src/components/` -- UI components, grouped by feature
- `src/hooks/` -- custom React hooks
- `src/stores/` -- Zustand stores (one per domain: tasks, auth, ui)
- `src/api/` -- React Query hooks wrapping API calls
- `src/lib/` -- pure utility functions
- `src/types/` -- shared TypeScript interfaces

## Conventions
- Components: function declarations, not arrow functions
- State: Zustand for client state, React Query for server state. Never use useState for data from the API.
- Styling: Tailwind CSS utility classes. No CSS modules, no styled-components.
- Routing: React Router v7 with lazy-loaded routes in `src/routes.tsx`
- All API calls go through `src/api/client.ts` (configured Axios instance with auth interceptor)

## Important
- NEVER put business logic in components -- extract to hooks or stores
- All new components must have a corresponding `.test.tsx` file
- Use `cn()` utility from `src/lib/utils.ts` for conditional class merging

Example 2: Python API (FastAPI)

# Nexus API

FastAPI backend for the Nexus platform. Python 3.12, async-first. 
PostgreSQL + SQLAlchemy 2.0 (async). Redis for caching.

## Commands
- `uv run fastapi dev` -- start dev server with hot reload
- `uv run pytest` -- run all tests
- `uv run pytest -x -k "test_name"` -- run single test, stop on failure
- `uv run ruff check .` -- lint
- `uv run ruff format .` -- format
- `uv run alembic upgrade head` -- run migrations
- `uv run alembic revision --autogenerate -m "description"` -- create migration

## Architecture
- `app/api/routes/` -- FastAPI routers (one file per resource)
- `app/models/` -- SQLAlchemy ORM models
- `app/schemas/` -- Pydantic request/response schemas
- `app/services/` -- business logic layer
- `app/repositories/` -- database query layer (no raw SQL in services)
- `app/core/` -- config, security, dependencies
- `tests/` -- mirrors `app/` structure, uses pytest-asyncio

## Conventions
- All endpoints return Pydantic models, never raw dicts
- Use dependency injection for DB sessions: `db: AsyncSession = Depends(get_db)`
- Repository pattern: services call repositories, never use `db.execute()` directly
- Error handling: raise `HTTPException` in routes only, use custom exceptions in services
- Naming: snake_case everywhere, plural resource names in URLs (`/api/v1/users`)

## Important
- NEVER use synchronous database calls -- everything is async
- NEVER commit `.env` -- use `.env.example` for documentation
- Run `ruff check` and `ruff format` before considering any change complete
- All new endpoints need tests in `tests/api/`

Example 3: Monorepo (Turborepo)

# CloudStack

Turborepo monorepo. pnpm workspaces.

## Packages
- `apps/web` -- Next.js 15 marketing site
- `apps/dashboard` -- Next.js 15 app (App Router, RSC-first)
- `apps/api` -- Hono.js API server on Cloudflare Workers
- `packages/ui` -- shared component library (React + Tailwind)
- `packages/db` -- Drizzle ORM schema + migrations (shared)
- `packages/auth` -- authentication utilities (shared)
- `packages/config-eslint` -- ESLint config
- `packages/config-ts` -- shared tsconfig bases

## Commands (from root)
- `pnpm dev` -- start all apps in parallel
- `pnpm build` -- build all packages and apps
- `pnpm lint` -- lint all packages
- `pnpm test` -- test all packages
- `pnpm dev --filter=dashboard` -- start only dashboard

## Conventions
- Import shared packages with `@cloudstack/ui`, `@cloudstack/db`, etc.
- New shared code goes in `packages/`, not duplicated across apps
- Each package has its own `tsconfig.json` extending `packages/config-ts`
- Database changes: modify `packages/db/schema.ts`, then `pnpm db:generate`

## Important
- NEVER install dependencies in the root -- always in the specific package
- NEVER import between apps directly -- extract shared code to a package
- When modifying `packages/ui`, verify both `apps/web` and `apps/dashboard` still build
- The `apps/api` package uses Hono, NOT Express or Fastify

Example 4: CLI Tool (Go)

# bolt CLI

Command-line tool for managing cloud deployments. Go 1.23, Cobra for commands, 
Bubble Tea for TUI components. Distributed as single binary.

## Commands
- `go build -o bolt ./cmd/bolt` -- build binary
- `go test ./...` -- run all tests
- `go test -v ./internal/deploy/...` -- test specific package
- `golangci-lint run` -- lint
- `goreleaser release --snapshot` -- test release build

## Architecture
- `cmd/bolt/` -- entrypoint, Cobra root command
- `cmd/bolt/commands/` -- one file per CLI command (deploy, logs, config, etc.)
- `internal/` -- core logic, not exported
- `internal/deploy/` -- deployment orchestration
- `internal/config/` -- YAML config file parsing
- `internal/api/` -- HTTP client for cloud API
- `pkg/` -- reusable packages safe for external import

## Conventions
- Errors: wrap with `fmt.Errorf("action: %w", err)` for context chains
- CLI output: use `internal/ui` package (wraps lipgloss styles), never raw fmt.Println for user-facing output
- Config: Viper for config file + env vars, Cobra for flags
- HTTP: standard library `net/http`, no third-party HTTP clients
- Tests: table-driven tests, use `testify/assert` for assertions

## Important
- NEVER use `os.Exit()` outside of `cmd/bolt/main.go`
- All user-facing strings must go through the `ui` package for consistent formatting
- Support both `--json` flag (machine output) and human-readable output for all commands
- Minimum Go version is 1.23 -- use range-over-func and other 1.23 features freely

Example 5: Mobile App (React Native)

# FitTrack

React Native 0.76 fitness tracking app. Expo SDK 52, TypeScript.
iOS and Android. Expo Router for navigation.

## Commands
- `npx expo start` -- start Expo dev server
- `npx expo run:ios` -- run on iOS simulator
- `npx expo run:android` -- run on Android emulator
- `npm test` -- Jest + React Native Testing Library
- `npm run lint` -- ESLint
- `npm run typecheck` -- tsc --noEmit
- `eas build --profile preview` -- create preview build

## Architecture
- `app/` -- Expo Router file-based routes
- `app/(tabs)/` -- bottom tab navigator screens
- `app/(auth)/` -- authentication flow screens
- `components/` -- shared components
- `hooks/` -- custom hooks
- `stores/` -- Zustand stores
- `services/` -- API layer (wrapping fetch, auth headers)
- `constants/` -- theme colors, sizes, config values

## Conventions
- Navigation: Expo Router file-based routing. Never use React Navigation directly.
- Styling: StyleSheet.create, organized by component. No NativeWind in this project.
- Platform checks: use `Platform.select()` not `Platform.OS === 'ios'`
- Animations: Reanimated 3 for performance-critical, LayoutAnimation for simple cases
- Storage: MMKV for key-value, SQLite (expo-sqlite) for structured data

## Important
- NEVER use `AsyncStorage` -- we use MMKV for all local storage
- Test on BOTH iOS and Android before marking changes complete
- All health data access goes through `services/health.ts` (wraps HealthKit/Health Connect)
- Expo Config Plugin modifications go in `plugins/` directory

CLAUDE.md examples for different project types
CLAUDE.md examples for different project types


Anti-Patterns: What Not to Do

A bad CLAUDE.md can be worse than no CLAUDE.md because it gives Claude Code confident but wrong context. Here are the most common mistakes.

1. The Novel (Too Long)

If your CLAUDE.md is over 500 lines, it is too long. Claude Code processes the entire file at the start of each session, and an overly long file dilutes the important information with noise.

Bad:

## Complete API Reference
### GET /users
Returns a list of users. Supports pagination via `page` and `limit` query params...
[400 more lines of API documentation]

Better: Link to the docs instead.

## API
- API docs: `docs/api.md`
- OpenAPI spec: `api/openapi.yaml`
- All endpoints follow REST conventions documented in `docs/api-conventions.md`

2. The Vague Handwave (Too Generic)

Instructions that could apply to any project are wasted space.

Bad:

- Write clean code
- Follow best practices
- Add comments where needed
- Make sure tests pass

Better: Be specific to your project.

- Functions over 30 lines should be broken up
- No abbreviations in variable names (use `transaction`, not `txn`)
- JSDoc on all exported functions
- Tests must cover error paths, not just happy paths

3. The Contradiction

When your CLAUDE.md says one thing but your codebase does another, Claude Code gets confused.

Bad:

## Conventions
- Use Tailwind CSS for all styling

...but half the codebase uses CSS Modules.

Better: Acknowledge reality.

## Conventions
- New components: use Tailwind CSS for styling
- Legacy components in `src/components/v1/` use CSS Modules -- migrate when touching these files

4. The Stale Artifact

A CLAUDE.md written six months ago that references packages since removed, build commands that changed, or architecture that was restructured.

Fix: Treat CLAUDE.md as living documentation. Update it when you change your stack or conventions.

5. The Prompt Injection

Some developers try to use CLAUDE.md as a prompt engineering playground, stuffing it with elaborate system-prompt-style instructions.

Bad:

You are an expert senior principal staff engineer with 25 years of experience.
Always think step by step. Take a deep breath before coding. 
Rate your confidence from 1-10 before every answer.

Better: CLAUDE.md is for project context, not personality instructions. Focus on facts about your codebase.

Common CLAUDE.md anti-patterns
Common CLAUDE.md anti-patterns


How to Iterate on Your CLAUDE.md

Your first CLAUDE.md will not be perfect. That is fine. Here is a practical process for improving it over time.

Start Small

Begin with just three sections: project overview, key commands, and conventions. That covers 80% of the value. You can always add more later.

Watch for Repeated Corrections

Every time you find yourself correcting Claude Code with the same feedback -- "no, we use pnpm not npm" or "put that in the services layer" -- add it to your CLAUDE.md. These corrections are your best source of what to include.

Review Monthly

Set a calendar reminder. Read through your CLAUDE.md once a month. Remove anything outdated. Add anything you have been repeatedly telling Claude Code in prompts.

Ask Claude Code to Help

You can literally ask Claude Code to suggest improvements to your CLAUDE.md:

Look at this codebase and suggest additions to CLAUDE.md based on 
patterns you observe in the code.

Claude Code will scan your project and suggest conventions it notices -- import patterns, file naming, test structures, and more. This is a great way to capture implicit conventions you might not think to document.

Use Per-Directory CLAUDE.md for Large Projects

If your project has distinct sections with different conventions (a frontend and a backend in the same repo, for example), use nested CLAUDE.md files:

project/
  CLAUDE.md              # Global: monorepo structure, shared commands
  frontend/
    CLAUDE.md            # Frontend-specific: React patterns, styling rules
  backend/
    CLAUDE.md            # Backend-specific: API patterns, DB conventions
  infrastructure/
    CLAUDE.md            # Infra-specific: Terraform conventions, naming

Iterating on CLAUDE.md over time
Iterating on CLAUDE.md over time


How SuperBuilder Helps

SuperBuilder is a desktop app built on top of Claude Code that makes managing your AI coding workflow easier -- including your CLAUDE.md.

Visual CLAUDE.md Editor

Instead of manually editing a markdown file, SuperBuilder provides a structured editor that organizes your CLAUDE.md into sections. Add commands, conventions, and architecture notes through a clean interface, and SuperBuilder generates the properly formatted markdown.

Template Suggestions

When you open a new project in SuperBuilder, it scans your package.json, pyproject.toml, go.mod, or other manifest files and suggests a CLAUDE.md template tailored to your stack. A React + Vite + Vitest project gets different suggestions than a Django + PostgreSQL project.

Memory System

SuperBuilder maintains a persistent memory across sessions that works alongside CLAUDE.md. As you work with Claude Code through SuperBuilder, it remembers corrections and preferences, building up context that complements your static CLAUDE.md file. Think of CLAUDE.md as the team documentation and SuperBuilder's memory as your personal notes.

Debug Mode Integration

When Claude Code is debugging an issue, SuperBuilder logs hypotheses, test results, and findings. This debug context works with your CLAUDE.md -- the architecture and conventions you document help Claude Code form better hypotheses about where bugs might live.

SuperBuilder CLAUDE.md editor interface
SuperBuilder CLAUDE.md editor interface


Putting It All Together

Here is a checklist for writing your CLAUDE.md today:

  1. State your stack in 2-3 lines at the top (framework, language, key libraries)
  2. List every command a developer needs (dev, test, lint, build, migrate)
  3. Map your file structure -- where do components, services, tests, and configs live?
  4. Write down your conventions -- the unwritten rules your team follows
  5. Add constraints -- things Claude Code should never do in your project
  6. Keep it under 200 lines for most projects (500 max for large monorepos)
  7. Commit it to version control so the whole team benefits
  8. Review it monthly and update when your stack or patterns change

The best CLAUDE.md files are not works of art. They are practical, specific, and current. They take 15 minutes to write and save hours of correcting AI-generated code that does not match your project.

If you are using Claude Code without a CLAUDE.md, you are using it at a fraction of its potential. Write one today. Start small, iterate, and watch the quality of AI-generated code in your project jump dramatically.


FAQ

How long should a CLAUDE.md be?

For most projects, 50-200 lines is ideal. Monorepos might stretch to 300-500 lines. If you are over 500 lines, you are probably including information that belongs in separate documentation files.

Should I commit CLAUDE.md to version control?

Yes. The project-level CLAUDE.md should be in your repo so every team member and CI environment benefits from it. Your personal ~/.claude/CLAUDE.md stays local.

Does CLAUDE.md work with other AI tools?

CLAUDE.md is specific to Claude Code (and tools built on it, like SuperBuilder). However, similar conventions exist for other tools -- Cursor uses .cursorrules, GitHub Copilot uses .github/copilot-instructions.md. The content is often transferable even if the file format differs.

Can I have multiple CLAUDE.md files?

Yes. Claude Code reads CLAUDE.md files from your home directory, project root, and any subdirectory you are working in. They are merged together, with more specific files taking precedence.

What if my CLAUDE.md contradicts the code?

Claude Code will generally follow your CLAUDE.md instructions, but it also reads your actual code. If there is a contradiction, it may get confused or ask for clarification. The fix is to keep your CLAUDE.md in sync with reality -- document what is, and note planned changes separately.

Should I include API keys or secrets in CLAUDE.md?

Never. CLAUDE.md is committed to version control and should contain no secrets. Use environment variable names instead: "Set DATABASE_URL in .env for local development."

How is CLAUDE.md different from a README?

A README is for human developers and usually covers setup, usage, and contribution guidelines. CLAUDE.md is optimized for AI consumption -- it focuses on conventions, constraints, and patterns that an AI agent needs to generate correct code. There is some overlap, but the audiences and goals differ.

CLAUDE.md FAQ
CLAUDE.md FAQ


Want to get more out of Claude Code? SuperBuilder gives you a visual interface for managing CLAUDE.md, persistent memory across sessions, and powerful debugging tools. Download it free at superbuilder.sh.

SuperBuilder

Build faster with SuperBuilder

Run parallel Claude Code agents with built-in cost tracking, task queuing, and worktree isolation. Free and open source.

Download for Mac