Skip to content

Initialize Your First Project

You drop Claude Code into your repo and ask for a small change. It picks the wrong package manager, scaffolds a component that ignores your folder conventions, and re-asks which test runner you use — again. Nothing is wrong with the model; it just has no idea what “the way we do things here” means. A CLAUDE.md file fixes that: it is the persistent project brief Claude reads at the start of every session, so it stops guessing and starts matching your stack.

  • A CLAUDE.md that captures your stack, build/test/lint commands, and the conventions Claude keeps violating
  • The memory hierarchy (project, user, and modular .claude/rules/) and when to use each
  • Real @path import syntax to split a bloated CLAUDE.md into focused files
  • The /init, /memory, and # workflows for keeping memory current while you code
  • Copy-paste prompts that make Claude draft and refactor its own memory files

What is CLAUDE.md?

CLAUDE.md is a special file that Claude Code automatically loads into context. Think of it as persistent memory that helps Claude understand your project’s specific needs, coding standards, and common workflows.

Key Benefits:

  • Persistent context across sessions
  • Shareable team knowledge, checked into source control
  • Automatically loaded on startup
  • Hierarchical for complex projects
  1. Navigate to your project

    Terminal window
    cd your-awesome-project
  2. Start Claude Code

    Terminal window
    claude
  3. Initialize CLAUDE.md

    Terminal window
    /init
  4. Review and customize Claude will analyze your project and generate a tailored CLAUDE.md file

/init gives you a starting point, but it tends to be generic. The fastest way to get a CLAUDE.md that actually reflects your project is to make Claude audit the repo and write it from evidence:

CLAUDE.md
# Project Overview
Brief description of what this project does and its main purpose.
# Architecture
- Frontend: React with TypeScript
- Backend: Node.js with Express
- Database: PostgreSQL
- State Management: Redux Toolkit
# Key Directories
- `src/`: Main source code
- `src/components/`: React components
- `src/api/`: API client code
- `src/utils/`: Utility functions
- `tests/`: Test files
# Common Commands
- `npm run dev`: Start development server
- `npm run build`: Build for production
- `npm test`: Run test suite
- `npm run lint`: Run linter
- `npm run type-check`: Check TypeScript types
# Code Style
- Use TypeScript for all new files
- Prefer functional components with hooks
- Use descriptive variable names
- Write tests for new features
- Follow existing patterns in the codebase
# Important Notes
- Environment variables are in `.env.example`
- Always run tests before committing
- Use feature branches for new work
- API documentation at `/docs/api.md`
# Current Sprint Goals
- [ ] Implement user authentication
- [ ] Add data validation to forms
- [ ] Improve error handling
Complex CLAUDE.md Example
# E-Commerce Platform
## Project Context
Multi-tenant SaaS e-commerce platform supporting B2B and B2C operations.
Built with microservices architecture, deployed on AWS ECS.
## Tech Stack
### Frontend
- Next.js 16 with App Router
- TypeScript strict mode
- Tailwind CSS + shadcn/ui
- React Query for data fetching
- Zustand for state management
### Backend Services
- API Gateway: Kong
- User Service: Node.js + Express + TypeORM
- Product Service: Go + Gin + GORM
- Order Service: Python + FastAPI + SQLAlchemy
- Payment Service: Java + Spring Boot
### Infrastructure
- AWS ECS for container orchestration
- PostgreSQL (RDS) for relational data
- Redis for caching and sessions
- ElasticSearch for product search
- S3 for media storage
## Development Workflow
### Local Development
```bash
# Start all services
docker-compose up
# Start specific service
docker-compose up user-service
# Run migrations
npm run migrate:up
# Seed test data
npm run seed:dev
```
### Testing Strategy
- Unit tests: Jest for JS/TS, Go test, pytest
- Integration tests: Supertest + Docker
- E2E tests: Playwright
- Min coverage: 80% for new code
### Git Workflow
1. Create feature branch from develop
2. Name format: feature/JIRA-123-brief-description
3. Commit format: "type(scope): description"
4. Open PR against develop
5. Require 2 approvals + passing CI
## API Patterns
### REST Endpoints
- GET /api/v1/resources - List with pagination
- GET /api/v1/resources/:id - Single resource
- POST /api/v1/resources - Create new
- PUT /api/v1/resources/:id - Full update
- PATCH /api/v1/resources/:id - Partial update
- DELETE /api/v1/resources/:id - Soft delete
### Common Headers
- Authorization: Bearer {token}
- X-Tenant-ID: {tenantId}
- X-Request-ID: {uuid}
## Security Considerations
- All endpoints require authentication except /health
- Use parameterized queries to prevent SQL injection
- Validate all inputs with Joi/Zod schemas
- Rate limiting: 100 req/min per user
- CORS configured for specific domains only
## Performance Guidelines
- Database queries must use indexes
- Implement pagination for list endpoints
- Cache GET requests in Redis (5 min TTL)
- Lazy load images and components
- Bundle size budget: 200KB for initial load
## Known Issues
- Payment webhooks occasionally timeout - retry logic in place
- Search indexing has 2-3 minute delay
- Some legacy endpoints use camelCase instead of snake_case
## Monitoring & Debugging
- Logs: CloudWatch (search by X-Request-ID)
- APM: DataDog (user-service.datadog.dashboard)
- Errors: Sentry (filter by service + env)
- Local debugging: See /docs/debugging.md

Claude Code supports multiple memory locations for different scopes:

Location: ./CLAUDE.md

Team-shared instructions checked into version control:

  • Architecture decisions
  • Coding standards
  • Build commands
  • API patterns
Terminal window
# Edit during session
/memory
# Or add quick notes
# Always use async/await instead of callbacks

When you keep catching Claude breaking the same convention in one area of the codebase, encode it as a scoped rule instead of repeating yourself:

The fastest way to add memories during coding:

  1. Type # followed by your note

    # The UserService.authenticate method requires a valid JWT token
  2. Choose memory location Claude prompts you to select where to save:

    • Project memory (./CLAUDE.md)
    • User memory (~/.claude/CLAUDE.md)
  3. Continue working The memory is immediately available

Quick Memory Patterns

Terminal window
# Build command is 'npm run build:prod' for production
# API keys are in Vault, not .env files
# Always run migrations before starting the app
# The calculateTax function has a known bug with decimals
# Prefer composition over inheritance in this codebase
# Contact @john for database schema changes

For large projects, keep the root CLAUDE.md small and pull in focused files with the @path/to/import directive. Plain bullet lists with bare paths do nothing — only the @ prefix actually imports a file.

CLAUDE.md with @path imports
# Main Project Configuration
See @README.md for the project overview and @package.json for available commands.
## Architecture
High-level system design and principles live here...
## Detailed Conventions
- Frontend conventions @frontend/CLAUDE.md
- Backend conventions @backend/CLAUDE.md
- Infrastructure runbooks @infra/CLAUDE.md
- Testing rules @tests/CLAUDE.md

Imports accept both relative and absolute paths. Relative paths resolve against the file doing the importing, not your working directory, and @ directives inside fenced code blocks are ignored so examples like this one stay inert. For personal instructions you want shared across git worktrees, import from your home directory (for example @~/.claude/my-conventions.md).

Once a root CLAUDE.md grows past a few hundred lines, let Claude do the splitting for you:

# Next.js E-Commerce App
## Project Structure
- App Router (not Pages Router)
- Server Components by default
- Client Components only when needed
- API routes in /app/api
## State Management
- Server state: React Query + Server Components
- Client state: Zustand for global, useState for local
- Form state: React Hook Form + Zod
## Styling Approach
- Tailwind CSS for utilities
- CSS Modules for complex components
- Framer Motion for animations
- Responsive-first design
## Component Patterns
```tsx
// Prefer this pattern for components
export function ComponentName({ prop1, prop2 }: Props) {
// Hooks at the top
// Early returns for edge cases
// Main render
}
```
## Data Fetching
- Use Server Components for initial data
- React Query for client-side updates
- Loading.tsx for suspense boundaries
- Error.tsx for error boundaries
# Django REST API
## Project Standards
- Python 3.11+ with type hints
- Black for formatting (line length 88)
- isort for imports
- pytest for testing
## Django Patterns
- Class-based views for CRUD
- Function-based views for complex logic
- Serializers handle all validation
- Managers for complex queries
## Database Guidelines
- Always use migrations
- Never edit migrations after deployment
- Use select_related/prefetch_related
- Index foreign keys and filter fields
## API Conventions
- RESTful URLs (/api/v1/users/)
- camelCase for JSON (use djangorestframework-camel-case)
- Pagination on all list endpoints
- Standard error format
## Testing Requirements
- Unit test all business logic
- Integration test all endpoints
- Use factory_boy for test data
- Mock external services
# Infrastructure as Code
## Terraform Conventions
- Modules in /modules directory
- Environments in /environments
- State in S3 with DynamoDB lock
- Always run plan before apply
## Kubernetes Patterns
- One namespace per environment
- ConfigMaps for config
- Secrets for sensitive data
- HPA for autoscaling
- PDB for availability
## CI/CD Pipeline
1. Lint (terraform fmt -check)
2. Validate (terraform validate)
3. Security scan (tfsec)
4. Plan (save plan file)
5. Manual approval for prod
6. Apply
## Monitoring Setup
- Prometheus for metrics
- Grafana for visualization
- Alert on SLI breaches
- Runbooks in /docs/runbooks

CLAUDE.md Best Practices

  1. Be Specific: “Use 2-space indentation” not “format nicely”
  2. Include Examples: Show actual code patterns you want followed
  3. Stay Current: Update as your project evolves
  4. Document Gotchas: Known issues, workarounds, and edge cases
  5. Link Resources: Reference documentation, wikis, and tools
  6. Use Structure: Organize with clear headings and sections
  7. Keep It Scannable: Use bullet points and code blocks
  8. Version Control: Track changes to understand evolution
project/
├── CLAUDE.md # Root context
├── frontend/
│ ├── CLAUDE.md # Frontend-specific
│ └── components/
│ └── CLAUDE.md # Component patterns
├── backend/
│ ├── CLAUDE.md # Backend-specific
│ └── services/
│ └── CLAUDE.md # Service patterns
└── infrastructure/
└── CLAUDE.md # DevOps context
  1. Create initial CLAUDE.md together

    • Hold a team session to agree on contents
    • Document existing conventions
    • Clarify ambiguous patterns
  2. Review in pull requests

    • Treat CLAUDE.md changes like code
    • Require team approval for updates
    • Keep history of why changes were made
  3. Regular maintenance

    • Review quarterly
    • Remove outdated information
    • Add new patterns as they emerge
  4. Onboarding tool

    • New developers read CLAUDE.md first
    • Use it during code reviews
    • Reference it in discussions

Symptoms: Claude doesn’t seem aware of your project context

Solutions:

  1. Verify file name is exactly CLAUDE.md (case-sensitive)
  2. Check file location (project root)
  3. Restart Claude Code session
  4. Run /memory to verify contents
CommandPurpose
/initGenerate initial CLAUDE.md
/memoryEdit memory files
#Add quick memory note
/clearClear conversation context
@CLAUDE.mdReference memory in prompts

Remember: A well-crafted CLAUDE.md file is like having perfect documentation that never gets lost and is always available exactly when Claude needs it.