Claude Code Claudemd
`CLAUDE.md` is the most important configuration file in Claude Code, used to pass project-level persistent instructions to Claude. Every time a Claude Code session starts, it automatically reads and loads the contents of this file, incorporating it as system-level context into every conversation.\n\nIn simple terms, `CLAUDE.md` is a work manual you write for Claude in your projectβtelling it what the project is, what conventions to follow, and what to watch out for, so that it can work in a project-compliant way every time, instead of having to re-explain everything in each conversation.\n\n* * *\n\n## What CLAUDE.md Does\n\nWithout `CLAUDE.md`, Claude starts from scratch understanding your project every time, and you need to repeatedly tell it: which package manager to use, what the code style is, how to run tests, which files not to touch... With `CLAUDE.md`, this information only needs to be written once, and Claude will follow it every time.\n\nSpecifically, `CLAUDE.md` can help you do the following:\n\n* **Unify team behavior**: Commit the file to git, and all team members using Claude Code will follow the same conventions\n* **Reduce repetitive communication**: Project conventions, architecture rules, and prohibitions are written once and take effect permanently\n* **Reduce error probability**: Clearly inform Claude which operations are risky to avoid incorrect decisions\n* **Accelerate AI understanding**: Help Claude quickly locate key files and understand project structure, reducing unnecessary file exploration\n\n* * *\n\n## File Placement Locations\n\nClaude Code loads `CLAUDE.md` from multiple locations, and files in different locations have different scopes:\n\n| Location | Path | Scope | Commit to git? |\n| --- | --- | --- | --- |\n| **Project root** | `{project root}/CLAUDE.md` | All sessions in current project | β
Recommended to commit, shared by team |\n| **Project local** | `{project root}/.claude/CLAUDE.md` | All sessions in current project | β Add to .gitignore, personal use only |\n| **Subdirectory** | `{any subdirectory}/CLAUDE.md` | Automatically loaded when Claude opens files in that directory | β
Suitable for multi-module repositories |\n| **Global user-level** | `~/.claude/CLAUDE.md` | All projects for current user | β Personal config, don't commit |\n\nWhen `CLAUDE.md` exists in multiple locations, Claude Code will **load and merge them all**, with priority from high to low as follows:\n\nProject local β Project root β Subdirectory β Global user-level\n> The `CLAUDE.md` in the project root directory is recommended to be committed to git, so the entire team shares the same set of AI work conventions.\n> \n> \n> Personal preferences (such as not liking semicolons) should be placed in `.claude/CLAUDE.md` and added to `.gitignore`, so as not to affect others.\n\n* * *\n\n## Quickly Creating CLAUDE.md\n\nThe simplest way is to let Claude Code automatically generate an initial version. After starting Claude Code in the project directory, execute:\n\n/init\nClaude Code will analyze your project structure, code style, and existing configuration files (such as `package.json`, `pyproject.toml`, `.eslintrc`, etc.), automatically generating a `CLAUDE.md` that matches your project's actual situation, which you can then supplement and adjust.\n\nYou can also manually create it in the project directory:\n\ntouch CLAUDE.md\n\n* * *\n\n## File Content Structure\n\n`CLAUDE.md` is a regular Markdown file with no mandatory format requirements, but a good structure can help Claude find key information faster. Here is the recommended content structure:\n\n# Project NameOne sentence explaining what this project is, so Claude can quickly identify the project nature.## Tech Stack- Language: Python 3.11- Framework: FastAPI 0.110- Database: PostgreSQL 15 + SQLAlchemy ORM - Testing: pytest ## Common Commands### Development```bash uv run uvicorn main:app --reload # Start development server uv run pytest # Run all tests uv run pytest -k "test_auth" # Run specific test ```### Code Quality```bash uv run ruff check . # Code linting uv run ruff format . # Code formatting ```## Project Structure- `src/api/` β API routes and request handling- `src/models/` β Database model definitions- `src/services/` β Business logic layer- `tests/` β Test files, mirroring the structure of src/ directory## Coding Standards- Use `uv` to manage dependencies, do not use pip to install directly- All functions must have type annotations- Use double quotes for strings consistently- New API routes must have corresponding tests added simultaneously## Important Notes- Do not modify existing files in the `migrations/` directory, only add new migration files- `config/secrets.py` contains sensitive configuration,Do not output its content to logs or terminals- Database operations must go through the Service layer, do not directly operate ORM in the route layer\n\n* * *\n\n## Detailed Explanation of Core Content Modules\n\n### 1. Common Commands\n\nThis is the **most frequently referenced** part of `CLAUDE.md`. When Claude executes tasks such as testing, building, and code checking, it will prioritize commands defined here, avoiding guesses or using incorrect commands:\n\n## Common Commands### Install Dependencies```bash npm ci # Install dependencies (for CI environments, strictly follow lock file) ```### Development```bash npm run dev # Start development server (port 3000) npm run build # Build production version npm run preview # Preview production build ```### Testing```bash npm test # Run all tests npm test -- --watch # Watch mode npm test -- --coverage # Generate coverage report ```### Code Quality```bash npm run lint # ESLint check npm run lint:fix # Auto-fix fixable issues npm run typecheck # TypeScript type checking ```\n### 2. Project Structure Explanation\n\nHelps Claude quickly locate files and reduce unnecessary directory scanning, especially effective in large projects:\n\n## Project Structure``` src/ βββ app/ # Next.js App Router pages β βββ (auth)/ # Page group requiring login β βββ api/ # API routes βββ components/ # Reusable UI components β βββ ui/ # Basic UI components (Button, Input, etc.) β βββ features/ # Business components (organized by functional modules) βββ lib/ # Utility functions and configuration β βββ db/ # Database client and queries β βββ auth/ # Authentication-related logic βββ types/ # TypeScript type definitions ```Key files:- `src/lib/db/client.ts` β Database connection configuration- `src/middleware.ts` β Authentication middleware, handles route protection- `env.example` β Examples of all necessary environment variables\n### 3. Coding Standards\n\nInform Claude of the project's code style and conventions to ensure generated code is consistent with the existing codebase:\n\n## Coding Standards### General- File names use kebab-case (e.g., `user-profile.ts`), class names use PascalCase- Prefer named exports, avoid default exports- Asynchronous functions must use async/await,Forbidden .then() chain calls### Component Standards- Component files and their test files are placed in the same directory (e.g., `Button.tsx` and `Button.test.tsx`)- Props types are defined using interface, naming format is `${ComponentName}Props`- Do not write business logic in components, extract to custom Hooks or Services### Error Handling- API routes use unified error response format: `{ error: string, code: string }`- Client-side errors are caught via Error Boundary, do not try/catch individually in each component\n### 4. Architecture Constraints and Prohibitions\n\nThis is the key section to prevent Claude from making "clever but wrong" decisions. For special cases that you know but Claude doesn't, they must be explicitly stated:\n\n## Architecture Constraints- All database queries must be executed through functions in `src/lib/db/queries/`, do not write SQL directly in routes or components - Use Zustand for state management, do not introduce Redux or other state management libraries- Use Tailwind CSS utility classes for styling, do not add new CSS files or use CSS Modules## Important Notes (Important)- Code in the `legacy/` directory is legacy code, **modification prohibited**, read-only- `.env.local` and `.env.production` contain real keys, **Do not output file contents**- Existing migration files in `prisma/migrations/` **Do not modify**, database changes can only add new migrations- Before modifying `src/middleware.ts`, you must inform me first, as this file affects authentication logic for all routes\n### 5. Development Environment Description\n\nHelps Claude understand the project's runtime environment to avoid command execution failures due to environment differences:\n\n## Development Environment- Node.js: Requires v20 or above (specified via `.nvmrc`)- Package manager: pnpm (prohibits using npm or yarn to install dependencies)- Local database: Started via Docker Compose (`docker compose up -d`)- Ports: Frontend 3000, API 3001, Database 5432### Environment VariablesRefer to `.env.example` file to configure local environment variables, copy to `.env.local` and fill in actual values. Required: `DATABASE_URL`, `NEXTAUTH_SECRET`, `NEXTAUTH_URL`\n\n* * *\n\n## Configuration for Monorepos\n\nIn a monorepo, you can place a global `CLAUDE.md` at the repository root, and place individual `CLAUDE.md` files in each sub-package directory. When Claude opens a file in a sub-package, it will load both the root directory and that sub-package directory's files:\n\nmy-monorepo/βββ CLAUDE.md β Global conventions: shared commands, overall architecture, general conventionsβββ packages/β βββ web/β β βββ CLAUDE.md β Frontend-specific: React conventions, styling rules, build processβ βββ api/β β βββ CLAUDE.md β Backend-specific: API design conventions, database conventionsβ βββ shared/β βββ CLAUDE.md β Shared package: export rules, version management conventionsβββ tools/ βββ CLAUDE.md β Tool scripts: special instructions and usage restrictions # My Monorepo A frontend-backend integrated project managed with pnpm workspace. ## Global Commands ```bash pnpm install # Install dependencies for all packages pnpm -r build # Build all packages pnpm -r test # Run tests for all packages pnpm --filter web dev # Only start web package development server ``` ## Inter-package Dependencies - Both `web` and `api` depend on `shared` - Prohibit `shared` from depending on `web` or `api` (to prevent circular dependencies) - Cross-package references use package names (e.g., `@my-app/shared`), do not use relative paths\n\n* * *\n\n## Referencing External Files with @ Syntax\n\nWhen your project already has specification documents (such as API design specifications, database design documents, etc.), you don't need to copy their contents into `CLAUDE.md`; simply reference them with `@file_path`.\n\nClaude will automatically load the referenced file contents when reading `CLAUDE.md`:\n\n## Specification DocumentsFor detailed API design specifications, please refer to: @docs/api-design-guide.md Database design conventions: @docs/database-conventions.md Component library usage instructions: @docs/component-guidelines.md\n> The referenced file paths are relative to the directory where `CLAUDE.md` is located. Referenced file contents will occupy context window space, avoid referencing overly large files (recommended single referenced file not exceeding 500 lines).\n\n* * *\n\n## Usage Suggestions for Global CLAUDE.md\n\nUser-level `~/.claude/CLAUDE.md` is suitable for storing cross-project general personal preferences and habits, which take effect for all projects:\n\n # Personal Global Configuration ## Response Preferences - Reply in Chinese - Briefly explain modificationApproach before code changes, do not directly provide code - When multiple implementation options exist, list options for me to choose, rather than directly selecting one ## General Conventions - Commit messages in English, format: `type(scope): description` - No copyright comments at the beginning of new files - Prefer native APIs, avoid introducing unnecessary dependencies ## Security Habits - Proactively prompt me about security implications before modifying authentication-related code - Do not output any keys or tokens in code comments or logs\n\n* * *\n\n## Maintenance Suggestions for CLAUDE.md\n\n### 1. Keep It Concise\n\n`CLAUDE.md` content occupies context window space in every session. Too much content will compress Claude's actual available context space, reducing efficiency instead. The following principles are recommended:\n\n* Write each rule only once, do not repeat the same meaning\n* Background information unrelated to code (such as company introductions, product planning) should not be included\n* Information that can be conveyed through the code itself (such as eslint configuration already defining code style) does not need to be repeated in `CLAUDE.md`\n* Recommended total word count controlled within 500 words; considerCondense when exceeding 1000 words\n\n### 2. Keep It Updated\n\nAs the project evolves, `CLAUDE.md` also needs to be updatedSynchronize. Updates should be triggered at the following times:\n\n* Package manager or build tool has been changed\n* Important dependencies added or removed\n* New coding conventions established\n* Claude repeatedly makes the same type of error (indicating need to supplement in `CLAUDE.md`)\n* A file or module becomes not freely modifiable (add to Important Notes)\n\n### 3. Use Imperative Language\n\nThe clearer the instructions, the higher the probability Claude will follow them. Avoid vague descriptions, use direct commands:\n\n| β Vague Description | β
Clear Instruction |\n| --- | --- |\n| Code should be relatively tidy | Functions must not exceed 50 lines, must be split when exceeded |\n| Try to write tests | Every new function must have corresponding unit tests |\n| Pay attention to security | User input must be processed through `sanitize()` function before being passed to database queries |\n| The legacy directory is not very important | Modification of any files under `legacy/` directory is prohibited |\n| Using pnpm is better | Use only pnpm for dependency management, npm or yarn is prohibited |\n\n* * *\n\n## Complete Example\n\nBelow is a complete `CLAUDE.md` example for a Node.js + TypeScript full-stack project, which can serve as a reference template for your project:\n\n## Example\n\n# MyApp β E-commerce Admin Backend\n\nAn e-commerce management system based on Next.js 14 App Router + Prisma + PostgreSQL.\n\n## Tech Stack\n\n- Frontend: Next.js 14 (App Router), TypeScript, Tailwind CSS, shadcn/ui\n\n- Backend: Next.js API Routes, Prisma ORM\n\n- Database: PostgreSQL 15\n\n- Authentication: NextAuth.js v5\n\n- Package Manager: pnpm\n\n## Common Commands\n\n```bash\n\n pnpm dev # Start development server (port 3000)\n\n pnpm build && pnpm start # Build and start production server\n\n pnpm test # Run all tests\n\n pnpm test:e2e # Run end-to-end tests (requires dev server to be running first)\n\n pnpm db:migrate # Execute database migrations\n\n pnpm db:studio # Open Prisma Studio (database visualization tool)\n\n pnpm lint && pnpm typecheck # Code linting and type checking\n\n ```\n\n## Project Structure\n\n- `src/app/` β App Router pages and API routes\n\n- `src/app/(dashboard)/` β Backend pages requiring login\n\n- `src/app/api/` β API routes (RESTful style)\n\n- `src/components/` β Reusable components\n\n- `src/lib/` β Utility functions, database client, authentication configuration\n\n- `prisma/schema.prisma` β Database Schema definition\n\n## Coding Standards\n\n- Use only named exports, prohibit default exports (except for Next.js page files)\n\n- Server components default to async, client components add `"use client"` at top of file\n\n- Unified API route return format: success `{ data: T }`, failure `{ error: string, code: string }`\n\n- Database queries encapsulated in `src/lib/db/` directory, do not directly use `prisma` client elsewhere\n\n## Important Notes\n\n- Existing files in `prisma/migrations/` **modification prohibited**, database changes can only execute `pnpm db:migrate` to add new migrations\n\n- `.env.local` contains real keys, **Do not read or output file contents**\n\n- `src/lib/auth.ts` is the core authentication file, **must inform me before modifying**\n\n- After modifying `prisma/schema.prisma`, must execute `pnpm db:migrate` and commit migration files\n\n* * *\n\n## Frequently Asked Questions\n\n**Q: What if Claude doesn't follow the rules in CLAUDE.md?**\n\nFirst check whether the rule description is clear enough (see "Use Imperative Language" suggestion above)
YouTip