Skip to content

Initialize your first project

A CLAUDE.md file is the persistent project brief Claude Code loads automatically at the start of every session, capturing stack conventions, build and test commands, and patterns that Claude Fable 5, Opus 5, and Sonnet 5 would otherwise need re-explaining each time. It sits within a memory hierarchy of project, user, and modular files, supports @path imports for splitting large files, and updates through the /init, /memory, and # workflows.

This guide is for developers configuring Claude Code for a new or existing repository. You will create a persistent memory file, configure modular rules, and verify context loading across sessions. For full AI-native lifecycle orchestration, see Design.

When you drop Claude Code into a repository without context and ask for a small change, it can pick the wrong package manager, scaffold a component that ignores your folder conventions, or re-ask which test runner you use. The model lacks your team’s context. A CLAUDE.md file fixes that: it serves as the persistent project brief Claude reads at the start of every session, eliminating guesswork and enforcing your stack conventions.

  • Configure a CLAUDE.md file that captures your stack, build, test, and lint commands.
  • Use the memory hierarchy (project, user, and modular .claude/rules/) appropriately.
  • Split a large CLAUDE.md into focused files using @path import syntax.
  • Maintain memory during development using /init, /memory, and # workflows.
  • Run copy-paste prompts that instruct Claude to audit your repository and draft memory files.

What is CLAUDE.md?

CLAUDE.md is a markdown file that Claude Code automatically loads into context at startup. It acts as persistent memory that helps Claude understand your project’s specific requirements, coding standards, and common workflows.

Key benefits:

  • Provides persistent context across sessions.
  • Stores team knowledge in version control.
  • Loads automatically on startup.
  • Supports hierarchical organization for complex projects.

To initialize Claude Code in your project, follow these steps:

  1. Navigate to your project directory:

    Terminal window
    cd REPOSITORY_PATH

    Replace REPOSITORY_PATH with the path to your local git repository.

  2. Start Claude Code:

    Terminal window
    claude
  3. Initialize CLAUDE.md:

    Terminal window
    /init
  4. Review and customize the generated configuration. Claude analyzes your project and generates an initial CLAUDE.md file.

The /init command generates a starting template, but repository-specific instructions provide better guidance. To generate a CLAUDE.md based on your actual codebase, run the following prompt in Claude Code:

The following template provides a foundational structure for small to medium projects:

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

For complex multi-service projects, include runtime workflows, API patterns, and observability details:

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 scopes to organize instructions cleanly:

Location: ./CLAUDE.md

Contains team-shared instructions committed to version control:

  • Architecture decisions and framework patterns
  • Coding standards and formatting rules
  • Build, test, and typecheck commands
  • API patterns and error handling models
Terminal window
# Edit project memory during an active session
/memory
# Or record quick notes
# Always use async/await instead of callbacks

When you find Claude repeatedly violating a pattern in one directory, add a scoped rule under .claude/rules/:

To add memories quickly during a coding session, perform the following steps:

  1. Type # followed by your note in the prompt input:

    # The UserService.authenticate method requires a valid JWT token
  2. Select where to save the memory when prompted:

    • Project memory (./CLAUDE.md)
    • User memory (~/.claude/CLAUDE.md)
  3. Continue working. The recorded instruction is available immediately in the active session.

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 @lead for database schema changes

For large projects, keep the root CLAUDE.md concise and import specialized files with the @path/to/file directive. Unprefixed bullet lists do not import content; only the @ prefix triggers an import.

The following example demonstrates root configuration imports:

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 relative and absolute paths. Relative paths resolve against the file containing the import statement, not your working directory. The @ directive inside fenced code blocks remains inert. To share global instructions across git worktrees, import from your home directory (for example, @~/.claude/my-conventions.md).

When your root CLAUDE.md exceeds 300 lines, use the following prompt to refactor it into modular files:

The following configuration demonstrates conventions for Next.js App Router projects:

# 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
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

The following configuration specifies conventions for Django REST framework projects:

# 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

The following configuration specifies standards for Terraform and Kubernetes pipelines:

# 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

Follow these principles when maintaining CLAUDE.md:

  1. Be specific: Write “Use 2-space indentation” instead of “Format nicely”.
  2. Include code patterns: Provide minimal code examples demonstrating preferred patterns.
  3. Keep instructions current: Update the file whenever build commands, linters, or conventions change.
  4. Document known constraints: List known gotchas, flaky test workarounds, and environment requirements.
  5. Reference external resources: Link to design systems, API docs, and runbooks.
  6. Use clean hierarchy: Organize with concise headers and bullet lists.
  7. Commit memory files: Track changes in git alongside code changes.

In large repositories or monorepos, place CLAUDE.md files at each logical boundary:

project/
├── CLAUDE.md # Root context and global commands
├── frontend/
│ ├── CLAUDE.md # Frontend-specific patterns and libraries
│ └── components/
│ └── CLAUDE.md # UI component conventions
├── backend/
│ ├── CLAUDE.md # Backend-specific architecture and models
│ └── services/
│ └── CLAUDE.md # Microservice patterns
└── infrastructure/
└── CLAUDE.md # Deployment and IaC runbooks
  1. Collaborate on the initial draft: Convene with your team to agree on essential commands, linting gates, and style standards.
  2. Review changes in pull requests: Require peer review for modifications to CLAUDE.md and .claude/rules/.
  3. Conduct regular maintenance: Review memory files quarterly to prune obsolete commands.
  4. Use during onboarding: Guide new engineers to read CLAUDE.md to understand repository conventions.

Symptoms: Claude ignores repository conventions and asks for build commands.

Solutions:

  1. Confirm the filename is exactly CLAUDE.md in uppercase.
  2. Verify the file exists in the repository root where claude was launched.
  3. Restart the session.
  4. Run /memory to verify loaded content.

To verify your Claude Code configuration:

  1. Launch a fresh session:

    Terminal window
    claude
  2. Check loaded memory:

    Terminal window
    /memory

    Confirm that your root CLAUDE.md and any scoped rules appear in the active context list.

  3. Ask Claude to state project conventions:

    What command do we use to run our test suite and type checks?

    Confirm that Claude returns the exact commands specified in your CLAUDE.md without guessing.

The following table summarizes common Claude Code memory commands:

CommandPurpose
/initAnalyze repository and generate initial CLAUDE.md
/memoryInspect and edit loaded memory files
#Record quick memory note to project or user configuration
/clearClear conversation history and reload memory
@CLAUDE.mdReference memory explicitly in prompts