The CLAUDE.md Guide: Give AI Full Context on Your Project
I've been using Claude Code daily since early 2025, and I can tell you the single biggest factor in getting useful output isn't prompt engineering or clever tricks. It's context. Specifically, it's a well-written CLAUDE.md file sitting at the root of your project. This one file is the difference between an AI assistant that fights your codebase and one that feels like a senior dev who's been on your team for months.
If you've been throwing prompts at Claude Code and getting back generic, wrong, or frustrating results, this guide is for you. I'll break down exactly how to structure your CLAUDE.md, what to include, what to leave out, and share real examples from production projects we've shipped at Social Animal.
Table of Contents
- What is CLAUDE.md and Why Does It Matter
- How Claude Code Reads Your Project Context
- The Anatomy of a Great CLAUDE.md File
- Section-by-Section Breakdown
- Real CLAUDE.md Examples
- Common Mistakes That Wreck Your AI Context
- CLAUDE.md vs Other AI Context Files
- Advanced Patterns for Large Projects
- Measuring the Impact
- FAQ
What is CLAUDE.md and Why Does It Matter
CLAUDE.md is a markdown file you place at the root of your repository that Claude Code reads automatically every time it starts a session. Think of it as onboarding documentation for your AI pair programmer. When a new developer joins your team, you don't just hand them a laptop and say "figure it out." You walk them through the architecture, explain the weird parts, point out the landmines. CLAUDE.md does the same thing for Claude.
Without it, Claude Code has to infer everything from your file structure, package.json, and whatever files it happens to read. That's like asking a new hire to understand your entire system by reading random source files. They'll get some things right, but they'll also make assumptions that waste everyone's time.
With a solid CLAUDE.md, I've seen task completion accuracy jump from roughly 60% to over 90% on first attempts. That's not a small improvement — it's the difference between AI-assisted development being a productivity multiplier and being a frustrating time sink.
How Claude Code Reads Your Project Context
Claude Code has a specific hierarchy for loading context. Understanding this matters because it affects how you organize your project memory.
The Context Loading Order
- ~/.claude/CLAUDE.md — Your global preferences (applied to every project)
- ./CLAUDE.md — The project-level file at your repo root
- ./subdirectory/CLAUDE.md — Directory-specific overrides
- .claude/settings.json — Project-specific tool permissions and settings
- Session context — What you tell Claude in the current conversation
The project-level CLAUDE.md is where you'll spend most of your time. The global file is good for personal preferences ("I prefer functional components" or "always use TypeScript strict mode"), but the real value is in per-project context.
Here's what's crucial: Claude Code reads the CLAUDE.md at the start of every session, but it also has limited context window space. If your CLAUDE.md is 5,000 words of rambling documentation, you're burning tokens that could be used for actual code reasoning. Be concise. Be specific. Every line should earn its place.
The Anatomy of a Great CLAUDE.md File
After writing and refining CLAUDE.md files across dozens of projects — Next.js apps, Astro sites, headless CMS integrations, API services — I've landed on a consistent structure that works.
The Ideal Structure
# Project Name
## Overview
One paragraph explaining what this project does and who it's for.
## Tech Stack
Exact versions and frameworks.
## Architecture
How the pieces fit together.
## Key Conventions
Coding standards, naming patterns, file organization rules.
## Common Commands
Build, test, deploy, and dev commands.
## Important Context
Stuff that's not obvious from the code.
## Known Issues / Gotchas
Landmines to avoid.
## Do NOT
Explicit things the AI should never do.
Let's dig into each section.
Section-by-Section Breakdown
Overview
Keep this to 2-3 sentences max. Claude doesn't need your product roadmap — it needs to understand the domain so it can make contextually appropriate decisions.
## Overview
This is the marketing site for Acme Corp, a B2B SaaS platform for supply chain management. The site is statically generated with dynamic API routes for form handling and lead capture. Content is managed through Sanity CMS by the marketing team.
Tech Stack
Be exact. Don't just say "React" — specify the version, the framework, the rendering strategy. This prevents Claude from suggesting patterns that work in React 18 but break in React 19, or recommending Pages Router when you're on App Router.
## Tech Stack
- **Framework**: Next.js 15.1 (App Router, RSC by default)
- **Language**: TypeScript 5.7 (strict mode)
- **Styling**: Tailwind CSS v4 with CSS-first configuration
- **CMS**: Sanity v3 with live preview
- **Deployment**: Vercel (Production + Preview environments)
- **Package Manager**: pnpm 9.x
- **Node**: v22 LTS
- **Testing**: Vitest + Playwright
- **State Management**: Zustand (minimal, only for client-side UI state)
Architecture
This is where most people either write too little or way too much. You're not writing a system design doc. You're giving Claude a mental model.
## Architecture
- `app/` — Next.js App Router pages and layouts
- `app/api/` — API routes (form submissions, webhooks)
- `components/` — Shared UI components (atomic design: atoms/, molecules/, organisms/)
- `lib/` — Utility functions, API clients, type definitions
- `lib/sanity/` — Sanity client, queries (GROQ), and type generation
- `content/` — MDX files for blog posts (co-located with frontmatter)
- `public/` — Static assets (prefer next/image for all images)
Data flows: Sanity CMS → GROQ queries in lib/sanity/queries.ts → Server Components → Client Components (only when interactivity needed)
All pages are statically generated at build time except /blog/[slug]/preview which uses draft mode.
Key Conventions
This section saves the most time. Without it, Claude will follow general best practices that may conflict with your team's choices.
## Key Conventions
- Components are named PascalCase, one component per file
- Use named exports, never default exports (except pages/layouts)
- All data fetching happens in Server Components — never use useEffect for data fetching
- API response types live in lib/types/ and are auto-generated from Sanity schema
- Use `cn()` utility (lib/utils.ts) for conditional class merging, not template literals
- Error boundaries wrap each major page section, not the entire page
- All form handling uses react-hook-form + zod validation schemas
- Commit messages follow Conventional Commits (feat:, fix:, chore:)
Common Commands
This seems basic, but Claude Code actually runs these commands. If it doesn't know the right ones, it'll guess, and it'll often guess wrong.
## Common Commands
- `pnpm dev` — Start development server (port 3000)
- `pnpm build` — Production build
- `pnpm lint` — ESLint + Prettier check
- `pnpm test` — Run Vitest unit tests
- `pnpm test:e2e` — Run Playwright E2E tests
- `pnpm sanity:typegen` — Regenerate Sanity types after schema changes
- `pnpm db:migrate` — Run Drizzle ORM migrations
Important Context
This is for the stuff Claude can't figure out by reading your code. Business logic, external constraints, things that would take a human reviewer 30 minutes to explain.
## Important Context
- We use ISR (revalidate: 3600) for all CMS pages. Never use `force-dynamic` unless absolutely necessary.
- The Sanity webhook at /api/revalidate handles on-demand revalidation — don't add manual revalidation logic.
- Image optimization goes through Sanity's CDN (cdn.sanity.io), not next/image for CMS content.
- Auth is handled by Clerk — never build custom auth flows.
- The /api/leads endpoint has rate limiting via Upstash Redis. Don't remove the rate limit middleware.
Known Gotchas
Every project has weird stuff. Put it here so Claude doesn't trip over it.
## Known Gotchas
- Sanity's portable text renderer has a bug with nested lists in v3.2. We use a custom serializer in components/portable-text/list-fix.tsx
- Tailwind v4 doesn't support the `@apply` directive in module CSS files — use inline classes instead
- The vercel.json rewrites for /docs/* proxy to our Mintlify docs site. Don't modify these without checking with the team.
- Environment variables prefixed with NEXT_PUBLIC_ are the only ones available client-side. Never expose API secrets this way.
The "Do NOT" Section
This is arguably the most important section. Negative instructions are incredibly effective with AI models.
## Do NOT
- Do not install new dependencies without asking first
- Do not use `any` type — find or create proper types
- Do not create new API routes for things that can be done in Server Components
- Do not modify the Sanity schema files without confirming the migration plan
- Do not use `"use client"` unless the component genuinely needs browser APIs or event handlers
- Do not write CSS files — everything is Tailwind utility classes
- Do not hardcode strings that should come from the CMS
Real CLAUDE.md Examples
Example: Next.js Marketing Site
This is a slimmed-down version of a CLAUDE.md we use on client projects, particularly when building Next.js sites with headless CMS backends.
# Acme Marketing Site
## Overview
Marketing website for Acme (acme.com). Built with Next.js 15, styled with Tailwind v4, content from Sanity CMS. Target: sub-2s LCP on all pages.
## Tech Stack
Next.js 15.1 | TypeScript 5.7 strict | Tailwind v4 | Sanity v3 | Vercel | pnpm
## Architecture
App Router with RSC. All data fetching in server components via GROQ queries in lib/sanity/queries.ts. Client components only for interactive elements (modals, forms, carousels).
Pages: / (home), /about, /pricing, /blog, /blog/[slug], /contact
## Conventions
- Named exports only (except page.tsx/layout.tsx)
- Components: PascalCase, one per file
- cn() for class merging
- Zod schemas for all form validation
- No useEffect for data fetching. Ever.
## Commands
pnpm dev | pnpm build | pnpm lint | pnpm test
## Do NOT
- Add "use client" without justification
- Install packages without asking
- Use default exports for components
- Modify sanity/schema/ files without confirming migration
- Use any type
Example: Astro Content Site
For Astro projects, the CLAUDE.md looks a bit different because the architecture paradigm is different.
# Tech Blog — Astro
## Overview
Developer blog with 500+ articles. Static-first, zero JS by default. MDX for content with custom components.
## Tech Stack
Astro 5.x | MDX | Tailwind v4 | Deployed to Cloudflare Pages | Content Collections v2
## Architecture
src/content/ — MDX articles with Zod-validated frontmatter
src/components/ — Astro components (zero JS) and React islands (interactive)
src/layouts/ — Base layouts
src/pages/ — File-based routing
## Key Rules
- Default to Astro components (.astro). Only use React for islands that need interactivity.
- client:visible for below-fold interactive components
- client:idle for non-critical interactive components
- Never use client:load unless absolutely necessary
- All images use Astro's Image component with proper width/height
- RSS feed auto-generates from content collection — don't build manual feed logic
## Do NOT
- Add React components when an Astro component would work
- Use client:load directive
- Skip image dimensions (causes CLS)
- Modify the content collection schema without updating existing frontmatter
Common Mistakes That Wreck Your AI Context
I've reviewed a lot of CLAUDE.md files at this point. Here are the patterns that consistently lead to bad results.
| Mistake | Why It Hurts | Fix |
|---|---|---|
| Too long (2000+ words) | Burns context window tokens, key info gets lost | Keep under 800 words. Link to external docs for deep dives. |
| Too vague ("we use React") | Claude fills in gaps with assumptions | Be specific: versions, patterns, exact tools |
| No negative instructions | Claude does "reasonable" things that break your conventions | Always include a "Do NOT" section |
| Copy-pasting README.md | READMEs are for humans, not AI context | Write CLAUDE.md from scratch with AI-specific framing |
| Including sensitive data | API keys, secrets in context files | Never put secrets in CLAUDE.md. Reference .env.example instead |
| Never updating it | Project evolves, context file doesn't | Review CLAUDE.md every sprint or major refactor |
| Contradictory instructions | "Use server components" + examples with useEffect fetching | Have one person own the file, review for consistency |
CLAUDE.md vs Other AI Context Files
Claude Code isn't the only AI tool that reads project context files. Here's how the landscape looks in 2025:
| File | Tool | Auto-Read | Scope |
|---|---|---|---|
| CLAUDE.md | Claude Code | Yes, on session start | Project-wide |
| .cursorrules | Cursor | Yes, on file open | Project-wide |
| .github/copilot-instructions.md | GitHub Copilot | Yes, in Copilot Chat | Repo-wide |
| .windsurfrules | Windsurf (Codeium) | Yes | Project-wide |
| AGENTS.md | OpenAI Codex CLI | Yes | Project-wide |
| .ai/context.md | Custom convention | No (manual reference) | Varies |
The good news: most of the content is transferable. If you write a solid CLAUDE.md, converting it to .cursorrules or copilot-instructions.md takes about 5 minutes. The structure and information are the same — only the file name and minor formatting differ.
If your team uses multiple AI tools (and many do in 2025), consider maintaining a single source of truth and generating the tool-specific files from it. A simple build script can copy your master context file to all the right locations.
Advanced Patterns for Large Projects
Nested CLAUDE.md Files
For monorepos or large codebases, you can place CLAUDE.md files in subdirectories. Claude Code will read the most specific one for the directory you're working in.
project/
├── CLAUDE.md # Global project context
├── apps/
│ ├── web/
│ │ └── CLAUDE.md # Web app specific context
│ └── api/
│ └── CLAUDE.md # API specific context
├── packages/
│ └── ui/
│ └── CLAUDE.md # Design system context
The root CLAUDE.md covers shared architecture and conventions. Each nested file adds specifics for that package.
Dynamic Context with /compact
Claude Code's /compact command summarizes the current conversation and frees up context space. For long sessions, I've found a pattern that works well:
- Start with CLAUDE.md loaded automatically
- Work on a feature
- Run
/compactwhen context gets heavy - Continue — Claude retains the CLAUDE.md context plus a compressed summary
Team-Shared vs Personal Context
We keep CLAUDE.md in version control (it should be committed). But individual developers also use ~/.claude/CLAUDE.md for personal preferences:
# Personal Preferences
- I prefer verbose variable names over abbreviations
- Show me the reasoning before writing code
- When suggesting changes, show the full file diff
- I use VS Code with Vim keybindings (don't suggest IDE-specific shortcuts)
This separation keeps the team file clean and focused on project facts while letting individuals customize their experience.
Measuring the Impact
How do you know your CLAUDE.md is working? Here are metrics we track internally:
- First-attempt accuracy: How often does Claude's first response need zero corrections? A good CLAUDE.md gets this above 80%.
- Convention violations: Count how many times Claude breaks your coding standards. Should trend toward zero.
- Context questions: If Claude keeps asking "what framework is this?" or "should I use the App Router?", your CLAUDE.md is missing information.
- Undo frequency: How often you have to reject or revert Claude's changes. Lower is better.
One team at a mid-size startup reported cutting their average AI-assisted task time from 12 minutes to 4 minutes after investing an hour in their CLAUDE.md. That's a 3x improvement from one file.
If you're building a project with us through our headless CMS development services, we include a tailored CLAUDE.md as part of every project handoff. It's that important to ongoing development velocity.
FAQ
What is CLAUDE.md and where does it go? CLAUDE.md is a markdown file placed at the root of your project repository. Claude Code automatically reads it at the start of every session to understand your project's architecture, conventions, tech stack, and constraints. Think of it as an onboarding document written specifically for your AI coding assistant.
How long should a CLAUDE.md file be? Aim for 300-800 words. Shorter files miss critical context, but anything over 1,000 words starts eating into your context window — space that's better used for actual code reasoning. Be concise and specific. Every sentence should earn its place. If you need more depth, link to external documentation rather than embedding it.
Should I commit CLAUDE.md to version control?
Absolutely. CLAUDE.md should be treated like any other project documentation — versioned, reviewed, and kept up to date. Your whole team benefits from consistent AI behavior. Personal preferences go in ~/.claude/CLAUDE.md instead, which stays local to each developer's machine.
How is CLAUDE.md different from .cursorrules? The content is nearly identical — both provide project context to an AI coding tool. The difference is which tool reads them. CLAUDE.md is for Claude Code (Anthropic's CLI tool), while .cursorrules is for Cursor IDE. If you use both tools, maintain one source of truth and copy it to both files, adjusting for any tool-specific formatting.
What's the most important section of a CLAUDE.md?
The "Do NOT" section. Negative instructions are disproportionately effective with AI models. Telling Claude what to avoid — don't use any types, don't add "use client" unnecessarily, don't install new packages without asking — prevents the most common and frustrating mistakes. A good ban list saves more time than pages of positive instructions.
Can I use CLAUDE.md for non-code projects? Yes. CLAUDE.md works for any project where you interact with Claude Code. I've seen effective ones for documentation repos, infrastructure-as-code projects, and even data analysis pipelines. The principle is the same: give Claude the context it needs to make good decisions about your specific project.
How often should I update my CLAUDE.md? Review it at every major refactor and at least once per sprint. If you upgrade a framework version, change a key dependency, or adopt a new convention, update the file immediately. Stale context is worse than no context because it actively misleads the AI. Some teams add a CLAUDE.md review to their PR checklist for infrastructure changes.
Does CLAUDE.md work with Claude on the web (claude.ai)? No. CLAUDE.md is specifically read by Claude Code, the CLI-based coding tool. If you're using Claude through the web interface or API, you'd need to paste the context manually or use the Projects feature to attach it as a knowledge file. Claude Code's automatic loading is what makes the file so powerful — zero friction, every session.