How to Write the Perfect CLAUDE.md File (2026)
Maximize Claude Code effectiveness with a well-crafted CLAUDE.md
Start Building with Hypereal
Access Kling, Flux, Sora, Veo & more through a single API. Free credits to start, scale to millions.
No credit card required • 100k+ developers • Enterprise ready
How to Write the Perfect CLAUDE.md File in 2026
The CLAUDE.md file is the single most impactful thing you can add to a project that uses Claude Code. It acts as a persistent system prompt that Claude reads every time it starts a session in your repository. A well-written CLAUDE.md can dramatically reduce mistakes, enforce coding standards, and help Claude understand your project's architecture without you having to explain it every time.
This guide covers everything you need to know about writing effective CLAUDE.md files, with templates and real-world examples.
What Is CLAUDE.md?
CLAUDE.md is a markdown file placed at the root of your project (or in ~/.claude/CLAUDE.md for global settings). When Claude Code launches in a directory, it automatically reads this file and uses it as context for all interactions.
Think of it as:
- A README for your AI assistant rather than for human developers
- A persistent system prompt that survives across sessions
- A coding standards document that Claude actually follows
Where to Place CLAUDE.md
Claude Code searches for CLAUDE.md files in this order:
| Location | Scope | Use Case |
|---|---|---|
~/.claude/CLAUDE.md |
Global (all projects) | Personal preferences, default conventions |
./CLAUDE.md |
Project root | Project-specific context and rules |
./src/CLAUDE.md |
Subdirectory | Module-specific instructions |
All found files are concatenated, with more specific files taking precedence.
The Essential Sections
A good CLAUDE.md file should include these sections:
1. Project Overview
Tell Claude what the project is in 2-3 sentences. This prevents Claude from guessing.
# Project Overview
This is a SaaS platform for AI media generation built with Next.js 14
(App Router), TypeScript, and Tailwind CSS. The backend uses Supabase
for auth and database, Stripe for payments, and a custom API layer
for AI model inference.
2. Tech Stack
List every major technology, framework, and library. Be specific about versions.
# Tech Stack
- Framework: Next.js 14.2 (App Router, NOT Pages Router)
- Language: TypeScript 5.4 (strict mode)
- Styling: Tailwind CSS 3.4 + shadcn/ui components
- Database: PostgreSQL via Supabase
- ORM: Prisma 5.x
- Auth: NextAuth.js v5 (Auth.js)
- Payments: Stripe (subscriptions + one-time)
- State: Zustand for client state
- Forms: React Hook Form + Zod validation
- Testing: Vitest + React Testing Library
- Package manager: pnpm (NOT npm or yarn)
3. Project Structure
Map out the key directories so Claude knows where to find and place things.
# Project Structure
- src/app/ - Next.js App Router pages and layouts
- src/app/api/ - API route handlers
- src/app/[locale]/ - Internationalized routes
- src/components/ - Reusable React components
- src/components/ui/ - shadcn/ui base components (DO NOT EDIT)
- src/lib/ - Utility functions, API clients, helpers
- src/hooks/ - Custom React hooks
- src/types/ - TypeScript type definitions
- src/config/ - App configuration files
- prisma/ - Database schema and migrations
- content/ - MDX blog articles
- messages/ - i18n translation JSON files
- public/ - Static assets
4. Coding Conventions
This is the most important section. Be explicit about your coding standards.
# Coding Conventions
## General
- Use functional components with hooks (no class components)
- Prefer named exports over default exports
- Use absolute imports with @/ prefix (e.g., @/components/Button)
- All files use TypeScript (.ts/.tsx), never plain JavaScript
## Naming
- Components: PascalCase (e.g., UserProfile.tsx)
- Hooks: camelCase with "use" prefix (e.g., useAuth.ts)
- Utilities: camelCase (e.g., formatDate.ts)
- Types: PascalCase with descriptive names (e.g., UserProfile, ApiResponse)
- Constants: UPPER_SNAKE_CASE
- CSS classes: Use Tailwind utilities, avoid custom CSS
## Components
- One component per file
- Props interface defined above the component
- Use React.FC sparingly; prefer explicit return types
- Destructure props in the function signature
- Use "use client" directive only when necessary
## Error Handling
- Use try/catch in API routes and server actions
- Return structured error responses: { error: string, code: number }
- Never expose internal error details to the client
- Log errors server-side with console.error
## Imports Order
1. React/Next.js imports
2. Third-party library imports
3. Internal imports (@/)
4. Type imports
5. Relative imports
5. Important Rules and Constraints
This is where you put hard rules that Claude must never break.
# Important Rules
- NEVER modify files in src/components/ui/ (these are shadcn/ui generated)
- NEVER commit .env files or hardcode secrets
- ALWAYS use server actions for mutations, not API routes
- ALWAYS add "use client" when using hooks or event handlers
- ALWAYS run `pnpm lint` before considering a task complete
- Database migrations MUST be created with `pnpm prisma migrate dev`
- NEVER delete or modify existing migration files
- All user-facing text MUST use the i18n system (useTranslations)
- NEVER use `any` type; use `unknown` if the type is truly unknown
6. Common Commands
List the commands Claude needs to build, test, and lint your project.
# Common Commands
- `pnpm dev` - Start development server
- `pnpm build` - Build for production
- `pnpm lint` - Run ESLint
- `pnpm typecheck` - Run TypeScript type checking
- `pnpm test` - Run test suite
- `pnpm test:watch` - Run tests in watch mode
- `pnpm prisma generate` - Regenerate Prisma client
- `pnpm prisma migrate dev` - Create and run migrations
- `pnpm prisma studio` - Open database browser
7. API and Data Patterns
Document how data flows through your application.
# Data Patterns
## API Routes
API routes are in src/app/api/. They use the Next.js Route Handler format:
export async function POST(request: Request) { ... }
## Server Actions
Prefer server actions over API routes for mutations.
Server actions are in src/lib/actions/ and use "use server" directive.
## Database Queries
All database queries go through Prisma. The client is at src/lib/db.ts.
Never query the database directly from components.
## Authentication
Use the auth() helper from src/lib/auth.ts to get the current session.
Protected API routes should check auth at the top of the handler.
Full Template
Here is a complete CLAUDE.md template you can adapt:
# Project Overview
[2-3 sentences describing your project]
# Tech Stack
- Framework: [framework and version]
- Language: [language and version]
- Styling: [CSS approach]
- Database: [database]
- Auth: [auth solution]
- Testing: [test framework]
- Package manager: [pnpm/npm/yarn]
# Project Structure
- src/app/ - [description]
- src/components/ - [description]
- src/lib/ - [description]
[add more as needed]
# Coding Conventions
[your coding standards]
# Important Rules
- NEVER [critical constraint]
- ALWAYS [required practice]
[add more as needed]
# Common Commands
- `[command]` - [description]
[add more as needed]
# Data Patterns
[how data flows through your app]
# Known Issues
[any gotchas Claude should be aware of]
Advanced Tips
Use CLAUDE.md for Subdirectories
If you have a monorepo or complex project, add CLAUDE.md files in subdirectories:
project/
CLAUDE.md # Root-level project context
packages/
api/
CLAUDE.md # API-specific conventions
web/
CLAUDE.md # Frontend-specific conventions
Include Examples of Good Patterns
Instead of just describing conventions, show them:
# Example: Creating a New API Route
Here is the pattern for a new API route:
\`\`\`typescript
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const data = await db.item.findMany({
where: { userId: session.user.id },
});
return NextResponse.json(data);
} catch (error) {
console.error("Failed to fetch items:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
\`\`\`
Reference Key Files
Point Claude to important files it should read:
# Key Files
- src/lib/auth.ts - Authentication configuration and helpers
- src/lib/db.ts - Database client and connection
- src/types/index.ts - Shared type definitions
- .env.example - Required environment variables
Keep It Updated
Treat CLAUDE.md as a living document. When you change conventions, update the file. When Claude makes a mistake, add a rule to prevent it.
Common Mistakes to Avoid
- Being too vague: "Use good coding practices" tells Claude nothing. Be specific.
- Being too long: Claude has a context window. Keep it under 500 lines.
- Contradicting yourself: Do not say "use named exports" in one place and use default exports in examples.
- Forgetting the negative: Tell Claude what NOT to do, not just what to do.
- Omitting the tech stack: Claude may assume the wrong framework version.
Measuring Effectiveness
After adding a CLAUDE.md, track whether Claude:
- Follows your naming conventions without reminders
- Places files in the correct directories
- Uses the right imports and patterns
- Avoids the mistakes you listed in "Important Rules"
- Runs the correct build/lint commands
If Claude keeps making the same mistake, add a more explicit rule to your CLAUDE.md.
Conclusion
A well-crafted CLAUDE.md file is the difference between Claude Code being a generic AI assistant and a context-aware team member that understands your project. Invest 30 minutes writing a good one, and you will save hours of corrections and re-explanations.
If you are building applications that need AI media generation capabilities -- images, videos, audio, or talking avatars -- Hypereal AI provides all of these through a single API. With pay-as-you-go pricing, fast generation, and no content restrictions on creative work, it is the easiest way to add AI media to your product.
Related Articles
Start Building Today
Get 35 free credits on signup. No credit card required. Generate your first image in under 5 minutes.
