How to Write a CLAUDE.md File: 13 Copy-Paste Templates

I spent three hours last Tuesday watching Claude Code rewrite a perfectly good React hook as a class component, and it was the fourth time that week. Every session started the same way: I re-explained my project structure, reminded the agent to use pnpm instead of npm, and then corrected its test commands. Fifteen minutes gone before any real work even started.

So I sat down and wrote a CLAUDE.md file. The whole thing took about ten minutes. And from that very next session, the corrections stopped completely. Claude read my rules once at the start, then followed them without me repeating a single thing. This guide walks you through how to write your own, with copy-ready examples for React, Next.js, Python, Java, Kotlin, C++, Swift, Android, iOS, frontend, backend, web development, and full web apps.

What Is a Claude.md File and Why Does It Matter?

CLAUDE.md file is a plain markdown document that tells Claude Code how your project works. You drop it in your project root, and Claude reads it at the start of every session. It picks up your tech stack, your coding rules, and your build commands before you type a single prompt. Without one, Claude starts every session blank.

Now, this matters because of how large language models actually work. Their training is frozen. They do not remember your last session. The only way Claude knows anything about your project is through the tokens in its context window, and CLAUDE.md is the one file that shows up in every single conversation.

So a good one saves you real time and produces better code right away. But a bloated or vague one wastes tokens and gets ignored. The difference comes down to a few clear principles.

How Does Claude Code Read Your CLAUDE.md?

Claude Code loads the contents of your CLAUDE.md into a system reminder at the start of each session. But here is the part that catches people off guard: Claude Code wraps your file with a note telling the model that the context “may or may not be relevant” and to skip it if it does not apply to the current task.

So if you pack unrelated content into the file, Claude is more likely to ignore everything, including the rules you actually need it to follow. That is exactly why keeping the file short and focused matters so much.

What Should a Claude.md File Include?

A good CLAUDE.md answers three questions about your project. These three questions form the backbone of every example in this guide.

  • WHAT: Your tech stack, project structure, and a quick map of where things live. This matters a lot in monorepos where Claude needs to know which folder holds which app or package.
  • WHY: The purpose of the project and what each major part does. Even a one-sentence description helps Claude make better decisions about naming and scope.
  • HOW: The exact commands to build, test, lint, and run the project. If you use bun instead of npm, say so. If your test command is pytest -x --tb=short, put it here. Claude cannot guess these.

That covers the foundation. Now, what should you leave out?

Five Rules for Writing a Good Claude.md

These five rules form the foundation of every strong configuration file.

Keep It Short

Research on instruction-following shows that frontier thinking models can reliably follow about 150 to 200 instructions. But Claude Code’s own system prompt already uses roughly 50 of those, so you are left with about 100 to 150 before performance starts to drop.

The general rule is to keep your CLAUDE.md under 300 lines, and shorter is better. HumanLayer, one of the teams that studied this closely, keeps their root CLAUDE.md under sixty lines. Every extra line competes with the lines that actually matter.

Make Every Line Universally Applicable

This file loads in every session, so every instruction should apply to every task you give Claude. Do not put database schema instructions in the same file that covers frontend styling. Those instructions just become noise when you are working on something unrelated.

A good test for every line in your CLAUDE.md: “If I remove this, will Claude make a mistake on most tasks?” If the answer is no, move it out.

When a line fails that test, move it to a separate doc file and point to it from your CLAUDE.md instead. Claude still finds it when it needs it, but the root file stays lean.

Use Progressive Disclosure

Not every instruction belongs in the root file. For project-specific rules that only apply to some tasks, create separate markdown files in a docs folder:

agent_docs/
  |- building_the_project.md
  |- running_tests.md
  |- code_conventions.md
  |- database_schema.md

Then list these files in your CLAUDE.md with a one-line description of each, and tell Claude to read the right one before starting work. This way, Claude pulls in extra context only when it needs it. Your base file stays clean.

Do Not Use Claude as a Linter

One of the most common mistakes is stuffing code style guidelines into CLAUDE.md. Linters and formatters already do this job, and they do it faster, cheaper, and more reliably than any language model. So do not waste context window space on rules that a tool can enforce on its own.

If you still need Claude to follow specific formatting, set up a Claude Code Stop hook that runs your formatter and linter after each edit. Let the tools catch formatting issues. Let Claude focus on logic.

Write It by Hand

Both Claude Code and other tools offer auto-generation commands like /init. Skip them. Auto-generated files tend to be bloated, generic, and full of instructions that sound right but do not match your actual project. And because CLAUDE.md affects every session, every plan, and every line of code Claude writes, a single bad instruction here multiplies into many bad outputs elsewhere. Write it yourself.

CLAUDE.md vs AGENTS.md: Which One Should You Use?

Claude md vs Agent md

AGENTS.md is the open-standard version of CLAUDE.md. It works across multiple AI coding tools, including Cursor, Aider, Windsurf, Copilot, and Claude Code. So if your team uses more than one tool, AGENTS.md lets you keep a single set of instructions instead of separate config files for each one.

Claude Code reads both files. If you only use Claude Code, stick with CLAUDE.md. But if you want portability across tools, go with AGENTS.md. The structure and best practices are the same for both.

Where to Place Your CLAUDE.md Files?

Claude Code supports three levels of configuration. Each one serves a different purpose.

  • Global (~/.claude/CLAUDE.md): Personal preferences that apply to every project. Good for things like “prefer pnpm” or “use British English” or “always explain trade-offs before large changes.”
  • Project root (./CLAUDE.md): Team and project standards. This is where build commands, architecture maps, and dependency rules go. Check this into version control so the whole team shares the same instructions.
  • Subfolder (./packages/api/CLAUDE.md): Module-specific rules for large projects or monorepos. Claude reads the nearest CLAUDE.md when working in a subfolder, so you can keep backend rules separate from frontend rules without bloating the root file.

How to Write a Claude.md for Different Types of Projects?

Every stack has its own quirks and requirements. Here are complete, copy-ready examples for the most common development environments.

Claude.md Example for React Projects

# Project: TaskBoard UI
## Overview
A React 19 task management dashboard for small teams. Optimizes for fast rendering and accessibility.
## Tech Stack
- React 19 with TypeScript (strict mode)
- Vite 6 for bundling
- React Router v7
- Zustand for state management
- Vitest + React Testing Library for tests
## Project Structure
- /src/components -- reusable UI components
- /src/pages -- route-level page components
- /src/hooks -- custom React hooks
- /src/stores -- Zustand stores
- /src/utils -- helper functions
## Commands
- Dev server: `npm run dev`
- Run tests: `npx vitest run`
- Lint: `npm run lint`
- Type check: `npx tsc --noEmit`
## Rules
- Use functional components only. No class components.
- Keep components under 150 lines. Split into smaller components if needed.
- Use named exports, not default exports.
- All props must have TypeScript interfaces defined.
- Run type check before finishing any task.

Claude.md Example for Next.js Projects

# Project: MarketplaceApp
## Overview
A Next.js 15 e-commerce marketplace with server-side rendering. Optimizes for SEO and page load speed.
## Tech Stack
- Next.js 15 (App Router)
- TypeScript strict mode
- Tailwind CSS v4
- Prisma ORM with PostgreSQL
- NextAuth.js v5 for authentication
## Project Structure
- /app -- App Router pages and layouts
- /app/api -- API route handlers
- /components -- shared UI components
- /lib -- database client, auth config, utilities
- /prisma -- schema and migrations
## Commands
- Dev server: `npm run dev`
- Build: `npm run build`
- Database migrate: `npx prisma migrate dev`
- Generate Prisma client: `npx prisma generate`
- Run tests: `npx vitest run`
## Rules
- Prefer Server Components. Use "use client" only when the component needs browser APIs, state, or event handlers.
- All database access goes through /lib/db.ts. Never import Prisma directly in components.
- API routes return consistent JSON shape: { data, error, status }.
- Use Zod for all request validation.
- Keep page components thin. Business logic goes in /lib.

Claude.md Example for Python Projects

# Project: DataPipelineService
## Overview
A Python data processing service that ingests CSV and JSON files, transforms them, and loads results into PostgreSQL. Runs as a scheduled job on AWS Lambda.
## Tech Stack
- Python 3.12
- Poetry for dependency management
- FastAPI for the HTTP layer
- SQLAlchemy 2.0 with async support
- Alembic for database migrations
- Pytest for testing
## Project Structure
- /src/api -- FastAPI route handlers
- /src/services -- business logic
- /src/models -- SQLAlchemy models
- /src/repositories -- database access layer
- /src/schemas -- Pydantic request/response schemas
- /tests -- test files mirroring src structure
- /alembic -- migration scripts
## Commands
- Install deps: `poetry install`
- Run dev server: `poetry run uvicorn src.main:app --reload`
- Run tests: `poetry run pytest -x --tb=short`
- Lint: `poetry run ruff check .`
- Format: `poetry run ruff format .`
- New migration: `poetry run alembic revision --autogenerate -m "description"`
## Rules
- Type hints on every function signature. No exceptions.
- All database queries go through the repository layer, not in route handlers.
- Use async/await for all I/O operations.
- Write a test for every new endpoint and service function.
- Never use print() for logging. Use the configured logger from src/core/logging.py.

Claude.md Example for Java Projects

# Project: OrderManagementAPI
## Overview
A Spring Boot REST API for managing orders, inventory, and customer data. Serves a React frontend and a mobile app.
## Tech Stack
- Java 21
- Spring Boot 3.4
- Gradle (Kotlin DSL)
- Spring Data JPA with PostgreSQL
- Flyway for database migrations
- JUnit 5 + Mockito for testing
## Project Structure
- /src/main/java/com/app/controller -- REST controllers
- /src/main/java/com/app/service -- business logic
- /src/main/java/com/app/repository -- JPA repositories
- /src/main/java/com/app/model -- entity classes
- /src/main/java/com/app/dto -- request/response DTOs
- /src/main/java/com/app/config -- Spring configuration
- /src/test -- test files
## Commands
- Build: `./gradlew build`
- Run: `./gradlew bootRun`
- Test: `./gradlew test`
- Lint: `./gradlew checkstyleMain`
## Rules
- Follow the controller-service-repository pattern strictly. Controllers never touch repositories directly.
- Use records for DTOs when possible.
- Every public method in service classes must have a corresponding unit test.
- Use constructor injection, not field injection with @Autowired.
- Return ResponseEntity with proper HTTP status codes from controllers.
- Database column names use snake_case. Java field names use camelCase. Map with @Column annotations.

Claude.md Example for Kotlin Android Projects

# Project: FitTracker
## Overview
An Android fitness tracking app built with Kotlin and Jetpack Compose. Tracks workouts, displays progress charts, and syncs data with a REST API.
## Tech Stack
- Kotlin 2.0
- Jetpack Compose for UI
- Material 3 design system
- Hilt for dependency injection
- Room for local database
- Retrofit + OkHttp for networking
- Kotlin Coroutines + StateFlow for async and state
## Project Structure
- /app/src/main/java/com/fittracker/ui -- Compose screens and components
- /app/src/main/java/com/fittracker/viewmodel -- ViewModels
- /app/src/main/java/com/fittracker/data/local -- Room entities, DAOs, database
- /app/src/main/java/com/fittracker/data/remote -- Retrofit API interfaces
- /app/src/main/java/com/fittracker/data/repository -- repository implementations
- /app/src/main/java/com/fittracker/di -- Hilt modules
## Commands
- Build: `./gradlew assembleDebug`
- Run tests: `./gradlew testDebugUnitTest`
- Lint: `./gradlew lintDebug`
## Rules
- All UI is Jetpack Compose. No XML layouts.
- Use StateFlow for observable state in ViewModels. No LiveData.
- All network calls go through repository classes. ViewModels never call Retrofit directly.
- Use Hilt @Inject constructor for all dependencies.
- Use Timber for logging. Never use Log.d() or println() in production code.
- Navigation uses Compose Navigation with type-safe route arguments.

Claude.md Example for C++ Projects

# Project: SignalProcessor
## Overview
A real-time audio signal processing library written in C++23. Used as a shared library by desktop and embedded applications.
## Tech Stack
- C++23
- CMake 3.28+
- vcpkg for package management
- Google Test for unit testing
- clang-format and clang-tidy for code quality
## Project Structure
- /src -- implementation files (.cpp)
- /include/signal -- public headers (.hpp)
- /tests -- unit tests
- /benchmarks -- performance benchmarks
- /cmake -- custom CMake modules
## Commands
- Configure: `cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake`
- Build: `cmake --build build`
- Run tests: `cd build && ctest --output-on-failure`
- Format: `clang-format -i src/*.cpp include/signal/*.hpp`
## Rules
- Use RAII and smart pointers (std::unique_ptr, std::shared_ptr). No raw new/delete.
- All public APIs must have Doxygen-style documentation comments.
- Use std::span instead of raw pointer + size pairs for buffer parameters.
- Prefer constexpr and compile-time computation where possible.
- Error handling uses std::expected for recoverable errors and exceptions for programming errors.
- Keep header-only utilities in /include/signal/detail/ namespace.

Claude.md Example for Swift iOS Projects

# Project: MealPlanner
## Overview
An iOS meal planning app built with SwiftUI. Users create weekly meal plans, generate grocery lists, and save favorite recipes.
## Tech Stack
- Swift 6.0
- SwiftUI for all UI
- Swift Data for persistence
- Swift Concurrency (async/await, actors)
- Swift Package Manager for dependencies
## Project Structure
- /MealPlanner/Views -- SwiftUI views organized by feature
- /MealPlanner/Models -- Swift Data model classes
- /MealPlanner/Services -- networking and business logic
- /MealPlanner/ViewModels -- ObservableObject view models
- /MealPlanner/Utilities -- extensions and helpers
- /MealPlannerTests -- unit tests
## Commands
- Build: `xcodebuild -scheme MealPlanner -destination 'platform=iOS Simulator,name=iPhone 16' build`
- Test: `xcodebuild -scheme MealPlanner -destination 'platform=iOS Simulator,name=iPhone 16' test`
## Rules
- All UI is SwiftUI. No UIKit unless wrapping a component that has no SwiftUI equivalent.
- Use @Observable macro for view models (Swift 6 Observation framework).
- Use structured concurrency with async/await. No completion handlers.
- All network requests go through the NetworkService actor.
- Follow Apple Human Interface Guidelines for spacing, typography, and navigation patterns.
- Test all ViewModel logic. Views do not contain business logic.

Claude.md Example for Frontend Projects

# Project: DesignSystemUI
## Overview
A shared component library and design system for three web applications. Built as a standalone package published to a private npm registry.
## Tech Stack
- TypeScript strict mode
- React 19
- Storybook 8 for component documentation
- Vanilla Extract for type-safe CSS
- Vitest + Testing Library for tests
- Changesets for versioning
## Project Structure
- /src/components -- all shared components
- /src/tokens -- design tokens (colors, spacing, typography)
- /src/hooks -- shared React hooks
- /src/utils -- helper functions
- /stories -- Storybook stories
- /tests -- component tests
## Commands
- Dev (Storybook): `npm run storybook`
- Build: `npm run build`
- Test: `npx vitest run`
- Lint: `npm run lint`
- Type check: `npx tsc --noEmit`
## Rules
- Every component must have a Storybook story.
- Components accept a className prop for style overrides. No inline styles.
- All color values come from design tokens. No hardcoded hex values.
- Accessibility: every interactive element must have ARIA labels and keyboard support.
- Export all public types from the package root index.ts.

Claude.md Example for Backend Projects

# Project: PaymentsAPI
## Overview
A Node.js backend service handling payment processing, subscription management, and webhook events for a SaaS product.
## Tech Stack
- Node.js 22
- TypeScript strict mode
- Fastify 5 web framework
- Drizzle ORM with PostgreSQL
- Stripe SDK for payments
- Vitest for testing
- pnpm for package management
## Project Structure
- /src/routes -- Fastify route handlers
- /src/services -- business logic
- /src/db -- Drizzle schema, migrations, and queries
- /src/middleware -- auth, rate limiting, error handling
- /src/workers -- background job processors
- /src/types -- shared TypeScript types
## Commands
- Install: `pnpm install`
- Dev server: `pnpm dev`
- Build: `pnpm build`
- Test: `pnpm test`
- Migrate DB: `pnpm db:migrate`
- Generate types: `pnpm db:generate`
## Rules
- All route handlers validate input with Zod schemas before processing.
- Business logic lives in /src/services. Route handlers are thin.
- All Stripe webhook events must be verified with the signing secret before processing.
- Use database transactions for any operation that touches multiple tables.
- Sensitive config (API keys, secrets) comes from environment variables. Never hardcode them.
- Log with structured JSON using the configured Pino logger.

Claude.md Example for Web Development Projects

# Project: CraftPortfolio
## Overview
A multi-page portfolio and blog website for a freelance designer. Optimizes for performance, SEO, and visual quality.
## Tech Stack
- Astro 5 (static site generator)
- TypeScript
- Vanilla CSS with custom properties
- MDX for blog content
- Sharp for image optimization
## Project Structure
- /src/pages -- Astro page routes
- /src/layouts -- page layout templates
- /src/components -- reusable Astro and HTML components
- /src/content -- MDX blog posts and portfolio entries
- /src/styles -- global CSS and design tokens
- /public -- static assets (fonts, favicons, images)
## Commands
- Dev server: `npm run dev`
- Build: `npm run build`
- Preview build: `npm run preview`
## Rules
- Ship zero JavaScript to the client unless a component absolutely requires interactivity.
- All images use Astro's Image component for automatic optimization and lazy loading.
- CSS uses custom properties for colors, spacing, and typography. No utility-class frameworks.
- Every page must pass Lighthouse performance, accessibility, and SEO audits at 90+ scores.
- Blog posts use frontmatter for title, date, description, and tags.

Claude.md Example for Full Web App Projects

# Project: TeamSync
## Overview
A full-stack project management web app with real-time collaboration. Teams create projects, assign tasks, and communicate through threaded comments.
## Tech Stack
- Next.js 15 (App Router) for frontend and API
- TypeScript strict mode
- tRPC for type-safe API layer
- Prisma ORM with PostgreSQL
- NextAuth.js v5 with GitHub and Google OAuth
- Socket.io for real-time updates
- Tailwind CSS v4
## Project Structure (Monorepo with pnpm workspaces)
- /apps/web -- Next.js application
- /packages/db -- Prisma schema, client, and migrations
- /packages/api -- tRPC router definitions
- /packages/ui -- shared React components
- /packages/config -- shared ESLint and TypeScript configs
## Commands
- Install: `pnpm install`
- Dev (all packages): `pnpm dev`
- Build: `pnpm build`
- Test: `pnpm test`
- DB migrate: `pnpm --filter @teamsync/db migrate`
- DB seed: `pnpm --filter @teamsync/db seed`
## Rules
- All database queries go through tRPC procedures. No direct Prisma calls in components.
- Prefer Server Components. Mark with "use client" only for interactivity.
- Real-time events use the Socket.io client in /apps/web/lib/socket.ts only.
- Authentication checks happen in tRPC middleware, not in individual procedures.
- New features get a branch, a PR, and at least one test before merging.

Claude.md Example for Android Projects (Java)

# Project: CampusConnect
## Overview
An Android social networking app for university students. Built with Java and XML layouts following MVVM architecture. Connects students by interests, courses, and campus events.
## Tech Stack
- Java 17
- Android SDK 35 (min SDK 26)
- Gradle (Groovy DSL)
- MVVM with ViewModel and LiveData
- Retrofit 2 + Gson for networking
- Room for local database
- Dagger Hilt for dependency injection
## Project Structure
- /app/src/main/java/com/campusconnect/ui -- Activities, Fragments, Adapters
- /app/src/main/java/com/campusconnect/viewmodel -- ViewModels
- /app/src/main/java/com/campusconnect/model -- data models and Room entities
- /app/src/main/java/com/campusconnect/repository -- repository classes
- /app/src/main/java/com/campusconnect/network -- Retrofit interfaces and API client
- /app/src/main/res -- XML layouts, drawables, and resources
## Commands
- Build: `./gradlew assembleDebug`
- Run tests: `./gradlew testDebugUnitTest`
- Run instrumented tests: `./gradlew connectedDebugAndroidTest`
- Lint: `./gradlew lintDebug`
## Rules
- Follow MVVM strictly. Activities and Fragments observe LiveData. They do not call repository methods directly.
- Use ViewBinding for all layout references. No findViewById().
- All network calls go through repository classes with proper error handling.
- Room database operations run on background threads using Executors or coroutines.
- Use string resources for all user-facing text. No hardcoded strings in Java files.

Common Mistakes When Writing a Claude.md

The examples above all follow the same pattern. Most problems come from breaking that pattern in ways that are easy to spot once you know what to look for.

  • Dumping your entire README into the file. A README explains your project to humans browsing GitHub. A CLAUDE.md tells an agent how to work on your code. They serve different audiences, so they need different content. Keep the CLAUDE.md focused on actionable instructions.
  • Adding rules after a single mistake. Claude gave you a class component once, so you add “never use class components” to the file. But if it only happened once, it was not a pattern. Only add a rule when you see the same mistake show up across multiple sessions.
  • Including general coding advice. “Write clean, readable code” or “follow best practices” adds zero value. Claude already knows these things. These instructions just waste tokens and push your real rules further down in the context window.
  • Forgetting to update it. Your CLAUDE.md says you use React Router v6, but you migrated to v7 two months ago. Now Claude generates v6 patterns and you spend time fixing them. Treat the file as a living document, and update it when your stack changes.
  • I once spent twenty minutes debugging an issue that turned out to be a monorepo problem. Root-level rules about my Go backend were confusing Claude when it worked on the React frontend. The fix was simple: use subfolder CLAUDE.md files for module-specific rules and keep the root file focused on cross-cutting concerns.

How to Structure a Claude.md for Any Project

Every example in this guide follows the same skeleton. You can copy this template and fill in the details for your own project. It takes about ten minutes.

# Project: [Name]
## Overview
[One to two sentences: what the project does, who it serves, what it optimizes for.]
## Tech Stack
[Bulleted list of languages, frameworks, and key tools.]
## Project Structure
[Map of the main directories and what each one contains.]
## Commands
[Exact commands for dev, build, test, lint, format, and migrate.]
## Rules
[Five to ten project-specific coding rules that Claude needs to follow.]

This template works for every stack in this guide. Start with the five sections, fill in your specifics, and add or remove sections based on what your project actually needs. The goal is to give Claude just enough context to work on its own, and not a line more.

Frequently Asked Questions

Here are the most common questions developers ask when setting up their first configuration file.

How Long Should a Claude.md File Be?

Keep it under 300 lines. Many effective CLAUDE.md files are actually under 60 lines. Shorter files get followed more reliably, because instruction-following quality drops as the number of instructions grows. Every unnecessary line drags down all your other instructions too.

Can I Use CLAUDE.md With Other AI Coding Tools?

CLAUDE.md is specific to Claude Code. If you use Cursor, Aider, Windsurf, or other AI tools alongside Claude, go with AGENTS.md instead. It follows the same format but works across multiple tools. And Claude Code reads both files, so you do not lose anything by switching.

Should I Commit CLAUDE.md to Version Control?

Yes, and you should. The project-level CLAUDE.md belongs in your repository so every team member gets the same instructions. For personal preferences or local environment variables, use CLAUDE.local.md and add it to your .gitignore to keep it out of version control.

Does the Order of Sections in Claude.md Matter?

Yes, it does. LLMs pay more attention to instructions at the beginning and end of the context window. So your project overview and critical rules belong at the top. Put the less frequently needed details lower.

What if Claude Keeps Ignoring My Claude.md?

Nine times out of ten, the file is too long or the instructions do not match the current task. Claude Code’s system prompt actually tells the model to skip CLAUDE.md content that does not seem relevant. So trim the file down to only the rules that apply to every session, and move everything else into separate doc files you can point to. That one change fixes most cases.

Did This Fix Your Claude Code Setup?

Ten minutes of writing your CLAUDE.md saves you fifteen minutes of corrections in every session that follows.

Pick the example closest to your project from this guide, copy it, and fill in your own details. If you work across multiple AI coding tools, check our guide to AGENTS.md for setting up a single config that works everywhere.