guide36 min read1mo ago

CLAUDE.md Examples: 20 Copy-Paste Templates for Every Project Type

20 real-world CLAUDE.md templates organized by stack and team size. Copy-paste examples for Next.js, Python, Rust, React Native, monorepos, microservices, and more.

CLAUDE.md Examples: 20 Copy-Paste Templates for Every Project Type
claude codeclaude.mdproject instructionstemplatesdeveloper toolsbest practices2026

CLAUDE.md Examples: 20 Copy-Paste Templates for Every Project Type (2026)

TL;DR

20 production-ready CLAUDE.md templates, organized by stack and team size. Every template is copy-paste ready and battle-tested on real codebases in 2026.

  • Solo Developer (4 templates) -- Next.js, FastAPI, React Native, Rust CLI
  • Frontend Team (3 templates) -- Turborepo monorepo, design system, headless e-commerce
  • Backend/DevOps (3 templates) -- microservices, database-heavy, serverless
  • Specialized (5 templates) -- AI/ML, security-focused, open source, docs site, SwiftUI
  • Team Patterns (5 templates) -- junior guardrails, code review, strict TypeScript, legacy migration, polyglot repo

Pick your stack, copy the template, customize the specifics. Time from zero to effective CLAUDE.md: under five minutes.


Table of Contents

  1. What Is CLAUDE.md and Why It Matters
  2. CLAUDE.md Anatomy: Section Breakdown
  3. Solo Developer Templates
  4. Frontend Team Templates
  5. Backend and DevOps Templates
  6. Specialized Project Templates
  7. Team Pattern Templates
  8. Common Mistakes: 5 Anti-Patterns to Avoid
  9. CLAUDE.md + Skills + MCP: How They Work Together
  10. Frequently Asked Questions

What Is CLAUDE.md and Why It Matters

CLAUDE.md is a special markdown file that Claude Code reads automatically at the start of every session. It lives in the root of a project directory and contains project-specific instructions, coding standards, forbidden patterns, and workflow rules that shape how Claude Code behaves inside that codebase.

Think of it as a .editorconfig for AI. Just as .editorconfig tells text editors how to format code, CLAUDE.md tells Claude Code how to think about, write, and modify code in a specific project. The difference is scope -- CLAUDE.md governs everything from architecture decisions to naming conventions to deployment workflows.

Why it matters in 2026: As AI-assisted development becomes standard practice, the gap between teams that get consistent, high-quality output from Claude Code and teams that fight constant corrections comes down to one thing -- project instructions. A well-written CLAUDE.md eliminates the "cold start" problem where Claude Code generates code that technically works but does not match the project's conventions, architecture, or team preferences.

Claude Code reads CLAUDE.md files at three levels:

  1. Project root (/project/CLAUDE.md) -- applies to every session in the project
  2. Subdirectories (/project/src/CLAUDE.md) -- scoped instructions for specific modules
  3. User-level (~/.claude/CLAUDE.md) -- personal preferences that apply across all projects

The file supports approximately 150-200 instructions before diminishing returns. Beyond that threshold, specificity drops and Claude Code may deprioritize lower-listed rules. The best CLAUDE.md files are dense, specific, and ruthlessly edited.

For a deeper understanding of how CLAUDE.md interacts with Claude Code's skill system and hooks, those concepts are covered in the integration section below. First, the anatomy of a well-structured CLAUDE.md.


CLAUDE.md Anatomy: Section Breakdown

Every effective CLAUDE.md follows a predictable structure. The order matters -- Claude Code weights instructions that appear earlier in the file slightly higher, so the most critical rules belong at the top.

Project Context

The opening section. Two to four sentences that tell Claude Code what this project is, what stack it uses, and what it should never forget. This section prevents Claude Code from making wrong assumptions about the architecture.

# Project: Acme Dashboard
Next.js 15 App Router with TypeScript strict mode. Postgres via Prisma ORM.
Deployed on Vercel. All API routes use Route Handlers, not Pages API.

Coding Standards

The largest section in most files. Covers naming conventions, file structure patterns, import ordering, component patterns, and formatting rules. Be as specific as possible -- "use camelCase" is vague, "use camelCase for variables and PascalCase for React components and types" is actionable.

Forbidden Patterns

Explicit instructions about what Claude Code must never do. These are often the most impactful lines in the entire file. Negative instructions ("never use any", "do not create files in the root directory") prevent the most common AI-generated code problems.

Workflow Instructions

How Claude Code should approach tasks in this project. This includes test requirements ("run pnpm test after every edit"), commit message format, PR description templates, and deployment checks.

Skills and MCP References

Pointers to available skills and MCP servers that Claude Code can use within the project. This section tells Claude Code about external capabilities -- database access, image generation, deployment tools -- without embedding the full configuration.

File and Directory Map

A compact map of the project structure so Claude Code knows where things live. Especially valuable in large codebases where file discovery through search would waste context window.


Now for the templates. Each one is a complete, copy-paste-ready CLAUDE.md. Customize the project-specific details (marked with {brackets}) and drop it into the project root.


Solo Developer Templates

1. Next.js 15 App Router Project

# {Project Name}

Next.js 15 App Router project with TypeScript strict mode. React 19 with Server Components by default.
Styling: Tailwind CSS v4. State: Zustand for client state, React Query for server state.
Database: Postgres via Prisma ORM. Auth: NextAuth.js v5. Deployed on Vercel.

## Architecture Rules

- App Router ONLY. No Pages Router. No `getServerSideProps` or `getStaticProps`.
- Default to Server Components. Add `"use client"` only when the component needs interactivity, hooks, or browser APIs.
- Route Handlers live in `app/api/` and always return `NextResponse.json()`.
- Server Actions live in dedicated `actions/` files with `"use server"` at the top.
- Data fetching happens in Server Components or Server Actions. Never fetch in Client Components directly -- pass data as props or use React Query.

## File Structure

app/ -- Routes and layouts (App Router) components/ -- Shared UI components (PascalCase filenames) lib/ -- Utility functions, configs, constants actions/ -- Server Actions prisma/ -- Schema and migrations public/ -- Static assets


## Coding Standards

- TypeScript strict mode. No `any`. No `as` type assertions unless documented with a comment explaining why.
- Components: named exports only. One component per file. File name matches component name.
- Imports: external packages first, then `@/` aliases, then relative imports. Blank line between groups.
- Tailwind classes: use `cn()` utility from `lib/utils` for conditional classes. No inline style objects.
- All async functions must have explicit error handling with try/catch or `.catch()`.
- API responses follow shape: `{ data: T } | { error: string, code: number }`.

## Forbidden Patterns

- NEVER use `var`. Use `const` by default, `let` only when reassignment is required.
- NEVER use `// @ts-ignore` or `// @ts-expect-error` without a linked issue number.
- NEVER use `innerHTML` or `dangerouslySetInnerHTML` unless sanitizing with DOMPurify.
- NEVER commit `.env` files. All env vars are in `.env.example` with placeholder values.
- NEVER use default exports except for Next.js route files (page.tsx, layout.tsx, route.ts).

## Commands

- `pnpm dev` -- Start dev server
- `pnpm build` -- Production build (must pass before any PR)
- `pnpm lint` -- ESLint check
- `pnpm test` -- Run Vitest suite
- `pnpm db:push` -- Push Prisma schema to database
- `pnpm db:studio` -- Open Prisma Studio

2. Python FastAPI Backend

# {Project Name}

Python 3.12 FastAPI backend. Async-first architecture.
Database: PostgreSQL via SQLAlchemy 2.0 (async). Migrations: Alembic.
Auth: JWT with python-jose. Task queue: Celery + Redis.
Containerized with Docker. Deployed to AWS ECS.

## Architecture Rules

- All endpoints are async (`async def`). No sync endpoints unless wrapping a blocking library.
- Business logic lives in `services/`, NOT in route handlers. Route handlers validate input, call a service, return the response.
- Database access happens only in `repositories/`. Services never import SQLAlchemy directly.
- Dependency injection via FastAPI's `Depends()`. No global state, no module-level database sessions.
- Pydantic v2 models for ALL request/response schemas. No raw dicts crossing API boundaries.

## File Structure

app/ api/routes/ -- Route handlers grouped by domain core/ -- Config, security, dependencies models/ -- SQLAlchemy ORM models schemas/ -- Pydantic request/response models services/ -- Business logic repositories/ -- Database access layer tasks/ -- Celery tasks tests/ unit/ -- Fast tests, mocked dependencies integration/ -- Tests that hit the database alembic/ -- Database migrations


## Coding Standards

- Type hints on ALL function signatures, including return types. Use `-> None` explicitly.
- Docstrings: Google style. Required on all public functions and classes.
- Imports: stdlib first, third-party second, local third. `isort` profile: black.
- Formatting: Black with line length 88. No manual formatting overrides.
- Naming: snake_case for functions/variables, PascalCase for classes, UPPER_SNAKE for constants.
- Error handling: raise `HTTPException` in routes, raise custom domain exceptions in services. Never bare `except:`.

## Forbidden Patterns

- NEVER use `from sqlalchemy import *` or any wildcard imports.
- NEVER store passwords in plaintext. Use `passlib.hash.bcrypt`.
- NEVER commit migration files without reviewing the generated SQL.
- NEVER use `time.sleep()` in async code. Use `asyncio.sleep()`.
- NEVER return raw SQLAlchemy model instances from API endpoints. Always serialize through Pydantic.
- NEVER use `print()` for logging. Use `structlog` with the configured logger.

## Commands

- `uv run uvicorn app.main:app --reload` -- Dev server
- `uv run pytest` -- Run tests
- `uv run pytest --cov=app --cov-report=term-missing` -- Tests with coverage
- `uv run alembic upgrade head` -- Apply migrations
- `uv run alembic revision --autogenerate -m "description"` -- Generate migration
- `uv run ruff check .` -- Lint
- `uv run black .` -- Format

3. React Native / Expo Mobile App

# {Project Name}

React Native with Expo SDK 52. TypeScript strict mode. Targets iOS and Android.
Navigation: Expo Router (file-based). State: Zustand + React Query.
Backend: Supabase (auth, database, storage). OTA updates: EAS Update.

## Architecture Rules

- Expo Router file-based routing in `app/` directory. No React Navigation manual configuration.
- All screens are in `app/` as route files. Shared components are in `components/`.
- Platform-specific code uses `.ios.tsx` / `.android.tsx` suffixes, NOT `Platform.select()` unless it is a one-liner.
- All Supabase calls go through `lib/supabase/` wrapper functions. No direct Supabase imports in components.
- Animations: use `react-native-reanimated` worklets. No `Animated` API from React Native core.

## Coding Standards

- Components: functional only. No class components. Named exports only.
- Styling: `StyleSheet.create()` at the bottom of each file. No inline styles except for dynamic values.
- All user-facing strings must use `i18n.t()` for localization readiness.
- Images: use `expo-image` (not `Image` from react-native). Always set width, height, and contentFit.
- All async operations must show loading states and handle errors with user-visible feedback.

## Forbidden Patterns

- NEVER use `any` type. No `@ts-ignore`.
- NEVER use `console.log` in production code. Use the logger utility in `lib/logger.ts`.
- NEVER use synchronous storage (`localStorage`). Use `expo-secure-store` for sensitive data, `@react-native-async-storage/async-storage` for preferences.
- NEVER hardcode API URLs. All endpoints come from `lib/config.ts`.
- NEVER use `setTimeout` for UI delays. Use Reanimated timing or Expo's animation utilities.

## Commands

- `npx expo start` -- Start dev server
- `npx expo start --ios` -- Start with iOS simulator
- `npx expo start --android` -- Start with Android emulator
- `npx expo run:ios` -- Native build (iOS)
- `pnpm test` -- Run Jest tests
- `eas build --platform ios` -- Production iOS build
- `eas build --platform android` -- Production Android build
- `eas update` -- Push OTA update

4. Rust CLI Tool

# {Project Name}

Rust CLI application built with `clap` v4 for argument parsing.
Error handling: `anyhow` for application errors, `thiserror` for library errors.
Serialization: `serde` + `serde_json`. HTTP: `reqwest` with rustls.
Minimum Supported Rust Version (MSRV): 1.78.

## Architecture Rules

- Binary entrypoint (`main.rs`) handles argument parsing and delegates to library functions.
- Core logic lives in `src/lib.rs` and submodules. `main.rs` should be under 50 lines.
- All public functions must return `Result<T, E>`. Never `unwrap()` or `expect()` in library code.
- Configuration: use `config` crate with layered sources (defaults, file, env vars, CLI args).
- Output formatting: structured output uses `serde_json`. Human output uses `colored` crate. Toggle via `--json` flag.

## File Structure

src/ main.rs -- CLI entrypoint, clap setup lib.rs -- Public API, re-exports config.rs -- Configuration loading commands/ -- One module per CLI subcommand client/ -- HTTP client and API wrappers models/ -- Data structures errors.rs -- Custom error types (thiserror) tests/ integration/ -- Full CLI integration tests


## Coding Standards

- Run `cargo fmt` before every commit. No manual formatting.
- `cargo clippy -- -W clippy::all -W clippy::pedantic` must pass with zero warnings.
- All public items must have doc comments (`///`). Include examples for complex functions.
- Use `impl Into<String>` and `AsRef<str>` for string parameters where appropriate.
- Prefer iterators over manual loops. Use `.collect()`, `.map()`, `.filter()` chains.
- Error messages must be lowercase, no trailing period (Rust convention).

## Forbidden Patterns

- NEVER use `unwrap()` or `expect()` in library code. Only allowed in tests and `main.rs` where errors are handled.
- NEVER use `unsafe` blocks without a `// SAFETY:` comment explaining the invariant.
- NEVER use `println!` for output in library code. Return data and let the caller decide formatting.
- NEVER add dependencies without checking their maintenance status and license compatibility.
- NEVER use `String` where `&str` would suffice for function parameters.

## Commands

- `cargo build` -- Debug build
- `cargo build --release` -- Release build
- `cargo test` -- Run all tests
- `cargo clippy` -- Lint
- `cargo fmt --check` -- Check formatting
- `cargo doc --open` -- Generate and open documentation
- `cargo bench` -- Run benchmarks (if configured)

Frontend Team Templates

5. Monorepo (Turborepo + pnpm)

# {Project Name} Monorepo

Turborepo monorepo managed with pnpm workspaces.
Contains: web app (Next.js 15), marketing site (Astro), shared UI library, API packages.
CI: GitHub Actions with Turborepo remote caching. Deployed on Vercel.

## Monorepo Structure

apps/ web/ -- Main Next.js 15 app (App Router) marketing/ -- Astro marketing site docs/ -- Documentation site (Nextra) packages/ ui/ -- Shared component library (@acme/ui) config/ -- Shared ESLint, Tailwind, TypeScript configs database/ -- Prisma schema, client, and types (@acme/db) utils/ -- Shared utilities (@acme/utils) api-client/ -- Type-safe API client (@acme/api) turbo.json -- Pipeline configuration


## Architecture Rules

- Packages use `@acme/` scope prefix. Imports between packages always use the package name, never relative paths across package boundaries.
- Shared UI components live in `packages/ui/`. App-specific components live in the app's own `components/` directory.
- Database types are exported from `@acme/db`. No Prisma imports outside that package.
- Every package has its own `tsconfig.json` extending `@acme/config/typescript`.
- Changes to `packages/` must not break any app. Run `turbo build` to verify before committing.

## Coding Standards

- TypeScript strict mode in all packages. No exceptions.
- Package dependencies: shared deps go in the root `package.json`. Package-specific deps go in the package's own `package.json`.
- Changesets for versioning: run `pnpm changeset` before merging any PR that modifies a package.
- Component exports: every `packages/ui` component must be re-exported from its `index.ts`.

## Forbidden Patterns

- NEVER import from one app into another app. Apps are independent. Share through packages.
- NEVER install dependencies at the root level unless they are truly workspace-wide (turbo, prettier, etc.).
- NEVER bypass Turborepo caching by running commands directly in subdirectories.
- NEVER create circular dependencies between packages. The dependency graph must be a DAG.

## Commands

- `pnpm dev` -- Start all apps in dev mode
- `pnpm dev --filter=web` -- Start only the web app
- `turbo build` -- Build all packages and apps (cached)
- `turbo test` -- Run all tests (cached)
- `turbo lint` -- Lint all packages
- `pnpm changeset` -- Create a changeset for versioning

6. Design System / Component Library

# {Project Name} Design System

React component library built with TypeScript, Radix UI primitives, and Tailwind CSS v4.
Documented in Storybook 8. Published to npm as `@{org}/ui`.
Tested with Vitest + Testing Library. Visual regression via Chromatic.

## Architecture Rules

- Every component gets its own directory: `src/components/{ComponentName}/`.
- Each directory contains: `{ComponentName}.tsx`, `{ComponentName}.test.tsx`, `{ComponentName}.stories.tsx`, and `index.ts`.
- Components are composed from Radix UI primitives when an accessible primitive exists. Do not reimplement focus traps, modals, or dropdowns from scratch.
- All components accept a `className` prop and merge it with internal classes using `cn()`.
- Variants are defined with `cva()` (class-variance-authority). No conditional Tailwind strings.

## Coding Standards

- Props interfaces: named `{ComponentName}Props`, exported alongside the component.
- All interactive components must support `ref` forwarding via `React.forwardRef`.
- All components must meet WCAG 2.2 AA accessibility standards. Test with axe in Storybook.
- Colors, spacing, and typography use design tokens only. No hardcoded values.
- Every component must have at least one Storybook story showing default, with-props, and edge-case states.

## Forbidden Patterns

- NEVER use `div` with click handlers. Use `button` or Radix primitives for interactive elements.
- NEVER use `px` units. Use `rem` or Tailwind spacing scale.
- NEVER add application logic to components. This is a UI library -- no API calls, no routing, no state management beyond component-local state.
- NEVER use `index` as a React key.
- NEVER export default. Named exports only.

## Commands

- `pnpm dev` -- Start Storybook
- `pnpm test` -- Run Vitest suite
- `pnpm test:watch` -- Watch mode
- `pnpm build` -- Build library for npm
- `pnpm lint` -- ESLint check
- `pnpm chromatic` -- Run visual regression tests
- `pnpm release` -- Publish to npm (requires auth)

7. E-Commerce Storefront (Headless Shopify)

# {Project Name} Storefront

Headless Shopify storefront built with Next.js 15 App Router and TypeScript.
Shopify Storefront API via GraphQL. Styling: Tailwind CSS v4.
Payments: Shopify Checkout. Search: Algolia. Analytics: GA4 + Segment.

## Architecture Rules

- Shopify Storefront API is the single source of truth for products, collections, and cart state.
- GraphQL queries live in `lib/shopify/queries/`. Mutations live in `lib/shopify/mutations/`. No inline GraphQL strings in components.
- Cart state is managed via Shopify's cart API and stored in cookies (not localStorage).
- Product pages are statically generated with ISR (revalidate every 60 seconds).
- Search uses Algolia InstantSearch. Product data syncs to Algolia via Shopify webhook.

## Coding Standards

- All Shopify API responses must be transformed through mappers in `lib/shopify/mappers/` before reaching components. Components never see raw Shopify GraphQL response shapes.
- Money formatting uses `Intl.NumberFormat` with the store's currency from Shopify.
- All product images use `next/image` with Shopify CDN URLs. Specify `sizes` prop for responsive loading.
- SEO: every product page needs dynamic `generateMetadata()` with title, description, and OpenGraph image from Shopify.

## Forbidden Patterns

- NEVER hardcode prices. All pricing comes from Shopify API.
- NEVER store payment or customer PII in the application. Shopify handles checkout and customer data.
- NEVER use Shopify's Liquid templates or theme files. This is a headless build.
- NEVER fetch product data on the client side. Use Server Components or ISR.
- NEVER use `dangerouslySetInnerHTML` for product descriptions without sanitization.

## Commands

- `pnpm dev` -- Start dev server
- `pnpm build` -- Production build
- `pnpm shopify:types` -- Generate TypeScript types from Shopify schema
- `pnpm test` -- Run tests
- `pnpm lint` -- Lint

Backend and DevOps Templates

8. Microservices (Docker + Kubernetes)

# {Project Name} Platform

Microservices architecture. Each service is a standalone container (Docker).
Orchestration: Kubernetes (EKS). Service mesh: Istio. Message broker: RabbitMQ.
Languages: Go (core services), Python (ML services), TypeScript (BFF).
CI/CD: GitHub Actions -> ECR -> ArgoCD -> EKS.

## Architecture Rules

- Each service lives in `services/{service-name}/` with its own Dockerfile, go.mod (or equivalent), and README.
- Services communicate via gRPC for synchronous calls and RabbitMQ for async events. No direct HTTP calls between services.
- Shared protobuf definitions live in `proto/`. Run `make proto` to regenerate stubs.
- Every service must expose `/healthz` (liveness) and `/readyz` (readiness) endpoints.
- Database per service. No shared databases. Services that need data from another service request it via API.

## File Structure

services/ auth/ -- Authentication service (Go) billing/ -- Billing and subscriptions (Go) notifications/ -- Email, push, SMS (Python) gateway/ -- API gateway / BFF (TypeScript) proto/ -- Shared protobuf definitions k8s/ base/ -- Base Kubernetes manifests overlays/staging/ -- Staging-specific overrides overlays/prod/ -- Production-specific overrides infrastructure/ -- Terraform modules scripts/ -- Build, deploy, and utility scripts


## Coding Standards

- Go services: follow `golang.org/x/lint` standards. Error wrapping with `fmt.Errorf("context: %w", err)`.
- All services must log in structured JSON format. Use `zerolog` (Go) or `structlog` (Python).
- Every service has unit tests (>80% coverage) and integration tests that run against Docker Compose.
- Kubernetes manifests use Kustomize overlays. No Helm charts unless the complexity justifies it.
- Resource requests and limits are REQUIRED in every Kubernetes deployment manifest.

## Forbidden Patterns

- NEVER share a database between services. If you need data from another service, expose an API.
- NEVER hardcode service URLs. Use Kubernetes service discovery (`{service}.{namespace}.svc.cluster.local`).
- NEVER store secrets in manifests or environment files. Use Kubernetes Secrets backed by AWS Secrets Manager.
- NEVER deploy without running `make test-integration` on the affected services.
- NEVER push images with `latest` tag. Always use the Git SHA as the image tag.

## Commands

- `make dev SERVICE=auth` -- Run a service locally with Docker Compose
- `make test SERVICE=auth` -- Unit tests
- `make test-integration SERVICE=auth` -- Integration tests
- `make proto` -- Regenerate protobuf stubs
- `make build SERVICE=auth` -- Build Docker image
- `make deploy-staging SERVICE=auth` -- Deploy to staging via ArgoCD

9. Database-Heavy Project (Postgres + Prisma)

# {Project Name}

Node.js application with heavy relational data operations. TypeScript strict mode.
Database: PostgreSQL 16 via Prisma ORM. Schema-first design.
Caching: Redis. Full-text search: PostgreSQL tsvector (not external search engine).
API: tRPC for type-safe client-server communication.

## Architecture Rules

- Prisma schema is the source of truth for the database. All structural changes go through Prisma migrations.
- Business logic lives in `services/`. Services receive a Prisma client via dependency injection.
- Complex queries that cannot be expressed in Prisma use `$queryRaw` with tagged template literals. All raw SQL lives in `lib/sql/` as named exports.
- Database transactions use `prisma.$transaction()` for multi-step operations. Never rely on application-level rollback logic.
- All list endpoints support cursor-based pagination. No offset pagination for user-facing queries.

## Migration Rules

- NEVER modify a migration file after it has been applied to staging or production.
- Every migration must be reversible. Include a rollback strategy in the migration's PR description.
- Add database indexes for any column used in `WHERE`, `ORDER BY`, or `JOIN` clauses.
- Large data migrations (>100k rows) must use batched operations with progress logging.
- Run `prisma migrate diff` to verify migration SQL before applying.

## Coding Standards

- Prisma queries: always select only the fields you need with `select`. No `include` of entire relations unless required.
- All database operations must have explicit error handling for unique constraint violations, not-found records, and connection failures.
- Use Prisma's `Decimal` type for financial data. Never `Float`.
- Redis cache keys follow format: `{entity}:{id}:{field}`. TTL must be set on every cached value.
- Query performance: any query taking >100ms in development must be optimized before merging.

## Forbidden Patterns

- NEVER use `prisma.*.findMany()` without `take` limit on user-facing endpoints.
- NEVER use raw `DELETE` without a `WHERE` clause. Prisma's type system prevents this, but watch raw SQL.
- NEVER store computed data that can be derived from source tables (unless for performance caching with clear invalidation).
- NEVER use `JSON` column type for data that should be relational. If you query by it, it needs its own table.
- NEVER ignore Prisma's generated types. All return values must match the Prisma-generated type.

## Commands

- `pnpm dev` -- Start with hot reload
- `pnpm db:migrate` -- Run pending migrations
- `pnpm db:seed` -- Seed development data
- `pnpm db:studio` -- Open Prisma Studio
- `pnpm db:reset` -- Reset and re-seed (destroys data)
- `pnpm test` -- Run tests (uses test database)
- `pnpm test:db` -- Run database-specific integration tests

10. Serverless (AWS Lambda / Vercel Functions)

# {Project Name}

Serverless application deployed on AWS Lambda via SST v3 (Ion).
Runtime: Node.js 22. Language: TypeScript strict mode.
Database: DynamoDB (single-table design). Auth: Cognito.
Event-driven: EventBridge for async workflows. SQS for queuing.

## Architecture Rules

- Functions are in `packages/functions/src/`. One file per Lambda function.
- Shared business logic lives in `packages/core/src/`. Functions are thin wrappers that call core logic.
- DynamoDB uses single-table design. All access patterns are documented in `docs/access-patterns.md`.
- Cold start budget: 500ms maximum. Measure with `powertools-lambda` metrics.
- API Gateway routes are defined in `sst.config.ts`. No CloudFormation YAML.

## Coding Standards

- Every Lambda handler must: validate input (Zod), call business logic, format response. Three responsibilities, nothing more.
- DynamoDB operations use the `@aws-sdk/lib-dynamodb` Document Client. Raw attribute values are never exposed to business logic.
- All environment variables accessed through a typed config module (`packages/core/src/config.ts`), never through `process.env` directly.
- Error responses follow shape: `{ error: string, code: string, statusCode: number }`.
- Bundle size per function must stay under 5MB. Check with `sst diff` before deploying.

## Forbidden Patterns

- NEVER use `*` imports from AWS SDK. Import only the specific client and commands needed.
- NEVER use synchronous file I/O in Lambda functions. Lambda's `/tmp` has limited space.
- NEVER use connection-pooled databases (Postgres, MySQL) without a connection proxy (RDS Proxy). Use DynamoDB or provision a proxy.
- NEVER set DynamoDB read/write capacity to on-demand without cost alerts in place.
- NEVER use `console.log` for structured logging. Use `@aws-lambda-powertools/logger`.

## Commands

- `pnpm sst dev` -- Start local development (live Lambda)
- `pnpm sst deploy --stage staging` -- Deploy to staging
- `pnpm sst diff` -- Preview infrastructure changes
- `pnpm test` -- Run tests
- `pnpm test:e2e` -- End-to-end tests against deployed stage

Specialized Project Templates

11. AI/ML Project (RAG Pipeline)

# {Project Name}

AI/ML application with RAG (Retrieval-Augmented Generation) pipeline.
Python 3.12. Framework: LangChain + LangGraph for orchestration.
Vector store: Pinecone. LLM: Claude 3.5 Sonnet via Anthropic API.
Embedding model: Voyage AI (voyage-3). Evaluation: Ragas.

## Architecture Rules

- Pipeline stages are defined as LangGraph nodes. Each node is a pure function: input state in, output state out.
- Document ingestion, chunking, embedding, and retrieval are separate pipeline stages. No monolithic RAG functions.
- Chunking strategy: semantic chunking with 512-token chunks, 50-token overlap. Configurable per document type.
- All LLM calls go through `lib/llm/` wrapper that handles retries, rate limiting, token counting, and cost tracking.
- Evaluation runs after every pipeline change. Metrics: faithfulness, relevancy, context precision (Ragas).

## Coding Standards

- Type hints required on all functions. Use `TypedDict` for state shapes that flow through the pipeline.
- All prompts live in `prompts/` directory as versioned `.txt` files with Jinja2 templates. No inline prompt strings.
- Experiment tracking: log all runs to MLflow with parameters, metrics, and artifacts.
- Chunking and embedding are deterministic for the same input. Test this with snapshot tests.
- Cost tracking: every LLM call must log token count and estimated cost. Add daily budget alerts.

## Forbidden Patterns

- NEVER put API keys in code or config files. Use `.env` with `python-dotenv` for local dev, AWS Secrets Manager for production.
- NEVER use `langchain` high-level chains for production. Use LangGraph for explicit control flow.
- NEVER fine-tune models without a documented dataset, evaluation baseline, and rollback plan.
- NEVER ship a RAG pipeline without evaluation metrics. Minimum: faithfulness > 0.85, relevancy > 0.80.
- NEVER use `pickle` for model serialization. Use `safetensors` or framework-native formats.

## Commands

- `uv run python -m app.pipeline.ingest` -- Run document ingestion
- `uv run python -m app.pipeline.evaluate` -- Run evaluation suite
- `uv run pytest` -- Run tests
- `uv run mlflow ui` -- Open MLflow tracking UI
- `docker compose up` -- Start Pinecone, Redis, and app locally

12. Security-Focused Project (OWASP Compliance)

# {Project Name}

Security-critical application. All code must follow OWASP Top 10 (2025 edition) guidelines.
Node.js with Express. TypeScript strict mode. PostgreSQL via Prisma.
Auth: OAuth 2.0 + PKCE. Sessions: server-side with Redis. Audit: complete activity logging.

## Security Architecture

- All inputs validated at the edge (middleware) using Zod schemas. No unvalidated data reaches business logic.
- SQL injection prevention: Prisma ORM only. `$queryRaw` requires parameterized queries (tagged templates). No string concatenation in SQL.
- XSS prevention: all HTML output escaped by default. CSP headers enforced. No `innerHTML` anywhere.
- CSRF: all state-changing requests require CSRF token. SameSite cookie policy: Strict.
- Rate limiting: all public endpoints have rate limits (express-rate-limit). Auth endpoints: 5 attempts per 15 minutes per IP.
- Encryption: all PII encrypted at rest (AES-256-GCM). TLS 1.3 minimum for transit.

## Audit Trail Rules

- Every data mutation (create, update, delete) must log: who, what, when, old value, new value.
- Audit logs are append-only. No update or delete operations on the audit table.
- Audit log retention: 7 years. Separate database/table with restricted access.
- Failed authentication attempts log: IP, user agent, timestamp, attempted identifier.

## Coding Standards

- All dependencies must be pinned to exact versions. Run `npm audit` weekly. Zero critical/high vulnerabilities allowed.
- Secrets: only accessed through the secrets management module (`lib/secrets.ts`). Never through `process.env` directly.
- Password hashing: `argon2id` with minimum parameters: memory 64MB, iterations 3, parallelism 1.
- Session tokens: 256-bit cryptographically random. Rotate on privilege escalation. 30-minute idle timeout, 8-hour absolute timeout.
- All HTTP responses include: `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security`, `Content-Security-Policy`.

## Forbidden Patterns

- NEVER use `eval()`, `Function()`, or `vm.runInNewContext()`.
- NEVER log PII (emails, names, addresses) or secrets. Mask or hash before logging.
- NEVER use `MD5` or `SHA-1` for any security purpose. Minimum: SHA-256.
- NEVER disable HTTPS in any environment, including development.
- NEVER use `cors({ origin: '*' })` in production.
- NEVER store tokens in localStorage. Use httpOnly, secure, SameSite=Strict cookies.

## Commands

- `pnpm dev` -- Start dev server (HTTPS via mkcert)
- `pnpm test` -- Run tests
- `pnpm audit` -- Run npm audit + custom security checks
- `pnpm lint:security` -- ESLint security plugin scan
- `pnpm owasp:check` -- Run OWASP dependency check

13. Open Source Library (Contributor Guidelines)

# {Project Name}

Open source TypeScript library published to npm.
Supports: Node.js 18+, Bun, Deno, modern browsers (via ESM).
Build: tsup (ESM + CJS dual output). Test: Vitest. Docs: TypeDoc.
License: MIT.

## Contributing Standards

- All PRs must target `main` branch. No direct commits to `main`.
- Every PR needs: description of change, test coverage, documentation update if API changed.
- Commit messages follow Conventional Commits: `feat:`, `fix:`, `docs:`, `chore:`, `breaking:`.
- Breaking changes require a migration guide in `MIGRATION.md` and `breaking:` commit prefix.
- All CI checks must pass before merge: tests, lint, type check, build, bundle size check.

## Architecture Rules

- Public API is defined exclusively in `src/index.ts`. Internal modules are not accessible to consumers.
- Zero runtime dependencies. If a utility is needed, implement it or use a build-time-only dependency.
- Tree-shakeable: all exports are named exports. No side effects in module scope.
- Support both ESM (`import`) and CJS (`require`). tsup handles dual output.
- Minimum test coverage: 95% line coverage, 90% branch coverage.

## Coding Standards

- TypeScript strict mode with `noUncheckedIndexedAccess: true`.
- All public functions and types have JSDoc comments with `@example` blocks.
- Generic type parameters: single uppercase letter only for simple cases (`T`, `K`, `V`). Descriptive names for complex cases (`TInput`, `TOutput`).
- Error handling: throw typed errors extending a base library error class. Never throw strings.
- Performance-sensitive code includes benchmarks in `benchmarks/` using `vitest bench`.

## Forbidden Patterns

- NEVER add a runtime dependency. Bundle size is a first-class concern.
- NEVER use `any` in public API types. Internal `any` requires a comment justifying why.
- NEVER use Node.js-specific APIs in core library code. Use `src/node/` for Node-specific adapters.
- NEVER merge a PR that increases bundle size by more than 1KB without explicit approval.
- NEVER use default exports. Named exports only.

## Commands

- `pnpm dev` -- Watch mode
- `pnpm build` -- Build with tsup
- `pnpm test` -- Run Vitest
- `pnpm test:coverage` -- Coverage report
- `pnpm lint` -- ESLint
- `pnpm typecheck` -- TypeScript type checking
- `pnpm size` -- Check bundle size
- `pnpm docs` -- Generate TypeDoc documentation
- `pnpm release` -- Changeset publish to npm

14. Technical Documentation Site

# {Project Name} Documentation

Documentation site built with Astro + Starlight.
Content: MDX files in `src/content/docs/`. Search: Pagefind (static).
Deployed on Cloudflare Pages. Versioned docs supported.

## Content Architecture

- Every doc page lives in `src/content/docs/{section}/{page}.mdx`.
- Sections map to sidebar groups. Ordering controlled by numeric prefix: `01-getting-started/`, `02-guides/`.
- Code examples must be real, runnable code. Test them in `examples/` directory and reference via import.
- API reference pages are auto-generated from source code JSDoc comments. Do not hand-write API docs.
- Every page has frontmatter: `title`, `description`, `sidebar.order`, and `lastUpdated`.

## Writing Standards

- Second person ("you") for tutorials. Third person for reference docs.
- One concept per page. If a page covers two distinct topics, split it.
- Code blocks must specify the language for syntax highlighting. Include file paths in code block titles.
- Every code example must be self-contained. No "assuming you have X set up already" without linking to the setup page.
- Diagrams: use Mermaid syntax in MDX. No external image files for architecture diagrams.

## Forbidden Patterns

- NEVER write "simply" or "just" -- these words dismiss complexity for beginners.
- NEVER show code without explaining what it does. Minimum: one sentence before every code block.
- NEVER link to external URLs without `rel="noopener"`. Internal links use relative paths.
- NEVER use screenshots of code. Use actual code blocks.
- NEVER leave TODO comments in published docs. Either write the content or omit the section.

## Commands

- `pnpm dev` -- Start Astro dev server
- `pnpm build` -- Production build with Pagefind indexing
- `pnpm preview` -- Preview production build locally
- `pnpm check` -- Astro check (broken links, missing images)
- `pnpm test:examples` -- Run all code examples to verify they work

15. Mobile App (SwiftUI / iOS)

# {Project Name}

iOS application built with SwiftUI. Minimum deployment target: iOS 17.
Architecture: MVVM with Observation framework (@Observable).
Networking: URLSession with async/await. Persistence: SwiftData.
CI: Xcode Cloud. Distribution: TestFlight -> App Store Connect.

## Architecture Rules

- Views in `Views/`, ViewModels in `ViewModels/`, Models in `Models/`, Services in `Services/`.
- Every screen has a ViewModel annotated with `@Observable`. Views never contain business logic or network calls.
- Navigation: `NavigationStack` with typed `NavigationPath`. No `NavigationLink(destination:)` -- use value-based navigation.
- Network layer: one `APIClient` service with generic `request<T: Decodable>()` method. No URLSession calls in ViewModels.
- Error handling: all async operations use Swift's typed throws. Display user-facing errors via a shared `ErrorHandler` service.

## Coding Standards

- Swift strict concurrency checking enabled. All sendable boundaries enforced.
- SwiftUI previews required for every view. Previews must use mock data from `Mocks/`.
- Access control: default to `private`. Use `internal` for package access. `public` only for framework targets.
- Naming: follow Swift API Design Guidelines. Boolean properties read as assertions (`isLoading`, `hasContent`).
- All strings use `String(localized:)` for localization. No hardcoded user-facing strings.

## Forbidden Patterns

- NEVER use `force unwrap` (`!`) outside of tests and IB outlets. Use `guard let` or `if let`.
- NEVER use UIKit in new code unless SwiftUI has no equivalent API.
- NEVER store secrets in the app bundle. Use server-side configuration or Keychain.
- NEVER use `@StateObject` or `@ObservedObject` -- use `@State` with `@Observable` classes (iOS 17+).
- NEVER use `DispatchQueue` directly. Use Swift Concurrency (async/await, TaskGroup).

## Commands

- `xcodebuild -scheme {App} -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 16' build` -- Build
- `xcodebuild test -scheme {App} -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 16'` -- Run tests
- `swift build` -- Build Swift package targets
- `swiftlint` -- Lint
- `swiftformat .` -- Format

Team Pattern Templates

16. Junior Developer Guardrails

# {Project Name} -- Developer Guardrails

This CLAUDE.md enforces safety rails for junior developers learning the codebase.
Claude Code should guide, explain, and prevent common mistakes rather than silently fix them.

## Behavior Rules

- When making a change, ALWAYS explain WHY the change is needed, not just WHAT changed. Add a brief comment or explanation in the response.
- When a requested change would violate a best practice, DO NOT silently refuse. Explain the issue, show the problematic pattern, show the correct pattern, and ask for confirmation before proceeding.
- When generating new code, add inline comments explaining non-obvious logic. Target: one comment per 10-15 lines.
- When fixing a bug, explain the root cause before showing the fix. Trace the issue back to its source.

## Escalation Triggers

If the user asks to do any of the following, explain the risk and suggest the safe alternative:
- Delete a database migration
- Force push to any branch
- Disable TypeScript strict mode or ESLint rules
- Add `any` type to bypass a type error
- Skip writing tests for new functionality
- Use `sudo` in any command
- Modify CI/CD configuration
- Change environment variables in production

## Code Quality Gates

- Every new function MUST have at least one test. Suggest the test file location and a starter test.
- Every PR-worthy change should be accompanied by a clear commit message suggestion following Conventional Commits.
- If a function exceeds 30 lines, suggest extracting helper functions.
- If a file exceeds 300 lines, suggest splitting into modules.

## Learning Resources

When explaining a concept, link to these resources when relevant:
- TypeScript: https://www.typescriptlang.org/docs/
- React: https://react.dev/learn
- Testing: https://testing-library.com/docs/
- Git: https://ohshitgit.com/

17. Code Review Enforcement

# {Project Name} -- Code Review Standards

Claude Code operates as a code review enforcer. All generated code must meet review-ready quality.

## Pre-Commit Checklist

Before suggesting any commit, verify ALL of the following:
1. All tests pass (`pnpm test`)
2. Lint passes with zero warnings (`pnpm lint`)
3. TypeScript compiles with zero errors (`pnpm typecheck`)
4. No `console.log` statements outside of debug utilities
5. No commented-out code
6. No TODO comments without a linked issue (format: `// TODO(#123): description`)
7. All new functions have JSDoc comments
8. All new files have a module-level doc comment explaining purpose

## Review Standards

- **Naming**: variable names describe what, function names describe action. Minimum 3 characters (no `x`, `d`, `cb` -- use `index`, `data`, `callback`).
- **Function size**: max 40 lines. If longer, must be justified or refactored.
- **File size**: max 400 lines. Suggest split if approaching limit.
- **Nesting depth**: max 3 levels of nesting. Extract early returns or helper functions.
- **Magic numbers**: no numeric literals except 0, 1, -1. Extract to named constants.
- **Error messages**: all user-facing errors must be actionable ("Failed to save: check network connection" not "Error").

## PR Description Template

When preparing changes for a PR, generate a description following this format:

What

[One sentence describing the change]

Why

[Business context or technical reason]

How

[Implementation approach, max 3 bullet points]

Testing

[What was tested and how]

Screenshots

[If UI changes, describe what would be shown]


## Merge Blockers

These issues MUST be resolved before any merge suggestion:
- Failing tests
- TypeScript errors
- Security vulnerabilities in new dependencies
- Breaking changes without migration path
- Missing documentation for public API changes

18. Strict TypeScript (Zero Escape Hatches)

# {Project Name} -- Strict TypeScript

Zero-tolerance TypeScript configuration. No type safety escape hatches permitted.

## TypeScript Configuration

The project uses the strictest possible TypeScript configuration:

{ "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noFallthroughCasesInSwitch": true, "forceConsistentCasingInFileNames": true, "exactOptionalPropertyTypes": true, "verbatimModuleSyntax": true } }


## Type Rules

- `any` is banned. Use `unknown` and narrow with type guards. If you think you need `any`, you need a generic instead.
- `as` type assertions are banned except for: `as const` and DOM element casting (`as HTMLInputElement`) after a null check.
- `// @ts-ignore` and `// @ts-expect-error` are banned. Fix the type error, do not suppress it.
- `!` non-null assertion is banned. Use optional chaining or explicit null checks.
- All function return types must be explicit. No inferred return types on exported functions.
- Union types exceeding 5 members must be extracted to a named type alias.

## Utility Type Standards

- Prefer `Pick<T, K>` and `Omit<T, K>` over redefining subsets of existing types.
- Use `Readonly<T>` for function parameters that should not be mutated.
- Use `Record<string, T>` instead of `{ [key: string]: T }`.
- Discriminated unions must use a `type` or `kind` field as the discriminator.
- Zod schemas are the source of truth for runtime validation. Infer TypeScript types from Zod: `z.infer<typeof schema>`.

## Forbidden Patterns

- NEVER use `any`. No exceptions. This is the core rule.
- NEVER use `Object`, `Function`, or `{}` as types. Use specific types.
- NEVER use `String`, `Number`, `Boolean` (uppercase). Use `string`, `number`, `boolean`.
- NEVER cast through `unknown` to bypass type checking (`x as unknown as TargetType`).
- NEVER use `interface` for objects that need to be composed. Use `type` for unions and intersections, `interface` for class shapes and declaration merging only.

19. Legacy Codebase Migration

# {Project Name} -- Legacy Migration

Brownfield project. Migrating from JavaScript to TypeScript, from Express to Fastify, from Mongoose to Prisma.
Migration is incremental -- old and new code coexist. Do NOT rewrite everything at once.

## Migration Strategy

- New files: TypeScript only (`.ts`). No new `.js` files.
- Existing files: migrate to TypeScript when you touch them for a feature or bug fix. Do not migrate files solely for the sake of migration.
- Express routes being modified get migrated to Fastify. Untouched Express routes stay until their module is scheduled.
- Mongoose models being modified get a parallel Prisma model. Once all routes using a model are migrated, remove the Mongoose version.
- Test files: migrate to Vitest when their source file is migrated. Keep Jest config until all tests are ported.

## Compatibility Rules

- Old Express middleware must work alongside new Fastify routes. The gateway layer handles routing to the correct framework.
- TypeScript files can import from JavaScript files using allowJs. JavaScript files must not import from TypeScript files.
- Both Mongoose and Prisma can coexist. They connect to the same database. Migration scripts handle schema sync.
- Feature flags (in `config/features.ts`) control which code path is active. New code is behind flags until verified.

## File Naming

- Migrated files: rename `.js` to `.ts` (or `.jsx` to `.tsx`).
- If a file has both old and new versions during migration: `user.service.js` (old) and `user.service.ts` (new). The feature flag determines which is loaded.
- Migration tracking: `MIGRATION_STATUS.md` at root tracks which modules have been migrated.

## Forbidden Patterns

- NEVER delete old code without verifying the new version handles all edge cases. Run the old test suite against both implementations.
- NEVER migrate and add features in the same PR. One PR for migration, separate PR for new functionality.
- NEVER remove a Mongoose model until ALL routes and services using it have been migrated to Prisma.
- NEVER use `require()` in new TypeScript files. Use ESM `import` syntax.
- NEVER skip writing tests during migration. If the old code lacks tests, write them BEFORE migrating.

## Commands

- `pnpm dev` -- Start both Express and Fastify servers (gateway routes between them)
- `pnpm test` -- Run both Jest (old) and Vitest (new) test suites
- `pnpm test:old` -- Jest only
- `pnpm test:new` -- Vitest only
- `pnpm migrate:check` -- Show migration status dashboard
- `pnpm typecheck` -- TypeScript check (may have expected errors in allowJs files)

20. Multi-Language Polyglot Repo

# {Project Name} -- Polyglot Repository

Multi-language repository containing services and libraries in Go, TypeScript, Python, and Rust.
Unified build system: Earthly (Earthfile). CI: GitHub Actions.
Each language follows its own ecosystem conventions, but shared standards apply across all.

## Repository Structure

services/ api-gateway/ -- Go (Gin) web-app/ -- TypeScript (Next.js) ml-pipeline/ -- Python (FastAPI) indexer/ -- Rust packages/ proto/ -- Protobuf definitions (shared) sdk-ts/ -- TypeScript SDK sdk-python/ -- Python SDK sdk-go/ -- Go SDK tools/ -- Internal CLI tools (Go) earthly/ -- Shared Earthly targets


## Universal Rules (All Languages)

- Every service and package has a README with: purpose, setup instructions, test command, and deploy command.
- All services expose OpenTelemetry traces. No custom tracing implementations.
- All services read config from environment variables. No language-specific config files in production.
- Error responses follow a unified shape across all services: `{ "error": { "code": "NOT_FOUND", "message": "..." } }`.
- Protobuf is the contract between services. Changes to `.proto` files require SDK regeneration in all languages.

## Language-Specific Standards

### Go
- Follow `gofmt` and `golangci-lint` with the `.golangci.yml` config at root.
- Error handling: wrap with `fmt.Errorf("context: %w", err)`. No bare `if err != nil { return err }`.
- Use `slog` for structured logging. No `fmt.Println` or `log.Println`.

### TypeScript
- Strict mode. No `any`. Formatting: Prettier. Linting: ESLint with the shared config.
- Use `pnpm` for package management. Lock file must be committed.

### Python
- Python 3.12+. Type hints required. Formatting: Ruff (replaces Black + isort).
- Use `uv` for package management. `pyproject.toml` for all configuration.

### Rust
- MSRV: 1.78. `cargo fmt` + `cargo clippy` must pass. No `unsafe` without `SAFETY` comment.

## Forbidden Patterns

- NEVER mix language-specific tooling into another language's build pipeline.
- NEVER duplicate business logic across languages. Shared logic goes in protobuf definitions or a single source-of-truth service.
- NEVER use language-specific serialization (pickle, gob) for cross-service communication. Use protobuf or JSON.
- NEVER add a `.proto` field without updating ALL SDK packages.
- NEVER use `latest` tags for any base Docker image. Pin to specific digests.

## Commands

- `earthly +build` -- Build everything
- `earthly +test` -- Test everything
- `earthly +lint` -- Lint all languages
- `earthly +build --SERVICE=api-gateway` -- Build specific service
- `earthly +proto` -- Regenerate protobuf stubs for all languages
- `docker compose up` -- Start all services locally

Common Mistakes: 5 Anti-Patterns to Avoid

Even with a template as a starting point, CLAUDE.md files can go wrong. These are the five most common anti-patterns observed across real projects in 2026.

1. The Novel

Writing a 2,000-line CLAUDE.md that reads like a technical specification document. Claude Code processes roughly 150-200 instructions effectively. Beyond that, it begins deprioritizing instructions that appear later in the file. The fix: treat CLAUDE.md like a tweet thread, not an RFC. Every line should be a direct instruction, not a discussion. Move background context to a separate ARCHITECTURE.md and reference it.

2. The Vague Manifesto

Instructions like "write clean code" or "follow best practices" or "use modern patterns." These are meaningless to an AI model because they do not contain actionable specifics. Instead of "follow best practices for error handling," write "all async functions must use try/catch, log the error with structlog, and return a typed error response." Specificity is everything.

3. The Contradiction Machine

Conflicting instructions that appear in different sections. A common example: the coding standards section says "use named exports" while a workflow section shows example code with default exports. Claude Code will follow one and violate the other, leading to inconsistent output. Review the entire file for contradictions before committing it.

4. The Stale Fossil

A CLAUDE.md that was written once and never updated. The project has migrated from Jest to Vitest, from Pages Router to App Router, from npm to pnpm -- but the CLAUDE.md still references the old stack. Claude Code will follow the outdated instructions faithfully, generating code for a stack that no longer exists. Add a last_reviewed date to the frontmatter and schedule quarterly reviews.

5. The Kitchen Sink

Including instructions for every possible scenario the team might encounter. A CLAUDE.md for a frontend project does not need Docker orchestration rules, ML pipeline conventions, or mobile app accessibility guidelines. Scope the instructions to what the project actually is. For multi-concern projects, use subdirectory CLAUDE.md files to scope instructions to relevant modules.


CLAUDE.md + Skills + MCP: How They Work Together

CLAUDE.md is one piece of a three-part system that controls how Claude Code behaves in a project. Understanding how all three interact prevents duplication and unlocks more powerful workflows.

CLAUDE.md defines the rules -- what Claude Code should and should not do in this specific project. It is static, declarative, and read at session start.

Skills define reusable capabilities -- multi-step workflows that Claude Code can execute on demand. A skill for "deploy to staging" or "run the full test pipeline" encapsulates complex procedures that CLAUDE.md can reference but should not inline. Learn how to build custom skills that integrate with project instructions.

MCP servers define external connections -- database access, API integrations, image generation, deployment platforms. CLAUDE.md tells Claude Code which MCP servers are available and when to use them.

Here is how they compose in practice:

# In CLAUDE.md

## Available Skills
- `deploy` -- Handles staging and production deployment via the deploy skill in `.claude/skills/`
- `db-migrate` -- Runs database migrations with safety checks

## MCP Servers
- Supabase MCP is available for database operations. Use it for schema changes and data queries.
- Vercel MCP is available for deployment. Always deploy to preview first.

## Workflow
When asked to deploy:
1. Run the `deploy` skill
2. The skill uses Vercel MCP to create a preview deployment
3. Share the preview URL for approval before promoting to production

This separation keeps CLAUDE.md focused on rules, skills focused on procedures, and MCP focused on connections. Each piece is independently updatable without breaking the others.

Hooks add a fourth layer -- automated triggers that enforce CLAUDE.md rules without relying on Claude Code to remember them. A PreToolUse hook can block forbidden patterns at the tool level, creating a hard enforcement layer on top of the soft instruction layer in CLAUDE.md.

For a full directory of available skills and MCP integrations, visit the Skiln skills directory or browse all tools.


Frequently Asked Questions

Where should CLAUDE.md be placed in a project?

Place the primary CLAUDE.md in the project root directory. Claude Code automatically discovers and reads it at session start. For large projects with distinct modules, add subdirectory CLAUDE.md files (e.g., src/api/CLAUDE.md) that contain module-specific instructions. Root-level instructions apply globally, and subdirectory instructions add or override rules for that scope.

How long should a CLAUDE.md file be?

Between 50 and 150 instructions is the effective range. Claude Code can process approximately 150-200 discrete instructions before lower-priority items get deprioritized. A typical effective CLAUDE.md runs 80-200 lines of markdown. If the file exceeds 300 lines, split concerns into subdirectory files or move reference documentation to separate files that CLAUDE.md points to.

Can CLAUDE.md override Claude Code's built-in behavior?

Yes, within the bounds of safety. CLAUDE.md instructions override Claude Code's default patterns for code style, architecture, and workflow. For example, Claude Code defaults to suggesting TypeScript when it detects a TypeScript project, but CLAUDE.md can instruct it to use a specific TypeScript configuration, import ordering, or component pattern. CLAUDE.md cannot override core safety behaviors like refusing to generate malicious code.

Does CLAUDE.md work with Claude Code on all plans?

CLAUDE.md is supported on all Claude Code plans, including the free tier. The file is read as part of the session context, and there are no plan-specific limitations on its content or length. Teams on paid plans benefit from larger context windows, which means longer CLAUDE.md files are processed more reliably.

How often should CLAUDE.md be updated?

Review CLAUDE.md whenever the project's stack, conventions, or team composition changes. Common triggers include: migrating frameworks, adding a new team member with different conventions, upgrading major dependencies, or changing deployment targets. A good practice is to add a last_reviewed comment at the top and update it quarterly.

Can multiple team members have different CLAUDE.md preferences?

Yes. Each developer can have a personal CLAUDE.md at ~/.claude/CLAUDE.md that applies across all projects. Personal files are good for editor preferences, commit message style, and explanation verbosity. Project-level CLAUDE.md handles shared standards. When personal and project instructions conflict, project instructions take precedence for that project's sessions.

What is the difference between CLAUDE.md and .cursorrules or .github/copilot-instructions.md?

CLAUDE.md is specific to Claude Code and its agent architecture. Unlike .cursorrules (Cursor) or .github/copilot-instructions.md (GitHub Copilot), CLAUDE.md can reference skills, MCP servers, and hooks -- creating a full behavioral system rather than just prompt injection. The instruction format is also more structured, supporting hierarchical file placement and scope inheritance.

Can CLAUDE.md include code examples?

Yes, and it should. Code examples in CLAUDE.md serve as pattern templates that Claude Code will follow when generating new code. A brief example of the preferred component pattern, API route structure, or test format is worth more than a paragraph of description. Keep examples short (5-15 lines) and representative of the most common patterns in the project.



Back to Blog

Frequently Asked Questions

Where should CLAUDE.md be placed in a project?
Place the primary CLAUDE.md in the project root directory. Claude Code automatically discovers and reads it at session start. For large projects with distinct modules, add subdirectory CLAUDE.md files that contain module-specific instructions.
How long should a CLAUDE.md file be?
Between 50 and 150 instructions is the effective range. Claude Code can process approximately 150-200 discrete instructions before lower-priority items get deprioritized. A typical effective CLAUDE.md runs 80-200 lines of markdown.
Can CLAUDE.md override Claude Code's built-in behavior?
Yes, within the bounds of safety. CLAUDE.md instructions override Claude Code's default patterns for code style, architecture, and workflow. CLAUDE.md cannot override core safety behaviors like refusing to generate malicious code.
Does CLAUDE.md work with Claude Code on all plans?
CLAUDE.md is supported on all Claude Code plans, including the free tier. The file is read as part of the session context, and there are no plan-specific limitations on its content or length.
How often should CLAUDE.md be updated?
Review CLAUDE.md whenever the project's stack, conventions, or team composition changes. A good practice is to add a last_reviewed comment at the top and update it quarterly.
Can multiple team members have different CLAUDE.md preferences?
Yes. Each developer can have a personal CLAUDE.md at ~/.claude/CLAUDE.md that applies across all projects. When personal and project instructions conflict, project instructions take precedence.
What is the difference between CLAUDE.md and .cursorrules or .github/copilot-instructions.md?
CLAUDE.md is specific to Claude Code and its agent architecture. Unlike .cursorrules or copilot-instructions.md, CLAUDE.md can reference skills, MCP servers, and hooks, creating a full behavioral system rather than just prompt injection.
Can CLAUDE.md include code examples?
Yes, and it should. Code examples in CLAUDE.md serve as pattern templates that Claude Code will follow when generating new code. Keep examples short (5-15 lines) and representative of the most common patterns in the project.

Stay in the Loop

Join 1,000+ developers. Get the best new Skills & MCPs weekly.

No spam. Unsubscribe anytime.