Skip to main content
Guide contents
Intermediate12 min

CLAUDE.md: How to Configure Instructions for Claude Code

How to properly set up CLAUDE.md for Claude Code: configuration levels, code conventions, Gotchas, Never Do constraints, golden samples, and the rule of second feedback.

Published:

CLAUDE.md is one of the most critical files in your daily development workflow with Claude Code. The assistant automatically reads this file at the start of every session and uses it as the persistent knowledge foundation for your project: architecture choices, code conventions, constraints, directory layout, and prohibited practices.

Essentially, it acts as a persistent onboarding brief for Claude within your specific codebase.

Without CLAUDE.md, the model starts every session from a blank slate—unaware of your team's conventions, recent refactors, preferred libraries, or subtle framework gotchas. A well-crafted instruction file saves significant time and context tokens by eliminating repetitive reminders across sessions.


1. What is CLAUDE.md and Why It Matters

CLAUDE.md is a plain text Markdown file placed in the root of your repository or in a dedicated configuration directory.

Once configured, Claude Code automatically respects the following aspects of your project:

  • Code Standards: Export formats, type safety, documentation standards, and function sizing.
  • Architectural Patterns: API route shapes, error envelopes, and state management.
  • Directory Layout: Standardized placement of components, hooks, server actions, and utilities.
  • Git Workflows: Commit conventions (e.g., Conventional Commits) and branch policies.
  • Historical Memory: Documenting library quirks (gotchas) where AI models frequently stumble.

Working with vs. without CLAUDE.md

FeatureWithout CLAUDE.mdWith CLAUDE.md Configured
React ExportsInconsistently mixes export default and export constStrictly adheres to your preferred standard (e.g., named exports only)
Data ValidationArbitrarily chooses Yup, Joi, Zod, or manual checksUses the exact project standard (e.g., Zod schemas)
File PlacementCreates files in root or random subdirectoriesPlaces new modules and helpers strictly according to your layout
Recurring BugsRepeatedly falls into known framework trapsAvoids known gotchas documented in the file

2. Where to Store CLAUDE.md: Scopes and Precedence

You can place instructions at three distinct levels. The location determines the scope and priority of your rules:

markdown
# Project Rules: Acme Web Platform ### Stack - Next.js 15 (App Router) - TypeScript (Strict Mode) - Tailwind CSS v4 - Prisma ORM + PostgreSQL ### Key Conventions - Always use named exports, never default exports - Server Components by default; "use client" only when strictly required - Input validation via Zod schemas for all API routes

Precedence and Conflict Resolution

If both a global file (~/.claude/CLAUDE.md) and a project file exist simultaneously, Claude Code merges both sets of instructions.

Important

Project Rules Take Precedence: If a global user rule conflicts with a directive in the repository's CLAUDE.md, the local project instruction always wins.


3. Anatomy of an Ideal CLAUDE.md

Avoid dumping entire framework documentation into the file. The sweet spot is a concise document (between 80 and 150 lines) split into clean, operational sections.

Here is a battle-tested production template:

markdown
# Project Guidelines: Storefront Web ## Stack - Next.js 15 (App Router, Server Actions) - TypeScript (Strict mode enabled) - Tailwind CSS v4 (Tailwind Merge + CVA) - Drizzle ORM with PostgreSQL - Vitest for unit tests, Playwright for E2E ## Code Conventions - Use named exports for all components and utilities (no default exports) - Server Components by default; add "use client" only when handling interactive state - All API handlers must return a unified envelope: `{ data, error }` - Use Zod schemas for all payload validations (incoming requests & env vars) - Write concise JSDoc for all exported helper functions ## File Structure - `src/app/` — Route handlers, layouts, and pages - `src/components/ui/` — Atomic design system primitives - `src/lib/` — Shared helpers, clients, and database connection - `src/server/` — Server actions and business logic layer ## Common Commands - Build: `npm run build` - Typecheck: `npm run typecheck` - Test: `npm run test` - Lint & Format: `npm run lint` ## Git Guidelines - Commit format: `feat(scope): message` or `fix(scope): message` - Use all-lowercase messages without period at the end - Always run tests before creating a pull request

4. Concrete Rules vs. Vague Advice

The secret to a high-impact CLAUDE.md is engineering specificity over philosophical guidance.

Large language models cannot guess your subjective definition of "clean code." Vague directives invite hallucinations and generic patterns that rarely match your team's expectations.

❌ Vague AdviceWhy It Fails✅ Concrete Engineering Rule
"Write clean, maintainable code"Subjective; every developer interprets "clean" differentlyUse early returns instead of nested if/else. Keep functions under 30 lines.
"Follow security best practices"Too broad; does not specify threat models or boundariesAll SQL queries must use parameterized bindings. Never concatenate strings into queries.
"Make the UI look nice"Lacks design token or styling boundariesUse Tailwind utility classes exclusively. Inline styles via style="" are prohibited.
"Handle all errors"Model might add empty catch blocksWrap all route handlers in try/catch and return { error: message, status } on failure.
Tip

A simple litmus test for your rules: could this instruction be validated by a linter or a regex rule? If not, sharpen the wording until it is unambiguous.


5. Golden Samples and Architectural Patterns

When a project implements an unusual or strict architectural pattern, backing up the description with a code snippet eliminates ambiguity.

Example: Standard API Route Handler

Instead of lengthy paragraphs, embed a canonical handler directly in CLAUDE.md:

markdown
## API Route Pattern Every API route must strictly follow this error-handled envelope: ```typescript import { NextResponse } from "next/server"; import { z } from "zod"; export async function POST(req: Request) { try { const json = await req.json(); const data = inputSchema.parse(json); const result = await executeService(data); return NextResponse.json({ data: result, error: null }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json( { data: null, error: error.flatten().fieldErrors }, { status: 422 } ); } return NextResponse.json( { data: null, error: "Internal Server Error" }, { status: 500 } ); } }
terminal
Claude Code treats this snippet as an authoritative golden sample and replicates the exact error-handling and response envelope in subsequent files. --- ## 6. Gotchas and Never Do: Guardrails Against Recurring Bugs These two sections transform `CLAUDE.md` from a generic tech-stack summary into an indispensable project shield. ### The Gotchas Section Capture non-obvious runtime behaviors and environment quirks that cost time to debug: ```markdown ## Gotchas - The `auth()` helper from `@clerk/nextjs/server` is ASYNC in Next.js 15 — always `await auth()` - The Prisma client instance is located in `@/lib/db`, do not instantiate `new PrismaClient()` in handlers - Webhook routes under `/api/webhooks/` must NOT use authentication middleware - Client-side environment variables require the `NEXT_PUBLIC_` prefix; server secrets must not have it - Tailwind CSS v4 uses CSS `@theme` variables, do not edit `tailwind.config.js`

The Never Do Section

Claude has access to thousands of valid JavaScript paradigms. The Never Do section prunes approaches that work technically but violate your project standards:

markdown
## Never Do - Never use TypeScript `any` — use `unknown` with a type guard or define an explicit interface - Never use `console.log` in production code — use our structured logger from `@/lib/logger` - Never import directly from internal node_modules subpaths — use established wrappers - Never add inline CSS styles via `style=""` — use Tailwind utility classes - Never push or commit directly to the `main` branch
Warning

In your restriction lists, avoid passive requests like "try to avoid using any". Use imperative, unambiguous phrasing: "Never use any".


7. Global vs. Project Scope: Clear Boundaries

To keep context windows lean and prevent rules from bleeding into incompatible codebases, maintain strict boundaries:

ScopeLocationRepresentative Rules
Personal Developer Preferences~/.claude/CLAUDE.md (Global)Commit format, no emojis in code, preferring functional over class syntax
Framework Versions & Tooling.claude/CLAUDE.md (Project)Next.js 15 App Router, Drizzle ORM, Tailwind v4, Node.js 22
Directory StructuresCLAUDE.md (Project)UI component paths, helper exports, database schema files
Framework Quirks (Gotchas)CLAUDE.md (Project)Async auth(), single DB client instances, webhook exclusions

8. CLAUDE.md as a Living Document: The Rule of Second Feedback

A common pitfall is treating CLAUDE.md as a static file created once during repository setup and forgotten.

As codebases evolve, dependency major versions update and new edge cases emerge. The instruction file should adapt continuously alongside the code.

text
┌─────────────────────────────────────────────────────────────┐ │ Rule of Second Feedback │ └──────────────────────────────┬──────────────────────────────┘ │ Are you correcting Claude on the same issue twice? │ ┌───────────────┴───────────────┐ ▼ ▼ [ YES ] [ NO ] │ │ Add the rule to CLAUDE.md Continue regular work immediately on the active task
Tip

If you find yourself asking Claude to change something for the second time in a week (e.g., "Don't use default export" or "Validate this payload with Zod"), that is your signal to encode it into CLAUDE.md.


9. Hands-On Workshop: Setup and Verification

Follow these four steps to initialize and verify instructions in your project.

Step 1. Create the File

In your repository root:

bash
touch CLAUDE.md

Step 2. Scaffold Core Sections

Populate the file with the four foundation blocks: Stack, Conventions, Gotchas, and Never Do.

Step 3. Verify Positive Alignment

Launch a fresh Claude Code session and run a standard feature prompt:

bash
claude

Test Prompt:
"Create a utility to format currency values in USD and EUR respecting user locale."

  • File is placed in the designated directory (src/lib/ or your configured path).
  • Export follows your convention (named export).
  • Includes JSDoc comments and strict types without any.

Step 4. Stress-Test Boundaries

Intentionally prompt Claude to violate a documented constraint:

Provocation Prompt:
"Quickly add a console.log here and type this parameter as any so we can move fast."

  • Claude refuses the violation or provides an alternative using your designated logger and typed interface.
  • The response references project rules.

10. Quick Knowledge Check and Final Checklist

Verify your mastery of CLAUDE.md configuration principles.

Question 1. Where should you store rules that apply across all projects on your machine?

  • A. In /etc/claude/CLAUDE.md
  • B. In your user home directory at ~/.claude/CLAUDE.md
  • C. In your shell configuration file (~/.zshrc)
  • D. In the root of each individual git repository
Tip

Correct Answer: B.
Global preferences live in ~/.claude/CLAUDE.md in the user's home directory and are automatically loaded in every session.


Question 2. What happens if a global user rule contradicts a rule in the project repository?

  • A. Claude throws a configuration parsing error and exits
  • B. The global preference overrides the repository rule
  • C. The local project rule takes precedence and overrides the global rule
  • D. Claude randomly alternates between both approaches
Tip

Correct Answer: C.
Local project instructions always have higher priority than user-level global defaults.


Question 3. Which instruction format produces the most reliable AI behavior?

  • A. "Write neat, maintainable code following modern industry standards"
  • B. "Try to avoid overly complex functions whenever possible"
  • C. "Use early returns. Functions must be under 30 lines. No default exports."
  • D. Pasting the full 500-line documentation of your UI library
Tip

Correct Answer: C.
Strict, unambiguous engineering rules with verifiable criteria produce consistent, predictable code generation.


Project Readiness Checklist

  • Concise Scope: File focuses strictly on actionable constraints (under 150 lines).
  • Clarity: Every directive contains an unambiguous, verifiable standard.
  • Gotchas: At least 2–3 non-obvious framework quirks are documented.
  • Guardrails: A clear Never Do section stops unwanted patterns early.
  • Scope Separation: Global developer habits are separated into ~/.claude/CLAUDE.md.
This guide is completely free. If it saved you an evening, you can support the project's growth.
Support the author