---
title: "Building Your Context Layer (The Only Moat)"
description: "CLAUDE.md is the difference between Claude Code guessing and Claude Code knowing. Here's how to build context that compounds."
pillar: "Claude Code"
level: "intermediate"
date: "2026-01-20"
url: "https://theglitch.ai/academy/claude-code/context-layers"
---

# Building Your Context Layer (The Only Moat)

CLAUDE.md is the difference between Claude Code guessing and Claude Code knowing. Here's how to build context that compounds.


# Building Your Context Layer (The Only Moat)

> **The Glitch's Take:** "Two developers, same tool, same task. One ships in an hour. The other struggles for a day. The difference is context."

**Part of:** [The Complete Guide to Claude Code](/articles/claude-code/claude-code-complete-guide)
**Level:** Intermediate
**Reading Time:** 10 minutes

---

## The Point

Claude Code's effectiveness is directly proportional to what it knows about your project. CLAUDE.md isn't optional documentation—it's the configuration file that determines whether Claude Code works or struggles.

This is your moat. Well-configured context is the one advantage that can't be copied, commoditized, or automated away.

---

## TL;DR

- **CLAUDE.md** tells Claude about your project, conventions, and expectations
- Context quality determines accuracy (40% → 90%+ improvement possible)
- Invest 30-60 minutes upfront, maintain ongoing
- Context compounds—early investment pays dividends on every task

---

## Why Context Is Everything

### The Accuracy Gap

| Context Level | First-Attempt Accuracy | Iterations Needed |
|---------------|------------------------|-------------------|
| No CLAUDE.md | 40-50% | 4-6 |
| Basic CLAUDE.md | 70-80% | 2-3 |
| Comprehensive CLAUDE.md | 90%+ | 1-2 |

The math is simple: better context = fewer iterations = more shipped.

### What Happens Without Context

Claude Code will:
- Guess at directory structure (often wrong)
- Use generic conventions (not yours)
- Miss existing patterns (create inconsistency)
- Ask basic questions it shouldn't need to ask
- Produce code that works but doesn't fit

### What Happens With Good Context

Claude Code will:
- Place files correctly the first time
- Match your coding style
- Follow your patterns
- Use your existing utilities
- Produce code that feels like you wrote it

---

## The CLAUDE.md Anatomy

### Section 1: Project Overview

```markdown
# CLAUDE.md

## Project Overview

- **Name**: Acme Dashboard
- **Type**: Full-stack web application
- **Purpose**: Internal analytics dashboard for sales team
- **Primary Language**: TypeScript
- **Framework**: Next.js 14 (App Router)
- **Database**: PostgreSQL via Prisma
- **Deployment**: Vercel
```

Why this matters: Establishes baseline understanding. Claude won't suggest MongoDB patterns for a Postgres project.

### Section 2: Quick Commands

```markdown
## Quick Commands

```bash
# Development
npm run dev              # Start dev server (port 3000)
npm run build            # Production build
npm run start            # Start production server

# Testing
npm run test             # Run all tests
npm run test:watch       # Watch mode
npm run test:coverage    # With coverage report

# Database
npm run db:generate      # Generate Prisma client
npm run db:push          # Push schema changes
npm run db:seed          # Seed development data

# Quality
npm run lint             # ESLint
npm run lint:fix         # ESLint with auto-fix
npm run typecheck        # TypeScript check
```
```

Why this matters: Claude Code can run these commands. If it knows the right commands, it uses them automatically.

### Section 3: Architecture

```markdown
## Architecture

### Directory Structure

```
/app                     # Next.js App Router pages
  /(auth)                # Auth-required routes
    /dashboard
    /settings
  /(public)              # Public routes
    /login
    /signup
  /api                   # API routes
    /v1                  # Versioned API
/components              # React components
  /ui                    # Generic UI (buttons, inputs)
  /features              # Feature-specific components
  /layouts               # Layout components
/lib                     # Shared utilities
  /api                   # API client functions
  /auth                  # Auth utilities
  /db                    # Database utilities
/prisma                  # Database schema and migrations
/types                   # TypeScript type definitions
/tests                   # Test files (mirrors /app and /components)
```

### Key Files

| File | Purpose |
|------|---------|
| `lib/auth/session.ts` | Session management, JWT handling |
| `lib/db/client.ts` | Prisma client singleton |
| `components/ui/index.ts` | UI component exports |
| `types/api.ts` | API request/response types |
```

Why this matters: Claude Code knows where to put new code and where to find existing utilities.

### Section 4: Conventions

```markdown
## Conventions

### Naming

| Type | Convention | Example |
|------|------------|---------|
| Components | PascalCase | `UserProfile.tsx` |
| Utilities | camelCase | `formatDate.ts` |
| Constants | UPPER_SNAKE | `API_BASE_URL` |
| Types | PascalCase + suffix | `UserProfileProps` |
| API routes | lowercase | `/api/v1/users` |

### Code Style

- **TypeScript**: Strict mode, no `any` without comment
- **React**: Functional components only, hooks for state
- **Async**: `async/await` over `.then()` chains
- **Errors**: Try/catch with typed errors, never swallow
- **Imports**: Absolute paths via `@/` prefix

### Component Pattern

```tsx
// Standard component structure
interface ComponentProps {
  // Props with JSDoc comments
}

export function Component({ prop }: ComponentProps) {
  // Hooks at top
  // Derived state
  // Effects
  // Handlers
  // Return JSX
}
```

### API Route Pattern

```typescript
// Standard API route structure
export async function GET(request: Request) {
  try {
    // Validate request
    // Process
    // Return NextResponse.json()
  } catch (error) {
    // Log error
    // Return appropriate status
  }
}
```
```

Why this matters: Claude Code matches your style. Code it produces looks like code you wrote.

### Section 5: Dependencies

```markdown
## Key Dependencies

### Why These Choices

| Dependency | Purpose | Why This One |
|------------|---------|--------------|
| `next-auth` | Authentication | Best Next.js integration |
| `prisma` | ORM | Type-safe, great DX |
| `zod` | Validation | Runtime + TypeScript types |
| `tanstack-query` | Data fetching | Caching, optimistic updates |
| `tailwindcss` | Styling | Utility-first, consistent |

### Adding Dependencies

Before adding a new dependency:
1. Check if existing dep solves the problem
2. Check bundle size impact
3. Verify active maintenance
4. Get approval if >100KB
```

Why this matters: Claude Code uses existing dependencies instead of suggesting new ones.

### Section 6: Common Tasks

```markdown
## Common Tasks

### Adding a New Page

1. Create route in `/app/(auth)/[route-name]/page.tsx`
2. Add types in `/types/[feature].ts`
3. Add API route if needed in `/app/api/v1/`
4. Add component tests in `/tests/components/`
5. Update navigation in `components/layouts/Sidebar.tsx`

### Adding a New API Endpoint

1. Create route file in `/app/api/v1/[resource]/route.ts`
2. Add Zod schema in `/lib/api/schemas/[resource].ts`
3. Add types in `/types/api.ts`
4. Add integration test in `/tests/api/`
5. Document in `/docs/api.md`

### Database Changes

1. Modify schema in `/prisma/schema.prisma`
2. Run `npm run db:generate`
3. Create migration: `npx prisma migrate dev --name [name]`
4. Update seed if needed: `/prisma/seed.ts`
5. Update affected types in `/types/`
```

Why this matters: Claude Code follows your workflow, not a generic one.

### Section 7: Notes for AI

```markdown
## Notes for AI

### Always

- Run `npm run lint` before marking task complete
- Run `npm run typecheck` after TypeScript changes
- Follow existing patterns in the codebase
- Use existing utility functions from `/lib`

### Never

- Add new dependencies without asking
- Make breaking changes to API routes without warning
- Skip error handling
- Use `any` without a comment explaining why

### Ask Before

- Changing database schema
- Modifying shared components in `/components/ui`
- Adding new environment variables
- Architectural changes

### Known Issues

- Auth refresh sometimes fails on Vercel preview—use `NEXTAUTH_URL` env var
- Prisma client caches aggressively—restart dev server after schema changes
```

Why this matters: Explicit instructions that Claude Code follows.

---

## Maintaining Context

### Update Triggers

Update CLAUDE.md when:
- Adding new conventions
- Changing directory structure
- Adding significant dependencies
- Discovering common issues
- Learning something Claude keeps getting wrong

### Review Cadence

- **Weekly**: Add any new patterns discovered
- **Monthly**: Review for outdated information
- **Per-feature**: Update after major features

### Versioning

Commit CLAUDE.md changes. It's documentation that matters.

---

## Advanced: The 3-File Memory System

For complex projects or ongoing work, use a structured memory externalization system with three files:

### File 1: context.md

Current state and working context:

```markdown
# Current Context

## Active Work
- Feature: User authentication flow
- Status: Building login form
- Blockers: None

## Recent Decisions
- Using JWT instead of sessions (performance reasons)
- React Hook Form for all forms
- 7-day refresh token expiry

## Open Questions
- Should we support OAuth in v1?
- Password reset via email or SMS?
```

### File 2: todos.md

Active task list and priorities:

```markdown
# Active Todos

## In Progress
- [ ] Build login form component
- [ ] Add validation with Zod

## Next Up
- [ ] Forgot password flow
- [ ] Email verification

## Blocked
- [ ] OAuth integration (waiting on provider decision)

## Completed (This Week)
- [x] Set up NextAuth
- [x] Create user database schema
```

### File 3: insights.md

Lessons learned and patterns discovered:

```markdown
# Project Insights

## What Works
- Zod + React Hook Form = excellent DX
- Server actions for form submission reduce client code
- Edge middleware for auth checks

## What Doesn't
- Client-side auth state leads to hydration issues
- Prisma eager loading causes N+1 problems

## Patterns to Repeat
- Always use `useTransition` for form submissions
- Wrap auth logic in dedicated hook
- Keep token refresh logic in middleware

## Mistakes Made (Don't Repeat)
- Initially stored tokens in localStorage (XSS risk)
- Forgot to invalidate sessions on password change
```

### Why This Works

Each file serves a different purpose with different update frequencies:

| File | Update Frequency | Purpose |
|------|------------------|---------|
| context.md | Every session | Current state, active work |
| todos.md | Multiple times/day | Task tracking, priorities |
| insights.md | After learnings | Knowledge accumulation |

Claude reads all three at session start. You never repeat context. Knowledge compounds.

### Infinite Data Processing

This system also works for processing large amounts of data (customer feedback, support tickets, research):

1. **Input:** Dump raw data into context.md
2. **Process:** Ask Claude to extract patterns, update insights.md
3. **Track:** Log what's processed in todos.md
4. **Repeat:** Fresh session, Claude knows what's done

One user processed 6 months of customer feedback (1000+ entries) using this system, extracting recurring themes, feature requests, and churn signals.

---

## Multi-File Context Architecture

For large projects, extend beyond CLAUDE.md:

```
/docs
  /CLAUDE.md              # Main context file
  /context.md             # Active working context
  /todos.md               # Task tracking
  /insights.md            # Accumulated learnings
  /ARCHITECTURE.md        # Deep architecture docs
  /API.md                 # API documentation
  /CONVENTIONS.md         # Extended conventions
```

Reference in main CLAUDE.md:
```markdown
## Extended Documentation

For detailed information:
- Architecture deep-dive: `/docs/ARCHITECTURE.md`
- API reference: `/docs/API.md`
- Full conventions: `/docs/CONVENTIONS.md`

## Working Memory
- Current context: `/docs/context.md`
- Active todos: `/docs/todos.md`
- Lessons learned: `/docs/insights.md`
```

Claude Code will read these when relevant.

---

## Quick Reference

### Minimum Viable CLAUDE.md

```markdown
# CLAUDE.md

## Project: [Name]
- Type: [Web App/API/CLI]
- Language: [Primary]
- Framework: [Framework]

## Commands
- Dev: `npm run dev`
- Test: `npm run test`
- Lint: `npm run lint`

## Structure
[List key directories]

## Conventions
[Top 3-5 rules]

## Notes for AI
- [Most important instruction]
- [Second most important]
```

Time to create: 10-15 minutes
Improvement: 40% → 70% accuracy

### Comprehensive CLAUDE.md

Full template as shown above.

Time to create: 30-60 minutes
Improvement: 40% → 90%+ accuracy

---

## Next Steps

- [10 Mistakes Everyone Makes with Claude Code](/articles/claude-code/claude-code-mistakes)
- [Claude Code + MCP Integration](/articles/claude-code/claude-code-mcp-integration)
- [Back to Claude Code Guide](/articles/claude-code/claude-code-complete-guide)

---

## Sources

- [Anthropic Claude Documentation](https://docs.anthropic.com)
- The Glitch's internal project configurations

---

*Last verified: 2026-01-20. Tested on 50+ projects with varying context quality.*

