The complete Claude Code setup guide

Your CLAUDE.md file is
the difference that matters.

Most Claude Code users get 30% of the value because their project context is wrong. This guide shows you exactly how to structure your CLAUDE.md — and gives you battle-tested templates to start from.

The file Claude Code reads before every conversation

When you run claude in a project directory, Claude Code automatically reads a file called CLAUDE.md in the project root. Every conversation in that project starts with that file loaded into context — it's the persistent project instructions that travel with Claude through your entire codebase.

Think of it as the orientation briefing you'd give a senior engineer joining your team. It tells Claude: what this codebase is, what stack you're on, how things are organized, which decisions are already settled, and what mistakes to never make. Without it, Claude treats every conversation as if it's starting from zero — it doesn't know your framework choices, your naming conventions, your security rules, or which architectural decisions you've already made.

With a well-written CLAUDE.md, Claude Code knows your project the way a senior team member does. It writes code that matches your patterns. It asks fewer clarifying questions. It catches edge cases that are specific to your architecture. It doesn't suggest refactors you've already explicitly rejected. The difference between a poorly-written and a well-written CLAUDE.md is roughly the difference between a junior developer who needs everything explained and a senior one who already knows the context.

CLAUDE.md markdown
# Loaded by Claude Code at the start of every session in this project # Project Overview B2B SaaS — accounts receivable automation for mid-market finance teams. Stack: Next.js 14 App Router, TypeScript strict, PostgreSQL, Prisma, Stripe, Resend. Production: Vercel. Staging: staging.acme.com. Local: localhost:3000. # Coding Laws - NEVER use `any` in TypeScript. NEVER suppress TS errors with @ts-ignore. - NEVER commit secrets. NEVER reference STRIPE_SECRET_KEY in client-side code. - All Stripe webhook handlers must be idempotent — check processed_at before acting. - API routes: Zod validation at the boundary. Never trust raw req.body. # Architecture Decisions - Feature folders: src/features/{feature}/components, hooks, api, types - Shared UI: src/components/ui/ (shadcn only — no custom primitives) - Database: src/db/schema.ts (single file, Drizzle schema, no Prisma Client) - Auth: Clerk. Never roll your own auth. Never touch next-auth. # Current Focus Sprint 14: Invoice reconciliation feature. Building the matching algorithm. Do not suggest changes to the payment flow — that shipped and is stable. # Quality Standards - Unit tests required for all business logic. Integration tests for API routes. - Error messages must include error codes, not bare strings. - PRs require passing CI (lint + typecheck + tests) before review request.
The key insight: CLAUDE.md is not a one-time system prompt. It's a living document that gets loaded into every Claude Code conversation in your project — automatically, without any copy-paste. The more precise and detailed it is, the better Claude performs on every task in your codebase.

The 5 sections every CLAUDE.md needs

Most CLAUDE.md files fail because they're missing one or more of these sections. Each one does a different job — and without any of them, Claude will make a specific class of mistake repeatedly.

1

Project Context — what this codebase is and why it exists

Claude doesn't know your business. It doesn't know whether you're building a consumer app or enterprise software, a prototype or a production system with 50,000 users. Project context sets the frame for everything else — security requirements, error tolerance, code quality bar, and how to make tradeoffs. "We use Next.js" is not context. "B2B SaaS, enterprise customers, SOC 2 in progress, uptime SLA" is context.

CLAUDE.md — Section 1: Project Context markdown
# Project Context Production B2B SaaS serving 340 paying enterprise customers. Core product: automated invoice reconciliation for mid-market finance teams. Stack: Next.js 14, TypeScript strict, PostgreSQL 15, Drizzle ORM, Stripe, Resend. Infrastructure: Vercel (edge functions), Neon DB, Upstash Redis, Cloudflare R2. Revenue: $280K ARR. SOC 2 Type II audit in Q3. This is production — no cowboy deploys. # Why this matters: Claude treats a hobby project differently than production SaaS. # Tell it the stakes. It will write safer, more defensive code as a result.
2

Coding Laws — hard rules Claude must never break

These are the non-negotiables: security invariants, patterns you've explicitly banned, architectural decisions you've already made and don't want re-litigated. State them as imperatives, not suggestions. "Be careful about security" is not a law. "NEVER expose API keys in client-side code. NEVER bypass authentication middleware. All external inputs must be validated with Zod before use." — those are laws.

CLAUDE.md — Section 2: Coding Laws markdown
# Coding Laws ## Security (zero tolerance) - NEVER use `any` in TypeScript. If you feel the urge, create a proper type. - NEVER expose STRIPE_SECRET_KEY, DATABASE_URL, or any secret in client-side code. - NEVER skip input validation on API routes. All request bodies go through Zod schemas. - NEVER store plain-text passwords. User auth is handled entirely by Clerk — don't touch it. - Migration files are immutable once deployed to staging. Create new migrations, never edit old. ## Architecture (settled decisions — don't re-litigate) - Do NOT suggest switching from Drizzle to Prisma. This decision was made in month 2. - Do NOT introduce class-based React components. Functional components + hooks only. - Do NOT add new dependencies without checking bundle impact first.
3

Architecture Decisions — why things are structured the way they are

Without documented architecture decisions, Claude will make inconsistent choices across sessions. It might organize new features differently from existing ones, use different error handling patterns, or propose a refactor of something you deliberately structured a certain way. Architecture decisions don't just describe how things are — they explain why, so Claude understands which patterns are load-bearing and which are flexible.

CLAUDE.md — Section 3: Architecture Decisions markdown
# Architecture Decisions ## Folder Structure src/ features/ # Feature-scoped code. Each feature is self-contained. {feature}/ components/ # React components for this feature only hooks/ # Custom hooks for this feature api/ # Route handlers and server actions types/ # TypeScript types scoped to this feature components/ui/ # shadcn/ui components ONLY — no custom primitives here lib/ # Shared utilities, no business logic db/ schema.ts # Single Drizzle schema file — all models here ## Why feature folders? # We chose feature-scoped folders over flat component trees after hitting scaling # issues at 40+ components. Features encapsulate their own state, data, and UI. # New features should follow this pattern without exception. ## Data Fetching - Server components for initial data load (no useEffect data fetching) - React Query for client-side mutations and cache invalidation - Server actions for form submissions (not API routes)
4

Current Focus — what you're actively building right now

Claude works best when it knows what sprint or feature you're currently working on. This prevents it from suggesting changes to stable, shipped code when you're trying to build something new. It also lets Claude prioritize suggestions that are relevant to your current work rather than general improvements to the whole codebase. Update this section at the start of every sprint or major feature.

CLAUDE.md — Section 4: Current Focus markdown
# Current Focus Sprint 14 (ends 2026-04-25): Invoice Reconciliation Matching Algorithm Active work: - Building the fuzzy-match engine in src/features/reconciliation/lib/matcher.ts - Designing the confidence score model (0–100) for match quality - Writing integration tests against real invoice fixture data What's stable — do not suggest changes to: - Payment flow (src/features/payments/) — shipped in Sprint 12, has customers using it - Auth system — Clerk is fully wired and working, don't touch it - Dashboard layout — locked after customer feedback sessions in Sprint 11 # Update this section every sprint. Stale focus is worse than no focus.
5

Quality Standards — what done actually means

Without explicit quality standards, Claude defaults to its training distribution — which means inconsistent test coverage, varying error handling patterns, and code quality that doesn't match your bar. Define what a completed feature looks like: test coverage requirements, PR checklist items, error handling patterns, logging standards. Claude will apply these consistently across every task.

CLAUDE.md — Section 5: Quality Standards markdown
# Quality Standards ## Testing - Unit tests required for all business logic (matcher.ts, calculators, validators) - Integration tests required for all API routes and server actions - No mocking the database in integration tests — use test fixtures with real queries - Test file convention: {module}.test.ts alongside the module ## Error Handling - All errors extend base AppError class with: message, code, statusCode, context - API routes return: { success: false, error: { code, message } } — never bare strings - User-facing error messages must be actionable: "Invoice not found" vs "Error 404" ## Before Marking a Task Done - TypeScript compiles cleanly (tsc --noEmit passes) - ESLint passes with zero warnings (not just errors) - Tests pass and new code has coverage - No console.log left in code (use structured logger instead) - Verify the feature in the browser, not just unit tests

Common CLAUDE.md mistakes that kill productivity

Most developers write a CLAUDE.md once, don't see much improvement, and conclude that project instructions don't matter. Usually it's one of these five mistakes.

Too short — under 150 words

A five-line CLAUDE.md ("we use React and TypeScript, please write clean code") is treated as background noise. Claude's context window holds thousands of tokens — 150 words is a rounding error. It's not enough information to change Claude's default behavior in any meaningful way. Claude will still fall back on its training distribution for every decision.

Fix: Target 500–2,000 tokens. That's roughly one to four pages of focused instructions. More than that risks diluting the key rules; less than that doesn't move the needle.

Too long — over 3,000 words of generic text

Padding your CLAUDE.md with every possible best practice, comprehensive style guide boilerplate, and general programming philosophy wastes tokens and buries the rules that actually matter for your project. When everything is a rule, nothing is. Claude will treat your five non-negotiable security invariants with the same weight as "use descriptive variable names."

Fix: Write only rules that are specific to your project and would differ from defaults. Generic best practices don't need to be in CLAUDE.md — Claude already knows them.

Vague stack descriptions without the specifics that matter

"We use TypeScript" tells Claude almost nothing — it uses TypeScript in every mode from strict to barely-typed. "We use TypeScript strict mode, no-any, all errors extend AppError, never use type assertions" gives Claude the specific constraints that change how it writes code. The gap between a generic stack description and a specific one is the gap between Claude writing generic TypeScript and Claude writing code that looks like it belongs in your codebase.

Fix: For every tool, library, or language, add the one or two constraints that are specific to how YOU use it — not just that you use it.

No architecture decisions — just folder structure

Telling Claude "we use feature folders" is helpful, but not explaining why means Claude will propose changing to flat folders whenever it seems convenient. Architecture decisions need the why — because Claude needs to understand which patterns are load-bearing for your system's maintainability, and which are just preferences it can override if a simpler approach exists for a specific task.

Fix: For every major structural decision, add a one-line rationale. "Feature folders — chosen after hitting scaling issues with flat structure at 40+ components." Now Claude knows this is settled, not flexible.

Static file that never gets updated

A CLAUDE.md written when you set up the project and never touched again becomes a liability. It describes the stack and architecture from month one, but your project has evolved — you've migrated databases, deprecated patterns, changed your auth provider, settled on new conventions. Stale context doesn't just fail to help — it actively misleads Claude into suggesting patterns from your old architecture or respecting decisions you've already reversed.

Fix: Update CLAUDE.md at the start of every sprint. Add the current focus, update any architecture sections that have changed, and add any new laws that came out of recent bugs or decisions.

Get a production-ready CLAUDE.md — already structured correctly

We've engineered 15+ CLAUDE.md templates by studying what actually works across 72+ production AI-assisted development environments. Each template ships with all five sections fully structured, the right depth for each section, and [PLACEHOLDER] markers for your specific stack and context.

What you get with a Brainfile template

  • All 5 sections pre-structured at the right depth
  • Role-specific laws from real production environments
  • Architecture decision patterns for your tech stack
  • Quality standard templates proven to work with Claude
  • Monthly updates as Claude Code evolves
  • 15–30 min to customize, not 3–5 hours to write

What writing from scratch looks like

  • 3–5 hours of initial writing and iteration
  • Multiple sessions before it actually changes Claude's output
  • Missing sections you didn't know to include
  • Goes stale as Claude Code updates change what works
  • No benchmark to compare against — is it good? unclear
  • You discover missing pieces when Claude makes the mistake

Template categories available:

💻
Full-Stack Dev
Next.js, TypeScript, API design, testing, CI/CD
⚙️
Backend Engineer
APIs, microservices, databases, observability, security
🎨
Frontend Engineer
React, design systems, accessibility, performance, testing
🚀
SaaS Founder
Product + GTM + fundraising + investor comms
📋
Product Manager
PRDs, roadmap, research, prioritization frameworks
📣
Growth Marketer
Brand voice, channel strategy, analytics, reporting
Get All Templates — $149/mo Build yours free →

30-day money-back guarantee · Instant access · Cancel anytime

How templates stay current — and why it matters

What works in a CLAUDE.md today may need adjustment as Claude Code evolves. Anthropic ships tool updates, model improvements, and new features that change how context is consumed. A static download from six months ago won't reflect what works best with the current Claude.

🔄

Claude updates change what works

When Anthropic improves Claude's instruction-following, certain CLAUDE.md patterns that were necessary workarounds become unnecessary. New Claude Code features (custom commands, hooks, sub-agents) create new best practices for how to structure context. We update every template when these changes ship — subscribers get the update automatically.

📊

Aggregated pattern learning

We run multiple production AI systems daily. Every pattern that improves Claude's output — new section types, better instruction phrasing, more effective law formatting — gets tested against real tasks and incorporated into the templates. You get the compound benefit of months of daily iteration, not a single snapshot.

📅

New templates added monthly

The template library expands as we engineer new roles and document the patterns that work for each. DevOps, data science, agency management, legal — each one requires its own structure. Subscribers get access to every new template on release day without paying again.

🔧

The config on day 1 is a snapshot. The subscription keeps it current.

This is the core reason Brainfile is a subscription and not a one-time download. The templates we shipped six months ago were excellent then. They've been updated four times since based on Claude model changes alone. A download is a point-in-time artifact. A subscription is a living system that improves as the tools improve.

FAQ — Claude Code context and CLAUDE.md setup

Where does CLAUDE.md live in my project?
In the root of your project directory — the same level as your package.json or pyproject.toml. Claude Code reads it automatically when you run claude in that directory. You don't need to reference it in any command — it's loaded at the start of every conversation in that project. Name the file exactly CLAUDE.md (all caps) — Claude Code looks for that specific filename.
How long should my CLAUDE.md be?
The sweet spot is 500–2,000 tokens — roughly 400 to 1,500 words. Under 500 tokens (about 350 words) tends to be too thin to meaningfully change Claude's behavior. Over 3,000 tokens risks diluting the key rules with filler that gets averaged out. The goal is dense, specific, high-signal instructions — not comprehensive documentation. If you're writing more than 2,000 tokens, ask: is this specific to my project, or would Claude already know this?
Can I have multiple CLAUDE.md files in nested directories?
Yes. Claude Code supports nested CLAUDE.md files in subdirectories. When Claude is working in src/features/payments/, it reads both the root CLAUDE.md and any CLAUDE.md in that directory or its parents. Use this for feature-specific rules: the root CLAUDE.md has project-wide laws, while a feature subdirectory's CLAUDE.md has context specific to that module. This is powerful for large monorepos where different packages have different conventions.
Does CLAUDE.md work with .claude/commands/ and other Claude Code features?
Yes — they're complementary. CLAUDE.md is the persistent project context loaded at the start of every conversation. .claude/commands/ are reusable slash commands for specific tasks (like /commit or /test). The commands can reference and depend on context established in your CLAUDE.md — for example, a /review command that applies the quality standards from your CLAUDE.md. Claude Code also supports hooks (pre/post task automation) that integrate with your CLAUDE.md context.
How often should I update my CLAUDE.md?
At the start of every sprint or major feature. At minimum: whenever you make a significant architectural decision, adopt or remove a library, change your testing strategy, or complete a feature that should now be considered stable and off-limits for refactoring. The Current Focus section should be updated every sprint — stale sprint context is actively misleading. The Coding Laws and Architecture sections should be updated whenever you settle a previously open question.
How is Brainfile different from just writing my own CLAUDE.md?
You can absolutely write your own — and you should eventually customize it to your specific project. The value Brainfile provides is in the structure and starting point. Most developers writing their first CLAUDE.md miss critical sections (usually Architecture Decisions and Current Focus), write laws that are too vague to change behavior, or write project context that doesn't include the specifics Claude actually uses to make better decisions. Our templates are built from studying what actually improves Claude's output in production systems — not from writing what seems logical. The difference is 15 minutes of customization versus 3–5 hours of iteration to reach the same quality.
Start with a template that works

15 expert-crafted CLAUDE.md templates.
Updated monthly. Cancel anytime.

Stop iterating from scratch. Get the structure that works, customize the specifics to your project in 15 minutes, and let Brainfile keep your templates current as Claude Code evolves.

$149 /month
Get All Templates — $149/mo Build yours free first

30-day money-back guarantee · No setup required · Instant access

Not ready to buy? Stay in the loop.

Claude Code setup guides, context engineering tips, and new template releases. Free.

No spam. Unsubscribe anytime.