Skip to main content

02 - Context and Project Setup with Claude

Provide effective context to Claude: repository structure, CLAUDE.md files, persistent system prompts and strategies for mono/multi-repo projects.

What do you think about this article?

At a Glance

Provide effective context to Claude: repository structure, CLAUDE.md files, persistent system prompts and strategies for mono/multi-repo projects.

The Importance of Context

Context is the single most important factor determining Claude's effectiveness. Without proper context, even the best prompts produce generic, inconsistent results. With rich, well-structured context, Claude becomes a remarkably capable development partner that understands your project's conventions, constraints, and goals.

In this article, we'll explore how to structure your project to maximize Claude's understanding, from file organization to system prompts and persistent instructions.

What You'll Learn

  • Create a CLAUDE.md file that guides all interactions
  • Structure projects for optimal AI understanding
  • Choose between mono-repo and multi-repo setups
  • Write effective system prompts
  • Establish naming conventions that Claude can follow

Series Overview

# Module Status
1Foundation - Claude as Technical PartnerCompleted
2Context and Project SetupYou are here
3Ideation and RequirementsNext
4Backend and Frontend Architecture
5Code Structure and Organization
6Prompt Engineering and Advanced Techniques
7Testing and Quality
8Documentation
9Deploy and DevOps

The CLAUDE.md File

The CLAUDE.md file is the single most important file for AI-assisted development. It lives at the root of your project and provides Claude with everything it needs to understand your codebase and generate consistent, high-quality code.

Why CLAUDE.md Matters

When Claude Code or Claude Projects detects a CLAUDE.md file, it automatically includes this context in every conversation. This means:

  • Consistency: Every response follows your project's conventions
  • Accuracy: Claude understands your stack, architecture, patterns
  • Efficiency: No need to repeat context in every prompt
  • Quality: Generated code matches your existing codebase style

CLAUDE.md Template

CLAUDE.md - Complete Template
# CLAUDE.md

This file provides guidance to Claude when working with this codebase.

## Project Overview

**Name:** [Project Name]
**Type:** [Web application / API / CLI tool / etc.]
**Status:** [Active Development / MVP / Production]

### Description
[2-3 sentences explaining what the project does and why it exists]

### Key Features
- [Feature 1]
- [Feature 2]
- [Feature 3]

## Technology Stack

### Backend
- **Runtime:** Node.js 20
- **Framework:** Express 5 / NestJS 10 / Fastify 4
- **Language:** TypeScript 5.3 (strict mode)
- **Database:** PostgreSQL 16 + Prisma ORM
- **Cache:** Redis 7
- **Testing:** Jest + Supertest

### Frontend
- **Framework:** Angular 21 / React 18 / Vue 3
- **Styling:** Tailwind CSS 3.4 / SCSS
- **State:** Signals / Redux / Pinia
- **Testing:** Vitest + Testing Library

### Infrastructure
- **Container:** Docker + Docker Compose
- **CI/CD:** GitHub Actions
- **Hosting:** AWS / Vercel / Firebase

## Architecture

### Backend Architecture
We follow **Layered Architecture**:
- **Controllers:** HTTP handling only, no business logic
- **Services:** All business logic, orchestration
- **Repositories:** Data access only, no logic
- **DTOs:** Input validation, response shaping

### Frontend Architecture
We use **Feature-Based Structure**:
- **core/:** Singleton services, guards, interceptors
- **shared/:** Reusable components, pipes, directives
- **features/:** Feature modules (lazy loaded)

### Data Flow
```
Request -> Controller -> Service -> Repository -> Database
Response <- Controller <- Service <- Repository <- Database
```

## Coding Conventions

### File Naming
- Use kebab-case for all files: `user-profile.component.ts`
- Suffix by type: `.controller.ts`, `.service.ts`, `.spec.ts`

### Code Style
- **Variables/Functions:** camelCase (`getUserById`)
- **Classes/Interfaces:** PascalCase (`UserService`, `UserProfile`)
- **Constants:** SCREAMING_SNAKE_CASE (`MAX_RETRY_COUNT`)
- **Booleans:** is/has/can prefix (`isLoading`, `hasError`)

### TypeScript
- ALWAYS use strict mode
- NEVER use `any` - use `unknown` or proper types
- Prefer interfaces over types for objects
- Use async/await, not Promise.then()

### Error Handling
- Use custom error classes extending `AppError`
- Never expose stack traces in production
- Always include error codes for client handling

## Folder Structure

```
project/
├── src/
│   ├── config/              # Configuration
│   ├── modules/             # Feature modules
│   │   ├── users/
│   │   │   ├── users.controller.ts
│   │   │   ├── users.service.ts
│   │   │   ├── users.repository.ts
│   │   │   ├── dto/
│   │   │   └── __tests__/
│   │   ├── auth/
│   │   └── tasks/
│   ├── shared/              # Shared utilities
│   ├── database/            # Migrations, seeds
│   └── app.ts
├── tests/                   # E2E tests
├── docs/                    # Documentation
└── scripts/                 # Utility scripts
```

## Development Commands

```bash
# Development
npm run dev          # Start development server
npm run build        # Production build
npm run test         # Run tests
npm run lint         # Lint code
npm run format       # Format code

# Database
npm run db:migrate   # Run migrations
npm run db:seed      # Seed database
npm run db:reset     # Reset database
```

## Important Rules

### Security
- ALWAYS validate inputs with DTOs
- NEVER log sensitive data (passwords, tokens)
- Use parameterized queries (Prisma handles this)
- Sanitize output to prevent XSS

### Testing
- Every service method needs unit tests
- Minimum coverage: 80%
- Mock all external dependencies
- Use descriptive test names

### Git
- Conventional Commits: `feat:`, `fix:`, `docs:`, etc.
- Branch naming: `feature/*`, `bugfix/*`, `hotfix/*`
- Always squash merge to main

## Current Focus

[What are you currently working on? What should Claude prioritize?]

## Known Issues

- [Issue 1 and workaround]
- [Issue 2 and workaround]

Providing Effective Context

Beyond CLAUDE.md, there are several strategies for providing context effectively.

Good Context Practices

  • Include relevant file snippets
  • Explain the current state
  • Describe what you've already tried
  • Specify constraints clearly
  • Reference specific files by path
  • Share error messages completely
  • Mention related systems

Bad Context Practices

  • Dump entire codebase at once
  • Assume Claude remembers past sessions
  • Use vague references ("that file")
  • Omit important constraints
  • Truncate error messages
  • Mix unrelated topics
  • Provide outdated information

Context Hierarchy

Context Priority Order
1. CLAUDE.md (project-wide context)
   ↓ Loaded automatically by Claude Code/Projects

2. Current File Context
   ↓ The file you're working on, related imports

3. Conversation History
   ↓ What you've discussed in this session

4. Explicit Prompt Context
   ↓ What you include in your current message

5. Uploaded Files
   ↓ Additional files you share for reference

The higher in this list, the more "persistent" the context.
Lower items can override higher ones for specific tasks.

Project Structure for AI Understanding

How you structure your project affects how well Claude can understand and work with your code. A clear, consistent structure leads to better suggestions.

Naming Conventions That Help

File Naming Patterns

Type Pattern Example
Controller [name].controller.ts users.controller.ts
Service [name].service.ts users.service.ts
Repository [name].repository.ts users.repository.ts
DTO [action]-[name].dto.ts create-user.dto.ts
Entity [name].entity.ts user.entity.ts
Test [name].spec.ts / .test.ts users.service.spec.ts
Angular Component [name].component.ts user-list.component.ts
Angular Page [name].page.ts users-list.page.ts

When Claude sees consistent naming patterns, it can automatically infer file locations, understand relationships, and generate code that fits naturally into your existing structure.

Mono-Repo vs Multi-Repo

The repository structure significantly impacts how you work with Claude. Each approach has different implications for context management.

Mono-Repo

project/
├── packages/
│   ├── backend/
│   │   ├── package.json
│   │   └── src/
│   ├── frontend/
│   │   ├── package.json
│   │   └── src/
│   └── shared/
│       ├── package.json
│       └── src/
├── package.json
├── CLAUDE.md
└── tsconfig.base.json
Advantages with Claude:
  • Single CLAUDE.md for entire project
  • Shared types always visible
  • Cross-package changes easy
  • Consistent context

Multi-Repo

project-backend/
├── package.json
├── CLAUDE.md (backend-specific)
└── src/

project-frontend/
├── package.json
├── CLAUDE.md (frontend-specific)
└── src/

project-shared/
├── package.json
├── CLAUDE.md (shared types)
└── src/
Advantages with Claude:
  • Focused context per repo
  • Smaller context window usage
  • Independent versioning
  • Team isolation

Recommendation for Personal Projects

For solo developers building personal projects, a mono-repo is usually the better choice. It keeps everything together, makes cross-cutting changes easier, and provides Claude with complete context. Tools like Turborepo or Nx make managing mono-repos straightforward.

Mono-Repo Setup Example

Mono-Repo with Turborepo
# Initialize mono-repo
npx create-turbo@latest

# Structure
taskflow/
├── apps/
│   ├── api/              # Express/NestJS backend
│   │   ├── src/
│   │   ├── package.json
│   │   └── tsconfig.json
│   └── web/              # Angular/React frontend
│       ├── src/
│       ├── package.json
│       └── tsconfig.json
├── packages/
│   ├── shared-types/     # Shared TypeScript types
│   │   ├── src/
│   │   └── package.json
│   ├── ui/               # Shared UI components
│   │   ├── src/
│   │   └── package.json
│   └── config/           # Shared configs (ESLint, TS)
│       └── package.json
├── turbo.json           # Turborepo config
├── package.json         # Root package.json
├── CLAUDE.md            # Project-wide context
└── README.md

System Prompts and Persistent Instructions

System prompts define Claude's behavior and personality for your project. Use them to enforce consistent responses across all interactions.

System Prompt Template
You are assisting with the development of [Project Name], a [type] application.

## Your Role
You are a senior software engineer collaborating with a solo developer.
Your goal is to provide high-quality, maintainable code that follows
the project's established patterns and conventions.

## Key Behaviors
- Always explain your reasoning before providing code
- Ask clarifying questions when requirements are ambiguous
- Point out potential issues or edge cases proactively
- Suggest tests for any implementation
- Follow the conventions defined in CLAUDE.md

## Technology Expertise
You are an expert in:
- TypeScript with strict mode
- Node.js and Express/NestJS
- Angular 21 with standalone components
- PostgreSQL and Prisma ORM
- Testing with Jest

## Response Format
For code generation:
1. Brief explanation of approach
2. Code with inline comments for complex logic
3. Potential edge cases to consider
4. Suggested tests

For debugging:
1. Identify the likely cause
2. Explain why it's happening
3. Provide solution with explanation
4. Suggest prevention strategies

## Constraints
- Never use `any` type in TypeScript
- Always use async/await, not Promise.then()
- Follow REST conventions for API design
- Include error handling in all implementations
- Maximum 100 characters per line

Using System Prompts in Different Tools

Tool-Specific Configuration

Tool How to Set System Prompt
Claude Projects Project Settings > Instructions (pinned to all chats)
Claude Code CLI CLAUDE.md file auto-detected at project root
API `system` parameter in messages.create()
Cursor .cursorrules file at project root

Project Initialization Workflow

When starting a new project with Claude, follow this structured approach to establish context from the beginning.

Step 1: Project Initialization Prompt
I'm starting a new project and want to set up proper context for our collaboration.

## Project Details
- **Name:** TaskFlow
- **Type:** Time tracking and task management web application
- **Target:** Solo freelancers and small teams (1-5 people)
- **MVP Scope:** User auth, projects, tasks with time tracking, basic reports

## Technology Preferences
- Backend: Node.js + TypeScript (considering Express vs NestJS)
- Frontend: Angular 21 with signals
- Database: PostgreSQL
- Hosting: Start cheap (Firebase/Vercel), scale later if needed

## My Background
- Intermediate developer (3 years experience)
- Comfortable with TypeScript and Angular
- Less experienced with backend architecture
- Learning goals: clean architecture, testing practices

## What I Need
Please help me:
1. Decide between Express and NestJS (with reasoning)
2. Draft an initial CLAUDE.md file
3. Suggest the folder structure
4. Define naming conventions

Let's discuss before generating any code.
Step 2: Refine CLAUDE.md Together
Based on our discussion, here's my draft CLAUDE.md.
Please review and suggest improvements:

[paste your draft]

Consider:
- Is anything missing that you'd find helpful?
- Are the conventions clear and consistent?
- Would any additional examples help?
- Are there ambiguous areas that need clarification?
Step 3: Validate Structure
I've created the initial folder structure. Please verify it matches
our agreed patterns and CLAUDE.md:

[paste tree output or folder structure]

Check for:
- Consistent naming
- Correct file locations
- Missing essential files
- Unnecessary complexity

Keeping Context Updated

Your CLAUDE.md should evolve with your project. Here are triggers for updates:

When to Update CLAUDE.md

  • New patterns: When you establish a new coding pattern
  • New dependencies: When adding significant libraries
  • Architecture changes: When restructuring code
  • Learned lessons: When you discover better approaches
  • New modules: When adding new feature areas
  • Bug patterns: When you find recurring issues to avoid
Prompt - Updating CLAUDE.md
I've made some changes to the project that should be reflected in CLAUDE.md:

1. Added Redis for session caching
2. Switched from class-validator to Zod for validation
3. Created a new events module for async processing

Please update the relevant sections of my CLAUDE.md:

[paste current CLAUDE.md]

Also suggest if any new sections should be added.

Context for Different Tasks

Different development tasks require different levels and types of context.

Context by Task Type

Task Essential Context Nice to Have
New Feature Architecture, related modules, data models Similar existing features, UI mockups
Bug Fix Error message, relevant code, recent changes Reproduction steps, logs
Refactoring Current implementation, constraints, tests Performance metrics, tech debt list
API Design Existing endpoints, data models, auth rules Client requirements, versioning strategy
Testing Code to test, dependencies, edge cases Existing test patterns, coverage gaps
Documentation Code/API to document, audience, format Existing docs style, examples

Common Context Mistakes

Mistake: Context Overload

// BAD: Dumping 10 files at once
"Here are all my files, help me
add a new feature..."

[10,000 lines of code]

Problem: Overwhelms context window, dilutes focus

Solution: Focused Context

// GOOD: Relevant files only
"I need to add email notifications
when a task is completed.

Here's the current task service:
[task.service.ts - 50 lines]

Here's my notification helper:
[notify.util.ts - 20 lines]"

Mistake: Stale Context

// CLAUDE.md from 3 months ago
"Database: MongoDB"

// Reality: You switched to PostgreSQL
// Claude gives MongoDB-specific code

Problem: Outdated info = wrong suggestions

Solution: Regular Updates

// Set a reminder to review CLAUDE.md
// After major changes:
"I've updated the database to PostgreSQL
and added Prisma ORM. Please update
your understanding accordingly."

Context Checklist

Setup Checklist

Item Status
CLAUDE.md created at project root
Project overview and goals documented
Technology stack specified with versions
Architecture patterns explained
Folder structure documented
Naming conventions defined
Code style rules specified
Development commands listed
Security and testing requirements included
Current focus / known issues noted

Conclusion

Proper context setup is the foundation for effective Claude collaboration. Invest time upfront in creating a comprehensive CLAUDE.md and maintaining it as your project evolves. The quality of Claude's assistance directly correlates with the quality of context you provide.

Key Takeaways

  • CLAUDE.md is essential: Create it at project start, keep it updated
  • Structure matters: Clear naming conventions help Claude understand your code
  • Mono-repo for solo: Easier context management for personal projects
  • System prompts define behavior: Use them for consistent responses
  • Context is a conversation: Refine it with Claude's feedback
  • Keep it current: Outdated context leads to wrong suggestions

Next Article

In the next article "Ideation and Requirements", we'll explore how to use Claude to refine your project idea, define MVP scope, create user personas, and document requirements effectively.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects