We use cookies to enhance your experience on the site
CodeWorlds
Back to collections
Guide31 min read

Claude Code Templates

Project templates and CLAUDE.md configurations for Claude Code and AI-assisted development. Ready structures for Next.js, NestJS, fullstack and monorepo.

Claude Code Templates

Czym są Claude Code Templates?

Claude Code Templates to kolekcja gotowych szablonów projektów i konfiguracji zoptymalizowanych dla pracy z Claude Code, Cursor i innymi AI coding assistants. Zawierają plik CLAUDE.md (lub .cursorrules), struktury folderów, konfiguracje i dokumentację, które maksymalizują efektywność AI przy generowaniu i modyfikowaniu kodu.

Dobry template to nie tylko kod startowy - to przede wszystkim kontekst dla AI. Gdy Claude Code rozumie architekturę projektu, konwencje nazewnictwa i używany stack technologiczny, może generować kod, który natychmiast pasuje do reszty aplikacji.

Filozofia za templates

AI coding assistants są tak dobre, jak kontekst, który im przekażesz. Bez informacji o projekcie, Claude będzie generował kod w "domyślnym" stylu, który może nie pasować do Twojego projektu. Z dobrym CLAUDE.md, AI:

  • Rozumie strukturę projektu i wie, gdzie umieszczać nowe pliki
  • Zna konwencje nazewnictwa (camelCase vs snake_case, komponenty vs hooki)
  • Wie, jakich bibliotek i wzorców używać (np. Prisma zamiast raw SQL)
  • Generuje spójny kod zgodny z resztą codebase
  • Unika duplikacji i wykorzystuje istniejące utility functions

Różnica między CLAUDE.md a .cursorrules

Oba pliki służą podobnemu celowi, ale dla różnych narzędzi:

AspektCLAUDE.md.cursorrules
NarzędzieClaude Code CLICursor IDE
FormatMarkdownMarkdown/Plain text
LokalizacjaRoot projektu.cursor/ folder
DługośćBez limituZalecane <2000 znaków
KontekstAutomatycznie czytanyAutomatycznie czytany

Możesz mieć oba pliki w projekcie dla różnych workflow'ów.

Dlaczego używać templates?

1. Natychmiastowa produktywność

Zamiast tracić czas na tłumaczenie Claude'owi struktury projektu przy każdym zadaniu, template robi to raz, a dobrze. Każda sesja zaczyna się z pełnym kontekstem.

2. Konsystencja kodu

AI generuje kod w tym samym stylu co reszta projektu. Brak miksu różnych konwencji w jednej codebase.

3. Mniej poprawek

Kod wygenerowany z dobrym kontekstem wymaga mniej ręcznych poprawek. AI od razu wie:

  • Gdzie importować komponenty
  • Jakich hooków używać
  • Jak nazywać zmienne
  • Jak obsługiwać błędy

4. Dokumentacja jako side effect

CLAUDE.md pełni jednocześnie funkcję dokumentacji projektu. Nowi developerzy (i AI) szybko rozumieją architekturę.

5. Reproducibility

Te same instrukcje dają podobne wyniki. Team może współdzielić template i uzyskiwać spójny kod.

Struktura Template

Podstawowa struktura projektu

Code
TEXT
project-template/
├── CLAUDE.md              # Główny plik konfiguracyjny dla Claude
├── .cursor/
│   └── rules.md           # Cursor-specific rules (krótsze)
├── src/
│   ├── components/        # React components
│   ├── hooks/             # Custom hooks
│   ├── lib/               # Utilities i konfiguracje
│   ├── types/             # TypeScript types
│   └── app/               # Next.js App Router pages
├── docs/
│   ├── ARCHITECTURE.md    # Szczegółowy opis architektury
│   └── API.md             # Dokumentacja API
├── scripts/
│   └── setup.sh           # Setup script dla nowych devów
├── .env.example           # Template zmiennych środowiskowych
└── package.json

Rekomendowane sekcje CLAUDE.md

  1. Overview - Krótki opis projektu (2-3 zdania)
  2. Tech Stack - Lista technologii z wersjami
  3. Directory Structure - Mapa folderów z opisami
  4. Commands - Podstawowe komendy npm/yarn
  5. Conventions - Reguły kodowania
  6. Common Tasks - Instrukcje dla częstych zadań
  7. Architecture Decisions - ADRs i uzasadnienia

CLAUDE.md Template - Kompletny przykład

Next.js App Router Template

Code
Markdown
# Project: [Nazwa Projektu]

## Overview
[Nazwa] to [krótki opis - 1-2 zdania]. Aplikacja służy do [główny cel].

## Tech Stack
- **Framework**: Next.js 15 (App Router)
- **Language**: TypeScript 5.x (strict mode)
- **Database**: PostgreSQL + Prisma ORM
- **Auth**: NextAuth.js v5 (Auth.js)
- **Styling**: Tailwind CSS + shadcn/ui
- **State**: React Query (TanStack Query) + Zustand
- **Testing**: Vitest + Testing Library
- **Deployment**: Vercel

## Directory Structure
\`\`\`
src/
├── app/                    # Next.js App Router
│   ├── (auth)/            # Auth group (login, register)
│   ├── (dashboard)/       # Protected dashboard pages
│   ├── api/               # API routes
│   │   ├── auth/         # NextAuth endpoints
│   │   └── trpc/         # tRPC router (jeśli używany)
│   └── layout.tsx         # Root layout
├── components/
│   ├── ui/                # shadcn/ui components
│   ├── forms/             # Form components
│   └── [feature]/         # Feature-specific components
├── hooks/                  # Custom React hooks
├── lib/
│   ├── prisma.ts          # Prisma client singleton
│   ├── auth.ts            # Auth configuration
│   └── utils.ts           # Utility functions
├── types/                  # TypeScript type definitions
└── server/                 # Server-side code
    ├── actions/           # Server Actions
    └── db/                # Database queries
\`\`\`

## Commands
\`\`\`bash
npm run dev          # Start dev server (port 3000)
npm run build        # Production build
npm run test         # Run tests with Vitest
npm run lint         # ESLint check
npm run db:push      # Push Prisma schema to DB
npm run db:studio    # Open Prisma Studio
npm run db:seed      # Seed database
\`\`\`

## Conventions

### Naming
- **Components**: PascalCase (UserProfile.tsx)
- **Hooks**: camelCase with "use" prefix (useAuth.ts)
- **Utils**: camelCase (formatDate.ts)
- **Types**: PascalCase with "I" prefix for interfaces (IUser)
- **Constants**: SCREAMING_SNAKE_CASE

### Components
- Use functional components with TypeScript
- Prefer Server Components where possible
- Keep components under 150 lines
- Extract logic to custom hooks
- Use composition over props drilling

### Imports
- Use absolute imports with @/ alias
- Group imports: react → next → external → internal → types
- Prefer named exports over default exports

### Error Handling
- Use Result pattern for expected errors
- Throw only for unexpected errors
- Always handle loading and error states in UI
- Use error boundaries for component errors

### Database
- Use Prisma transactions for multi-step operations
- Soft delete where appropriate (deletedAt column)
- Index foreign keys and commonly queried fields

## Common Tasks

### Adding a new page
1. Create file in `src/app/(group)/page-name/page.tsx`
2. Add metadata export for SEO
3. Create Server Component, fetch data at top level
4. Use Client Components only for interactivity

### Adding a new API endpoint
1. Create `src/app/api/[endpoint]/route.ts`
2. Export named functions (GET, POST, PUT, DELETE)
3. Use Zod for request validation
4. Return NextResponse.json() with proper status codes

### Adding a Server Action
1. Create in `src/server/actions/[feature].ts`
2. Add "use server" directive at top
3. Use revalidatePath/revalidateTag for cache invalidation
4. Return { success: boolean, data?: T, error?: string }

### Creating a form
1. Use react-hook-form + zod for validation
2. Create schema in `src/lib/validations/[feature].ts`
3. Use Server Action for submission
4. Show loading state during submission
5. Display validation errors inline

### Database changes
1. Update `prisma/schema.prisma`
2. Run `npm run db:push` (dev) or create migration
3. Update related TypeScript types
4. Update affected components

## Architecture Decisions

### Why App Router over Pages Router?
- Better DX with Server Components
- Built-in layouts and loading states
- Improved data fetching patterns
- Future-proof architecture

### Why Prisma over raw SQL?
- Type-safe queries
- Auto-generated types
- Easy migrations
- Great DX with Prisma Studio

### Why Zustand over Redux?
- Simpler API for this project size
- Less boilerplate
- Works well with Server Components
- TypeScript support out of the box

## Environment Variables
Required variables (see .env.example):
- DATABASE_URL - PostgreSQL connection string
- NEXTAUTH_SECRET - Auth.js secret
- NEXTAUTH_URL - Base URL for auth callbacks

## Notes for AI
- Always use TypeScript strict mode
- Prefer async/await over .then()
- Use early returns for guard clauses
- Add JSDoc comments for exported functions
- Consider mobile responsiveness
- Follow accessibility best practices (ARIA, semantic HTML)

NestJS Backend Template

Code
Markdown
# Project: [API Name]

## Overview
[Nazwa] API to backend service dla [opis]. Obsługuje [główne funkcjonalności].

## Tech Stack
- **Framework**: NestJS 10.x
- **Language**: TypeScript 5.x (strict)
- **Database**: PostgreSQL + TypeORM
- **Cache**: Redis
- **Queue**: Bull (Redis-based)
- **Auth**: JWT + Passport
- **Docs**: Swagger/OpenAPI
- **Testing**: Jest + Supertest

## Directory Structure
\`\`\`
src/
├── modules/               # Feature modules
│   ├── auth/
│   │   ├── auth.module.ts
│   │   ├── auth.controller.ts
│   │   ├── auth.service.ts
│   │   ├── strategies/    # Passport strategies
│   │   ├── guards/        # Auth guards
│   │   └── dto/           # Data Transfer Objects
│   ├── users/
│   └── [feature]/
├── common/
│   ├── decorators/        # Custom decorators
│   ├── filters/           # Exception filters
│   ├── guards/            # Global guards
│   ├── interceptors/      # Interceptors
│   └── pipes/             # Validation pipes
├── config/                # Configuration modules
├── database/
│   ├── entities/          # TypeORM entities
│   ├── migrations/        # Database migrations
│   └── seeds/             # Seed data
└── main.ts
\`\`\`

## Commands
\`\`\`bash
yarn start:dev       # Start with hot reload
yarn build           # Production build
yarn start:prod      # Start production server
yarn test            # Run unit tests
yarn test:e2e        # Run E2E tests
yarn migration:run   # Run pending migrations
yarn migration:create # Create new migration
\`\`\`

## Conventions

### Module Structure
Każdy feature module zawiera:
- `.module.ts` - Module definition
- `.controller.ts` - HTTP endpoints
- `.service.ts` - Business logic
- `/dto` - Request/Response DTOs
- `/entities` - TypeORM entities (jeśli potrzebne)

### Naming
- **Modules**: singular (user.module.ts, not users)
- **Controllers**: plural endpoints (/users, not /user)
- **Services**: singular (UserService)
- **Entities**: singular, PascalCase (User)
- **DTOs**: CreateUserDto, UpdateUserDto, UserResponseDto

### Error Handling
- Throw NestJS HttpExceptions
- Use global exception filter for consistency
- Log errors with correlation ID
- Return standardized error response:
\`\`\`json
{ "statusCode": 400, "message": "...", "error": "Bad Request" }
\`\`\`

### Validation
- Use class-validator on all DTOs
- Use class-transformer for type conversion
- Enable whitelist to strip unknown properties
- Use custom validation decorators when needed

## API Response Format
\`\`\`typescript
// Success
{
  "data": T,
  "meta": { "page": 1, "total": 100 }
}

// Error
{
  "statusCode": number,
  "message": string,
  "error": string,
  "timestamp": string,
  "path": string
}
\`\`\`

## Common Tasks

### Adding a new module
\`\`\`bash
nest g module modules/[name]
nest g controller modules/[name]
nest g service modules/[name]
\`\`\`

### Adding a new endpoint
1. Add method to controller with decorators
2. Create DTO in `/dto` folder
3. Implement logic in service
4. Add Swagger decorators for docs
5. Write tests

### Database migration
1. Make changes to entity
2. Run `yarn migration:generate src/database/migrations/[name]`
3. Review generated SQL
4. Run `yarn migration:run`

## Environment Variables
- DATABASE_URL
- JWT_SECRET
- JWT_EXPIRES_IN
- REDIS_URL
- CORS_ORIGINS

Fullstack Monorepo Template

Code
Markdown
# Project: [Nazwa Monorepo]

## Overview
Monorepo zawierające frontend (Next.js), backend (NestJS) i shared packages.

## Tech Stack
- **Monorepo**: Turborepo + pnpm workspaces
- **Frontend**: Next.js 15, TypeScript, Tailwind
- **Backend**: NestJS 10, TypeScript, PostgreSQL
- **Shared**: TypeScript types, validation schemas
- **API**: REST + tRPC (optional)

## Workspace Structure
\`\`\`
/
├── apps/
│   ├── web/               # Next.js frontend
│   │   ├── src/
│   │   └── package.json
│   └── api/               # NestJS backend
│       ├── src/
│       └── package.json
├── packages/
│   ├── ui/                # Shared React components
│   │   ├── src/
│   │   └── package.json
│   ├── db/                # Database client (Prisma)
│   │   ├── prisma/
│   │   └── package.json
│   ├── types/             # Shared TypeScript types
│   │   ├── src/
│   │   └── package.json
│   └── config/            # Shared configs (ESLint, TSConfig)
│       ├── eslint/
│       └── typescript/
├── turbo.json             # Turborepo config
├── pnpm-workspace.yaml    # Workspace definition
└── package.json           # Root package.json
\`\`\`

## Commands (root level)
\`\`\`bash
pnpm install         # Install all dependencies
pnpm dev             # Start all apps in dev mode
pnpm build           # Build all packages and apps
pnpm lint            # Lint everything
pnpm test            # Run all tests
pnpm db:push         # Push Prisma schema
pnpm db:generate     # Generate Prisma client
\`\`\`

## Workspace-specific commands
\`\`\`bash
# Run command in specific workspace
pnpm --filter web dev
pnpm --filter api test
pnpm --filter @repo/ui build
\`\`\`

## Inter-package imports
\`\`\`typescript
// In apps/web
import { Button } from "@repo/ui"
import { User } from "@repo/types"
import { prisma } from "@repo/db"
\`\`\`

## Conventions

### Package naming
- Apps: web, api, admin, mobile
- Packages: @repo/[name] (ui, types, db, config)

### Shared code rules
- Types that both frontend and backend use → @repo/types
- Validation schemas (Zod) → @repo/types
- React components → @repo/ui
- Database client → @repo/db

### Dependency management
- Shared deps in root package.json
- App-specific deps in app's package.json
- Use workspace:* for internal packages

## Notes for AI
- Check which workspace you're in before making changes
- Use correct package names in imports
- Consider if code should be shared or app-specific
- Run commands from root with --filter for specific apps

Cursor Rules Template (.cursorrules)

Cursor preferuje krótsze instrukcje. Oto zoptymalizowana wersja:

Code
Markdown
# Project Rules

Tech: Next.js 15 App Router, TypeScript strict, Tailwind, shadcn/ui, Prisma

## Structure
- src/app/ - pages and layouts
- src/components/ - React components (prefer Server Components)
- src/lib/ - utilities and configs
- src/server/actions/ - Server Actions

## Conventions
- TypeScript strict, no any
- Named exports, absolute imports (@/)
- Components < 150 lines
- Error handling with Result pattern
- Mobile-first, accessible

## Commands
- npm run dev (port 3000)
- npm run db:push (Prisma)

## When creating components
1. Check if similar exists in src/components/ui
2. Use shadcn/ui patterns
3. Add proper TypeScript types
4. Consider Server vs Client Component

Zaawansowane konfiguracje

Template z Environment Variables

Code
Markdown
## Environment Setup

### Development
\`\`\`bash
cp .env.example .env.local
# Edit .env.local with your values
\`\`\`

### Required Variables
| Variable | Description | Example |
|----------|-------------|---------|
| DATABASE_URL | PostgreSQL connection | postgresql://... |
| NEXTAUTH_SECRET | Auth secret (32+ chars) | openssl rand -base64 32 |
| NEXTAUTH_URL | App URL | http://localhost:3000 |
| STRIPE_SECRET_KEY | Stripe API key | sk_test_... |

### Optional Variables
| Variable | Description | Default |
|----------|-------------|---------|
| LOG_LEVEL | Logging verbosity | info |
| ENABLE_ANALYTICS | Enable tracking | false |

### Generating secrets
\`\`\`bash
# Generate NEXTAUTH_SECRET
openssl rand -base64 32

# Generate API key
openssl rand -hex 24
\`\`\`

Template z Testing Guidelines

Code
Markdown
## Testing

### File naming
- Unit tests: `[name].test.ts`
- Integration tests: `[name].integration.test.ts`
- E2E tests: `[name].e2e.ts`

### Test structure
\`\`\`typescript
describe('UserService', () => {
  describe('createUser', () => {
    it('should create user with valid data', async () => {
      // Arrange
      const input = { email: 'test@test.com', name: 'Test' }

      // Act
      const result = await userService.createUser(input)

      // Assert
      expect(result).toMatchObject(input)
    })

    it('should throw on duplicate email', async () => {
      // ...
    })
  })
})
\`\`\`

### Mocking
- Use Vitest's vi.mock() for modules
- Create fixtures in `__fixtures__/`
- Use factories for test data

### Coverage requirements
- Minimum 80% coverage for new code
- 100% coverage for critical paths (auth, payments)

Template z CI/CD Information

Code
Markdown
## CI/CD Pipeline

### GitHub Actions Workflow
\`\`\`yaml
# .github/workflows/ci.yml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v4
      - run: pnpm install
      - run: pnpm lint
      - run: pnpm test
      - run: pnpm build
\`\`\`

### Deployment
- **Production**: main branch → Vercel
- **Preview**: PR branches → Vercel Preview

### Pre-commit hooks (Husky)
- Lint staged files
- Run affected tests
- Type check

### Branch naming
- feature/[ticket]-description
- fix/[ticket]-description
- chore/description

Tworzenie własnego template

Krok 1: Zbierz informacje o projekcie

Code
Markdown
## Checklist do CLAUDE.md

### Podstawowe
- [ ] Nazwa i opis projektu
- [ ] Główny tech stack z wersjami
- [ ] Struktura folderów
- [ ] Podstawowe komendy

### Konwencje
- [ ] Styl nazewnictwa (camelCase, PascalCase, etc.)
- [ ] Preferowane wzorce (hooks vs HOC, etc.)
- [ ] Import conventions
- [ ] Error handling approach

### Specyficzne dla projektu
- [ ] Niestandardowe abstrakcje
- [ ] Utility functions do reuse
- [ ] Common gotchas
- [ ] Performance considerations

Krok 2: Zacznij od minimum

Code
Markdown
# Project Name

## Stack
Next.js 15, TypeScript, Prisma, Tailwind

## Structure
- src/app - pages
- src/components - components
- src/lib - utilities

## Commands
npm run dev
npm run build

## Rules
- TypeScript strict mode
- Server Components preferred
- Tailwind for styling

Krok 3: Iteruj na podstawie potrzeb

Za każdym razem, gdy musisz poprawiać wygenerowany kod, dodaj regułę do CLAUDE.md:

Code
Markdown
## Learned rules
- Always use `prisma` singleton from `src/lib/prisma.ts`
- Forms use react-hook-form + zod, not native forms
- Images use next/image, not img tag
- Links use next/link, not anchor tags

Cennik

OpcjaKoszt
CLAUDE.md templatesDarmowe
Community templatesDarmowe
Custom template consultingCustom

Templates są darmowe - to tylko pliki markdown. Wartość jest w wiedzy i doświadczeniu, które zbierasz tworząc własne.

FAQ - Najczęściej zadawane pytania

Czy CLAUDE.md musi być w root projektu?

Claude Code szuka CLAUDE.md w katalogu, z którego jest uruchamiany. Najlepiej umieścić go w root. Możesz też mieć osobne pliki w podfolderach dla monorepo.

Jak długi powinien być CLAUDE.md?

Nie ma ścisłego limitu, ale praktycznie:

  • Minimum: 50-100 linii (podstawowe info)
  • Optymalnie: 200-400 linii (pełny kontekst)
  • Maximum: Tyle, ile potrzeba

Cursor rules powinny być krótsze (~2000 znaków).

Czy mogę używać markdown formatting?

Tak, Claude rozumie markdown. Używaj:

  • Headers (#, ##, ###) dla struktury
  • Code blocks dla przykładów
  • Tables dla porównań
  • Lists dla konwencji

Jak często aktualizować template?

  • Po znaczących zmianach w architekturze
  • Po dodaniu nowych konwencji
  • Po napotkaniu powtarzających się problemów
  • Podczas onboardingu nowych narzędzi

Czy dzielić CLAUDE.md między projektami?

Możesz mieć bazowy template i dostosowywać go per projekt. Główne sekcje (tech stack, structure) będą się różnić, ale konwencje kodowania mogą być wspólne.

Jak testować skuteczność template?

  1. Daj Claude'owi zadanie bez template
  2. Daj to samo zadanie z template
  3. Porównaj jakość i spójność kodu
  4. Iteruj na template na podstawie różnic

Czy CLAUDE.md zastępuje README.md?

Nie, to różne cele:

  • README.md → Dla ludzi, ogólny opis projektu
  • CLAUDE.md → Dla AI, szczegółowy kontekst techniczny

Mogą się uzupełniać, ale nie zastępują.


Claude Code Templates

What are Claude Code Templates?

Claude Code Templates are a collection of ready-to-use project templates and configurations optimized for working with Claude Code, Cursor, and other AI coding assistants. They include a CLAUDE.md file (or .cursorrules), folder structures, configurations, and documentation that maximize AI effectiveness when generating and modifying code.

A good template is not just starter code - it is primarily context for AI. When Claude Code understands the project architecture, naming conventions, and the technology stack in use, it can generate code that immediately fits the rest of the application.

Philosophy behind templates

AI coding assistants are only as good as the context you provide them. Without information about the project, Claude will generate code in a "default" style that may not fit your project. With a good CLAUDE.md, the AI:

  • Understands the project structure and knows where to place new files
  • Knows naming conventions (camelCase vs snake_case, components vs hooks)
  • Knows which libraries and patterns to use (e.g., Prisma instead of raw SQL)
  • Generates consistent code that matches the rest of the codebase
  • Avoids duplication and leverages existing utility functions

Difference between CLAUDE.md and .cursorrules

Both files serve a similar purpose, but for different tools:

AspectCLAUDE.md.cursorrules
ToolClaude Code CLICursor IDE
FormatMarkdownMarkdown/Plain text
LocationProject root.cursor/ folder
LengthNo limitRecommended <2000 chars
ContextAutomatically readAutomatically read

You can have both files in a project for different workflows.

Why use templates?

1. Immediate productivity

Instead of spending time explaining the project structure to Claude with every task, a template does it once and does it well. Every session starts with full context.

2. Code consistency

The AI generates code in the same style as the rest of the project. No mixing of different conventions in one codebase.

3. Fewer corrections

Code generated with good context requires fewer manual corrections. The AI immediately knows:

  • Where to import components
  • Which hooks to use
  • How to name variables
  • How to handle errors

4. Documentation as a side effect

CLAUDE.md simultaneously serves as project documentation. New developers (and AI) quickly understand the architecture.

5. Reproducibility

The same instructions produce similar results. A team can share a template and get consistent code.

Template structure

Basic project structure

Code
TEXT
project-template/
├── CLAUDE.md              # Main configuration file for Claude
├── .cursor/
│   └── rules.md           # Cursor-specific rules (shorter)
├── src/
│   ├── components/        # React components
│   ├── hooks/             # Custom hooks
│   ├── lib/               # Utilities and configurations
│   ├── types/             # TypeScript types
│   └── app/               # Next.js App Router pages
├── docs/
│   ├── ARCHITECTURE.md    # Detailed architecture description
│   └── API.md             # API documentation
├── scripts/
│   └── setup.sh           # Setup script for new devs
├── .env.example           # Environment variables template
└── package.json

Recommended CLAUDE.md sections

  1. Overview - Short project description (2-3 sentences)
  2. Tech Stack - List of technologies with versions
  3. Directory Structure - Folder map with descriptions
  4. Commands - Basic npm/yarn commands
  5. Conventions - Coding rules
  6. Common Tasks - Instructions for frequent tasks
  7. Architecture Decisions - ADRs and rationale

CLAUDE.md Template - complete example

Next.js App Router Template

Code
Markdown
# Project: [Project Name]

## Overview
[Name] is [short description - 1-2 sentences]. The application serves [main purpose].

## Tech Stack
- **Framework**: Next.js 15 (App Router)
- **Language**: TypeScript 5.x (strict mode)
- **Database**: PostgreSQL + Prisma ORM
- **Auth**: NextAuth.js v5 (Auth.js)
- **Styling**: Tailwind CSS + shadcn/ui
- **State**: React Query (TanStack Query) + Zustand
- **Testing**: Vitest + Testing Library
- **Deployment**: Vercel

## Directory Structure
\`\`\`
src/
├── app/                    # Next.js App Router
│   ├── (auth)/            # Auth group (login, register)
│   ├── (dashboard)/       # Protected dashboard pages
│   ├── api/               # API routes
│   │   ├── auth/         # NextAuth endpoints
│   │   └── trpc/         # tRPC router (if used)
│   └── layout.tsx         # Root layout
├── components/
│   ├── ui/                # shadcn/ui components
│   ├── forms/             # Form components
│   └── [feature]/         # Feature-specific components
├── hooks/                  # Custom React hooks
├── lib/
│   ├── prisma.ts          # Prisma client singleton
│   ├── auth.ts            # Auth configuration
│   └── utils.ts           # Utility functions
├── types/                  # TypeScript type definitions
└── server/                 # Server-side code
    ├── actions/           # Server Actions
    └── db/                # Database queries
\`\`\`

## Commands
\`\`\`bash
npm run dev          # Start dev server (port 3000)
npm run build        # Production build
npm run test         # Run tests with Vitest
npm run lint         # ESLint check
npm run db:push      # Push Prisma schema to DB
npm run db:studio    # Open Prisma Studio
npm run db:seed      # Seed database
\`\`\`

## Conventions

### Naming
- **Components**: PascalCase (UserProfile.tsx)
- **Hooks**: camelCase with "use" prefix (useAuth.ts)
- **Utils**: camelCase (formatDate.ts)
- **Types**: PascalCase with "I" prefix for interfaces (IUser)
- **Constants**: SCREAMING_SNAKE_CASE

### Components
- Use functional components with TypeScript
- Prefer Server Components where possible
- Keep components under 150 lines
- Extract logic to custom hooks
- Use composition over props drilling

### Imports
- Use absolute imports with @/ alias
- Group imports: react → next → external → internal → types
- Prefer named exports over default exports

### Error Handling
- Use Result pattern for expected errors
- Throw only for unexpected errors
- Always handle loading and error states in UI
- Use error boundaries for component errors

### Database
- Use Prisma transactions for multi-step operations
- Soft delete where appropriate (deletedAt column)
- Index foreign keys and commonly queried fields

## Common Tasks

### Adding a new page
1. Create file in `src/app/(group)/page-name/page.tsx`
2. Add metadata export for SEO
3. Create Server Component, fetch data at top level
4. Use Client Components only for interactivity

### Adding a new API endpoint
1. Create `src/app/api/[endpoint]/route.ts`
2. Export named functions (GET, POST, PUT, DELETE)
3. Use Zod for request validation
4. Return NextResponse.json() with proper status codes

### Adding a Server Action
1. Create in `src/server/actions/[feature].ts`
2. Add "use server" directive at top
3. Use revalidatePath/revalidateTag for cache invalidation
4. Return { success: boolean, data?: T, error?: string }

### Creating a form
1. Use react-hook-form + zod for validation
2. Create schema in `src/lib/validations/[feature].ts`
3. Use Server Action for submission
4. Show loading state during submission
5. Display validation errors inline

### Database changes
1. Update `prisma/schema.prisma`
2. Run `npm run db:push` (dev) or create migration
3. Update related TypeScript types
4. Update affected components

## Architecture Decisions

### Why App Router over Pages Router?
- Better DX with Server Components
- Built-in layouts and loading states
- Improved data fetching patterns
- Future-proof architecture

### Why Prisma over raw SQL?
- Type-safe queries
- Auto-generated types
- Easy migrations
- Great DX with Prisma Studio

### Why Zustand over Redux?
- Simpler API for this project size
- Less boilerplate
- Works well with Server Components
- TypeScript support out of the box

## Environment Variables
Required variables (see .env.example):
- DATABASE_URL - PostgreSQL connection string
- NEXTAUTH_SECRET - Auth.js secret
- NEXTAUTH_URL - Base URL for auth callbacks

## Notes for AI
- Always use TypeScript strict mode
- Prefer async/await over .then()
- Use early returns for guard clauses
- Add JSDoc comments for exported functions
- Consider mobile responsiveness
- Follow accessibility best practices (ARIA, semantic HTML)

NestJS Backend Template

Code
Markdown
# Project: [API Name]

## Overview
[Name] API is a backend service for [description]. It handles [main functionalities].

## Tech Stack
- **Framework**: NestJS 10.x
- **Language**: TypeScript 5.x (strict)
- **Database**: PostgreSQL + TypeORM
- **Cache**: Redis
- **Queue**: Bull (Redis-based)
- **Auth**: JWT + Passport
- **Docs**: Swagger/OpenAPI
- **Testing**: Jest + Supertest

## Directory Structure
\`\`\`
src/
├── modules/               # Feature modules
│   ├── auth/
│   │   ├── auth.module.ts
│   │   ├── auth.controller.ts
│   │   ├── auth.service.ts
│   │   ├── strategies/    # Passport strategies
│   │   ├── guards/        # Auth guards
│   │   └── dto/           # Data Transfer Objects
│   ├── users/
│   └── [feature]/
├── common/
│   ├── decorators/        # Custom decorators
│   ├── filters/           # Exception filters
│   ├── guards/            # Global guards
│   ├── interceptors/      # Interceptors
│   └── pipes/             # Validation pipes
├── config/                # Configuration modules
├── database/
│   ├── entities/          # TypeORM entities
│   ├── migrations/        # Database migrations
│   └── seeds/             # Seed data
└── main.ts
\`\`\`

## Commands
\`\`\`bash
yarn start:dev       # Start with hot reload
yarn build           # Production build
yarn start:prod      # Start production server
yarn test            # Run unit tests
yarn test:e2e        # Run E2E tests
yarn migration:run   # Run pending migrations
yarn migration:create # Create new migration
\`\`\`

## Conventions

### Module Structure
Each feature module contains:
- `.module.ts` - Module definition
- `.controller.ts` - HTTP endpoints
- `.service.ts` - Business logic
- `/dto` - Request/Response DTOs
- `/entities` - TypeORM entities (if needed)

### Naming
- **Modules**: singular (user.module.ts, not users)
- **Controllers**: plural endpoints (/users, not /user)
- **Services**: singular (UserService)
- **Entities**: singular, PascalCase (User)
- **DTOs**: CreateUserDto, UpdateUserDto, UserResponseDto

### Error Handling
- Throw NestJS HttpExceptions
- Use global exception filter for consistency
- Log errors with correlation ID
- Return standardized error response:
\`\`\`json
{ "statusCode": 400, "message": "...", "error": "Bad Request" }
\`\`\`

### Validation
- Use class-validator on all DTOs
- Use class-transformer for type conversion
- Enable whitelist to strip unknown properties
- Use custom validation decorators when needed

## API Response Format
\`\`\`typescript
// Success
{
  "data": T,
  "meta": { "page": 1, "total": 100 }
}

// Error
{
  "statusCode": number,
  "message": string,
  "error": string,
  "timestamp": string,
  "path": string
}
\`\`\`

## Common Tasks

### Adding a new module
\`\`\`bash
nest g module modules/[name]
nest g controller modules/[name]
nest g service modules/[name]
\`\`\`

### Adding a new endpoint
1. Add method to controller with decorators
2. Create DTO in `/dto` folder
3. Implement logic in service
4. Add Swagger decorators for docs
5. Write tests

### Database migration
1. Make changes to entity
2. Run `yarn migration:generate src/database/migrations/[name]`
3. Review generated SQL
4. Run `yarn migration:run`

## Environment Variables
- DATABASE_URL
- JWT_SECRET
- JWT_EXPIRES_IN
- REDIS_URL
- CORS_ORIGINS

Fullstack Monorepo Template

Code
Markdown
# Project: [Monorepo Name]

## Overview
A monorepo containing a frontend (Next.js), backend (NestJS), and shared packages.

## Tech Stack
- **Monorepo**: Turborepo + pnpm workspaces
- **Frontend**: Next.js 15, TypeScript, Tailwind
- **Backend**: NestJS 10, TypeScript, PostgreSQL
- **Shared**: TypeScript types, validation schemas
- **API**: REST + tRPC (optional)

## Workspace Structure
\`\`\`
/
├── apps/
│   ├── web/               # Next.js frontend
│   │   ├── src/
│   │   └── package.json
│   └── api/               # NestJS backend
│       ├── src/
│       └── package.json
├── packages/
│   ├── ui/                # Shared React components
│   │   ├── src/
│   │   └── package.json
│   ├── db/                # Database client (Prisma)
│   │   ├── prisma/
│   │   └── package.json
│   ├── types/             # Shared TypeScript types
│   │   ├── src/
│   │   └── package.json
│   └── config/            # Shared configs (ESLint, TSConfig)
│       ├── eslint/
│       └── typescript/
├── turbo.json             # Turborepo config
├── pnpm-workspace.yaml    # Workspace definition
└── package.json           # Root package.json
\`\`\`

## Commands (root level)
\`\`\`bash
pnpm install         # Install all dependencies
pnpm dev             # Start all apps in dev mode
pnpm build           # Build all packages and apps
pnpm lint            # Lint everything
pnpm test            # Run all tests
pnpm db:push         # Push Prisma schema
pnpm db:generate     # Generate Prisma client
\`\`\`

## Workspace-specific commands
\`\`\`bash
# Run command in specific workspace
pnpm --filter web dev
pnpm --filter api test
pnpm --filter @repo/ui build
\`\`\`

## Inter-package imports
\`\`\`typescript
// In apps/web
import { Button } from "@repo/ui"
import { User } from "@repo/types"
import { prisma } from "@repo/db"
\`\`\`

## Conventions

### Package naming
- Apps: web, api, admin, mobile
- Packages: @repo/[name] (ui, types, db, config)

### Shared code rules
- Types that both frontend and backend use → @repo/types
- Validation schemas (Zod) → @repo/types
- React components → @repo/ui
- Database client → @repo/db

### Dependency management
- Shared deps in root package.json
- App-specific deps in app's package.json
- Use workspace:* for internal packages

## Notes for AI
- Check which workspace you're in before making changes
- Use correct package names in imports
- Consider if code should be shared or app-specific
- Run commands from root with --filter for specific apps

Cursor Rules Template (.cursorrules)

Cursor prefers shorter instructions. Here is an optimized version:

Code
Markdown
# Project Rules

Tech: Next.js 15 App Router, TypeScript strict, Tailwind, shadcn/ui, Prisma

## Structure
- src/app/ - pages and layouts
- src/components/ - React components (prefer Server Components)
- src/lib/ - utilities and configs
- src/server/actions/ - Server Actions

## Conventions
- TypeScript strict, no any
- Named exports, absolute imports (@/)
- Components < 150 lines
- Error handling with Result pattern
- Mobile-first, accessible

## Commands
- npm run dev (port 3000)
- npm run db:push (Prisma)

## When creating components
1. Check if similar exists in src/components/ui
2. Use shadcn/ui patterns
3. Add proper TypeScript types
4. Consider Server vs Client Component

Advanced configurations

Template with environment variables

Code
Markdown
## Environment Setup

### Development
\`\`\`bash
cp .env.example .env.local
# Edit .env.local with your values
\`\`\`

### Required Variables
| Variable | Description | Example |
|----------|-------------|---------|
| DATABASE_URL | PostgreSQL connection | postgresql://... |
| NEXTAUTH_SECRET | Auth secret (32+ chars) | openssl rand -base64 32 |
| NEXTAUTH_URL | App URL | http://localhost:3000 |
| STRIPE_SECRET_KEY | Stripe API key | sk_test_... |

### Optional Variables
| Variable | Description | Default |
|----------|-------------|---------|
| LOG_LEVEL | Logging verbosity | info |
| ENABLE_ANALYTICS | Enable tracking | false |

### Generating secrets
\`\`\`bash
# Generate NEXTAUTH_SECRET
openssl rand -base64 32

# Generate API key
openssl rand -hex 24
\`\`\`

Template with testing guidelines

Code
Markdown
## Testing

### File naming
- Unit tests: `[name].test.ts`
- Integration tests: `[name].integration.test.ts`
- E2E tests: `[name].e2e.ts`

### Test structure
\`\`\`typescript
describe('UserService', () => {
  describe('createUser', () => {
    it('should create user with valid data', async () => {
      // Arrange
      const input = { email: 'test@test.com', name: 'Test' }

      // Act
      const result = await userService.createUser(input)

      // Assert
      expect(result).toMatchObject(input)
    })

    it('should throw on duplicate email', async () => {
      // ...
    })
  })
})
\`\`\`

### Mocking
- Use Vitest's vi.mock() for modules
- Create fixtures in `__fixtures__/`
- Use factories for test data

### Coverage requirements
- Minimum 80% coverage for new code
- 100% coverage for critical paths (auth, payments)

Template with CI/CD information

Code
Markdown
## CI/CD Pipeline

### GitHub Actions Workflow
\`\`\`yaml
# .github/workflows/ci.yml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v4
      - run: pnpm install
      - run: pnpm lint
      - run: pnpm test
      - run: pnpm build
\`\`\`

### Deployment
- **Production**: main branch → Vercel
- **Preview**: PR branches → Vercel Preview

### Pre-commit hooks (Husky)
- Lint staged files
- Run affected tests
- Type check

### Branch naming
- feature/[ticket]-description
- fix/[ticket]-description
- chore/description

Creating your own template

Step 1: Gather information about your project

Code
Markdown
## CLAUDE.md Checklist

### Basics
- [ ] Project name and description
- [ ] Main tech stack with versions
- [ ] Folder structure
- [ ] Basic commands

### Conventions
- [ ] Naming style (camelCase, PascalCase, etc.)
- [ ] Preferred patterns (hooks vs HOC, etc.)
- [ ] Import conventions
- [ ] Error handling approach

### Project-specific
- [ ] Custom abstractions
- [ ] Utility functions to reuse
- [ ] Common gotchas
- [ ] Performance considerations

Step 2: Start with a minimum

Code
Markdown
# Project Name

## Stack
Next.js 15, TypeScript, Prisma, Tailwind

## Structure
- src/app - pages
- src/components - components
- src/lib - utilities

## Commands
npm run dev
npm run build

## Rules
- TypeScript strict mode
- Server Components preferred
- Tailwind for styling

Step 3: Iterate based on needs

Every time you need to fix generated code, add a rule to your CLAUDE.md:

Code
Markdown
## Learned rules
- Always use `prisma` singleton from `src/lib/prisma.ts`
- Forms use react-hook-form + zod, not native forms
- Images use next/image, not img tag
- Links use next/link, not anchor tags

Pricing

OptionCost
CLAUDE.md templatesFree
Community templatesFree
Custom template consultingCustom

Templates are free - they are just markdown files. The value lies in the knowledge and experience you accumulate by creating your own.

FAQ - frequently asked questions

Does CLAUDE.md have to be in the project root?

Claude Code looks for CLAUDE.md in the directory from which it is launched. It is best to place it in the root. You can also have separate files in subfolders for monorepos.

How long should CLAUDE.md be?

There is no strict limit, but practically:

  • Minimum: 50-100 lines (basic info)
  • Optimal: 200-400 lines (full context)
  • Maximum: As long as needed

Cursor rules should be shorter (~2000 characters).

Can I use markdown formatting?

Yes, Claude understands markdown. Use:

  • Headers (#, ##, ###) for structure
  • Code blocks for examples
  • Tables for comparisons
  • Lists for conventions

How often should I update the template?

  • After significant architecture changes
  • After adding new conventions
  • After encountering recurring problems
  • When onboarding new tools

Should I share CLAUDE.md between projects?

You can have a base template and customize it per project. The main sections (tech stack, structure) will differ, but coding conventions can be shared.

How to test template effectiveness?

  1. Give Claude a task without a template
  2. Give the same task with a template
  3. Compare code quality and consistency
  4. Iterate on the template based on differences

Does CLAUDE.md replace README.md?

No, they serve different purposes:

  • README.md → For humans, general project description
  • CLAUDE.md → For AI, detailed technical context

They can complement each other, but they do not replace one another.