Rules & Templates

Ready-to-Use Project Rules

Copy-paste CLAUDE.md and .cursorrules templates for your project type. Customize and ship.

What Are Project Rules?

Tell Your AI How Your Project Works

Project rules are config files that your AI coding assistant reads automatically. They contain your conventions, patterns, and guardrails.

CLAUDE.md
  • Used by Claude Code
  • Location: .claude/CLAUDE.md (project) or ~/.claude/CLAUDE.md (global)
  • Auto-loaded at the start of every conversation
  • Contains: project conventions, tech stack, patterns to follow, things to avoid
  • Markdown format
.cursorrules
  • Used by Cursor
  • Location: .cursorrules in project root
  • Auto-loaded into every Cursor AI chat
  • Same purpose: conventions, patterns, rules
  • Plain text / markdown format
Both files serve the same purpose — they tell your AI assistant how YOUR project works, so it writes code that fits your codebase instead of generic tutorials. The content is nearly identical; only the filename and location differ.
6 Templates

Pick Your Stack, Copy the Rules

Click a template to expand it. Copy the content into your CLAUDE.md or .cursorrules file and customize for your project.

React SPA
Vite + TypeScript + Tailwind + React Query + Zustand
# Project Rules — React SPA

## Tech Stack
- React 18 + TypeScript + Vite
- React Router v6 for routing
- Zustand for state management
- Tailwind CSS for styling
- React Query for server state
- Vitest + React Testing Library for tests

## Project Structure
src/
├── components/    → Reusable UI components
├── pages/         → Route-level page components
├── hooks/         → Custom React hooks
├── stores/        → Zustand stores
├── api/           → API client and endpoints
├── types/         → TypeScript interfaces
├── utils/         → Helper functions
└── assets/        → Static files

## Conventions
- Functional components only — no class components
- Custom hooks for any logic used in 2+ components
- Co-locate component, styles, and tests in the same folder
- Named exports only — no default exports
- Use TypeScript strict mode — no `any` types
- Component files: PascalCase (Button.tsx)
- Utility files: camelCase (formatDate.ts)

## State Management
- Server state → React Query (useQuery, useMutation)
- Client state → Zustand stores (minimal, atomic)
- Form state → React Hook Form
- URL state → React Router search params
- Never duplicate server data in client stores

## Styling
- Tailwind utility classes — no custom CSS unless absolutely necessary
- No inline styles
- Component variants via className props
- Design tokens in tailwind.config.ts

## API Calls
- All API calls go through src/api/ — never call fetch/axios directly in components
- Use React Query hooks for data fetching
- Handle loading, error, and empty states on every page
- Type all API responses with TypeScript interfaces

## Testing
- Test behavior, not implementation
- One test file per component/hook
- Use screen queries from Testing Library — no querySelector
- Mock API calls with MSW (Mock Service Worker)

## Do NOT
- Use `any` type — use `unknown` if truly dynamic
- Install new packages without asking first
- Create wrapper components for single-use cases
- Put business logic in components — extract to hooks/utils
- Skip error boundaries on route-level pages
Next.js Full-Stack
App Router + Prisma + NextAuth + Tailwind + Radix UI
# Project Rules — Next.js Full-Stack

## Tech Stack
- Next.js 14 + App Router + TypeScript
- Tailwind CSS + Radix UI primitives
- Prisma ORM + PostgreSQL
- NextAuth.js for authentication
- React Query for client-side data fetching
- Zod for validation

## Project Structure
src/
├── app/              → App Router pages and layouts
│   ├── (auth)/       → Auth-protected route group
│   ├── api/          → API route handlers
│   └── layout.tsx    → Root layout
├── components/
│   ├── ui/           → Primitive components (Button, Input, Dialog)
│   └── features/     → Feature-specific components
├── lib/              → Utilities, auth config, db client
├── prisma/           → Schema and migrations
└── types/            → Shared TypeScript types

## Server vs Client
- Default to Server Components — add "use client" only when needed
- Use Server Actions for mutations (form submissions, data writes)
- Use API routes only for webhooks, external integrations, or cron
- Fetch data in Server Components, pass to Client Components as props

## Database
- All schema changes go through Prisma migrations
- Run `npx prisma migrate dev --name <name>` for every change
- Always add reverse relations on both sides
- Use transactions for multi-table operations
- Never write raw SQL unless Prisma can't express the query

## API Routes
- Validate all input with Zod schemas
- Return consistent response shape: { data, error, message }
- Handle errors with try/catch — never let errors bubble unhandled
- Use middleware for auth checks on protected routes

## Authentication
- Use NextAuth.js session — never roll custom auth
- Check session in Server Components with getServerSession()
- Protect API routes with auth middleware
- Never expose user IDs in URLs — use server-side lookup

## Styling
- Tailwind utility classes — no custom CSS files
- Radix UI for accessible primitives (Dialog, Dropdown, Tabs)
- Consistent spacing: p-4, p-6, gap-4
- Mobile-first responsive: default mobile, then sm:, md:, lg:

## Do NOT
- Use `getServerSideProps` or `getStaticProps` — we use App Router
- Put database calls in Client Components
- Skip loading.tsx and error.tsx files for routes
- Use cookies/localStorage for auth — use NextAuth sessions
- Add packages without confirming first
Node.js Backend
Express + TypeScript + Prisma + Redis + JWT + Zod
# Project Rules — Node.js Backend

## Tech Stack
- Node.js 20 + Express + TypeScript
- Prisma ORM + PostgreSQL
- Redis for caching and sessions
- JWT for authentication
- Zod for request validation
- Winston for logging
- Vitest for tests

## Project Structure
src/
├── routes/         → Express route handlers
├── services/       → Business logic (one per domain)
├── middleware/      → Auth, validation, error handling
├── prisma/         → Schema and migrations
├── utils/          → Helpers, constants, types
├── jobs/           → Background jobs and cron tasks
└── index.ts        → App entry point

## API Design
- RESTful: GET (read), POST (create), PUT (replace), PATCH (update), DELETE (remove)
- URL pattern: /api/v1/{resource} — plural nouns, no verbs
- Consistent response: { success, data, error, message }
- Pagination: ?page=1&limit=20 — always paginate list endpoints
- Filter/sort via query params: ?status=active&sort=-createdAt

## Validation
- Validate ALL input at the route level using Zod
- Parse body, params, and query separately
- Return 400 with clear error messages for invalid input
- Never trust client data — validate even if frontend validated

## Error Handling
- Central error handler middleware — don't catch errors in routes
- Use custom ApiError class with status code and message
- Log all 500 errors with Winston — include stack trace
- Never return stack traces to the client
- Always return JSON — never HTML error pages

## Authentication
- JWT access tokens (short-lived, 15min)
- Refresh tokens (long-lived, 7 days, stored in DB)
- Auth middleware on every protected route
- Rate limit auth routes (login, register, forgot-password)

## Database
- Prisma for all queries — no raw SQL
- Run migrations: `npx prisma migrate dev --name <name>`
- Use transactions for multi-table writes
- Add indexes on frequently queried columns
- Soft delete (deletedAt) over hard delete

## Do NOT
- Use `any` type — TypeScript strict mode
- Console.log in production — use Winston logger
- Store secrets in code — use environment variables
- Skip input validation on any endpoint
- Add dependencies without asking first
Python Backend
FastAPI + SQLAlchemy + Pydantic + Alembic + Poetry
# Project Rules — Python Backend

## Tech Stack
- Python 3.12 + FastAPI + Uvicorn
- SQLAlchemy 2.0 + Alembic migrations
- PostgreSQL database
- Pydantic v2 for validation
- Poetry for dependency management
- Pytest for testing

## Project Structure
app/
├── api/
│   ├── v1/          → API route modules
│   └── deps.py      → Dependency injection
├── models/          → SQLAlchemy models
├── schemas/         → Pydantic request/response schemas
├── services/        → Business logic
├── core/            → Config, security, database setup
├── tests/           → Test modules
└── main.py          → FastAPI app entry point

## Conventions
- Type hints on every function — no untyped code
- Pydantic models for ALL request/response schemas
- Dependency injection for DB sessions, auth, etc.
- Async endpoints for I/O-bound operations
- snake_case for everything — files, functions, variables

## API Design
- RESTful endpoints under /api/v1/
- Pydantic schemas: Create, Update, Response variants
- Status codes: 200 (success), 201 (created), 400 (validation), 401 (unauth), 404 (not found)
- Pagination: offset/limit pattern
- Use FastAPI's built-in OpenAPI docs

## Database
- SQLAlchemy 2.0 style (mapped_column, DeclarativeBase)
- Alembic for all migrations — never alter DB manually
- Session per request via dependency injection
- Use async sessions with asyncpg for PostgreSQL

## Testing
- Pytest with async support (pytest-asyncio)
- Test database with automatic rollback per test
- httpx.AsyncClient for API tests
- Fixtures for common test data

## Do NOT
- Use global database sessions — use dependency injection
- Write raw SQL — use SQLAlchemy ORM
- Skip type hints — Pydantic and mypy enforce them
- Catch broad exceptions (except Exception) — be specific
- Add packages without confirming first
React Native / Expo
Expo SDK 51 + Expo Router + NativeWind + React Query
# Project Rules — React Native (Expo)

## Tech Stack
- Expo SDK 51 + React Native + TypeScript
- Expo Router for file-based navigation
- React Query for data fetching
- Zustand for client state
- NativeWind (Tailwind for RN) for styling
- Expo SecureStore for sensitive data

## Project Structure
src/
├── app/             → Expo Router pages (file-based routing)
├── components/      → Reusable UI components
├── hooks/           → Custom hooks
├── stores/          → Zustand stores
├── api/             → API client and endpoints
├── constants/       → Colors, sizes, config
└── utils/           → Helper functions

## Conventions
- Functional components only
- Platform-specific code via .ios.tsx / .android.tsx suffixes
- Expo modules over bare RN libraries when available
- TypeScript strict mode — no `any`

## Navigation
- Expo Router file-based routing
- Stack layout for main navigation
- Tab layout for bottom tabs
- Modal routes with presentation: "modal"

## Styling
- NativeWind (Tailwind) utility classes
- No inline StyleSheet.create unless NativeWind can't express it
- Consistent spacing: p-4, gap-3, rounded-xl
- Use theme colors from constants

## API & Data
- API base URL: switch between dev (localhost) and prod automatically
- React Query for server state — no manual fetch in useEffect
- Handle offline gracefully — show cached data when no network
- Expo SecureStore for tokens — never AsyncStorage for secrets

## Do NOT
- Use react-native-cli patterns — we use Expo
- Import from react-native directly when Expo has a module
- Hardcode API URLs — use config/constants
- Test on one platform only — always check iOS + Android
- Add native dependencies without confirming first
Monorepo (Turborepo)
Turborepo + pnpm workspaces + shared packages + TypeScript
# Project Rules — Monorepo (Turborepo)

## Tech Stack
- Turborepo for build orchestration
- pnpm workspaces for package management
- TypeScript (shared tsconfig)
- Shared packages for common code

## Project Structure
apps/
├── web/             → Next.js frontend
├── api/             → Express/Fastify backend
└── mobile/          → React Native / Expo
packages/
├── ui/              → Shared UI component library
├── config/          → Shared configs (ESLint, TS, Tailwind)
├── types/           → Shared TypeScript types
└── utils/           → Shared utility functions

## Conventions
- Shared code goes in packages/ — never duplicate between apps
- Each package has its own package.json and tsconfig.json
- Import shared packages by name: @repo/ui, @repo/types
- Changes to packages/ trigger rebuilds for all dependent apps
- Keep packages focused — one concern per package

## Dependencies
- Root package.json: only dev tools (turbo, typescript, eslint)
- App dependencies: in each app's package.json
- Shared dependencies: in each package's package.json
- Use pnpm — never npm or yarn

## Build & CI
- `turbo build` builds all apps in dependency order
- `turbo dev` runs all dev servers in parallel
- Turborepo caches builds — configure turbo.json properly
- CI uses remote caching (Vercel Remote Cache)
- Lint and test run in parallel per package

## Do NOT
- Install dependencies in root unless they're dev tools
- Import between apps directly — extract to a package
- Duplicate types/utils across apps — move to packages/
- Skip turbo.json outputs config — breaks caching
- Add workspace dependencies without confirming first
Better Together

How Skills + Rules Work Together

Rules define the "what to follow." Skills define the "how to do it." Together, they give your AI both context and process.

Rules
Project-wide conventions that apply to everything. Tech stack, file structure, naming, patterns, "do nots."
+
Skills
Task-specific processes for individual workflows. Step-by-step instructions, checklists, quality gates.
=
Consistent Output
AI knows both your standards and your processes. Code fits your codebase on the first try.
Writing Tips

Tips for Writing Your Own Rules

Make your project rules effective from day one. Here are the patterns that work best.

1
Start from a template
Pick the template above that matches your stack. Delete sections that don't apply, then customize the rest with your actual project details.
2
Be specific, not generic
Write "use Prisma for all queries" not "use an ORM." Write "Tailwind utility classes" not "CSS-in-JS." The more specific, the better the AI output.
3
Include real file paths
Reference your actual project structure: src/components/ui/ for primitives, src/api/ for endpoints. Real paths prevent the AI from guessing.
4
Add "Do NOT" sections
Explicitly list anti-patterns. "Do NOT use any type." "Do NOT put business logic in components." Negative rules prevent the most common AI mistakes.
5
Keep it under 500 lines
LLMs have context limits. A focused 200-300 line rules file beats a 2000-line encyclopedia. Prioritize the rules that matter most for your project.
6
Update quarterly
Your stack evolves. Review your rules every quarter: remove outdated patterns, add new conventions, update file paths after refactors.

Browse 66 Skills

Pair your project rules with structured skills for planning, building, reviewing, testing, and shipping.

Explore All Packs