Cursor Rules Examples
A well-written .cursorrules file tells Cursor AI how to write code in your project -- your preferred patterns, naming conventions, frameworks, and constraints. Without it, Cursor generates generic code that often needs heavy editing.
Browse production-ready Cursor rules examples for React, Next.js, TypeScript, Python, and other popular stacks. Each config is ready to copy into your project and customize to match your coding standards.
Cursor Rules Examples
Production-ready .cursorrules configs for popular stacks. Copy, customize, and drop into your project.
Next.js + TypeScript Cursor Rules
# .cursorrules — Next.js + TypeScript You are an expert Next.js 14+ developer using the App Router, TypeScript strict mode, and Tailwind CSS. ## Code Style - Use functional components with arrow function syntax - Prefer named exports over default exports for components - Use TypeScript strict mode — no `any` types, explicit return types on functions - Use path aliases: `@/` for src, `@db/` for database layer ## Next.js Patterns - Use Server Components by default; add 'use client' only when needed - Use `loading.tsx` for Suspense boundaries, `error.tsx` for error boundaries - API routes go in `app/api/` using `route.ts` convention - Use server actions in `lib/actions/` for form mutations - Dynamic routes use singular nouns: `/prompt/[id]`, not `/prompts/[id]` ## Styling - Tailwind CSS only — no CSS modules or styled-components - Use `cn()` utility (clsx + tailwind-merge) for conditional classes - Mobile-first responsive design with `sm:`, `md:`, `lg:` breakpoints - Dark mode via `class` strategy on root element ## State Management - React Context for global state; avoid Redux - Server state via fetch in Server Components - Client state via useState/useReducer; lift state minimally ## Error Handling - Always handle errors explicitly — no empty catch blocks - API routes return typed JSON responses with appropriate status codes - Use Zod for runtime validation of API inputs
Why it works: Covers the most common Next.js + TypeScript decisions Cursor has to make — component style, routing patterns, and styling approach — so generated code matches your project from the start.
React + Tailwind Component Rules
# .cursorrules — React Component Standards
You write React components using TypeScript, Tailwind CSS, and shadcn/ui primitives.
## Component Structure
- Props interface defined above the component, named `ComponentNameProps`
- Destructure props in the function signature
- Extract complex logic into custom hooks in `hooks/` directory
- Keep components under 150 lines; split into subcomponents if longer
## Naming
- Components: PascalCase (`UserProfile.tsx`)
- Hooks: camelCase with `use` prefix (`useUserData.ts`)
- Utilities: camelCase (`formatDate.ts`)
- Constants: UPPER_SNAKE_CASE
## Tailwind Conventions
- Use `cn()` for merging classes: `cn('base-class', condition && 'conditional-class')`
- Prefer Tailwind utilities over custom CSS
- Use design tokens from CSS custom properties for colors
- Group responsive classes: `text-sm md:text-base lg:text-lg`
## Accessibility
- All interactive elements must have visible focus states
- Images require alt text; decorative images use `alt=""`
- Use semantic HTML elements (`button`, `nav`, `main`) over generic `div`
- ARIA labels on icon-only buttons
## Performance
- Use `React.memo` only when profiling shows re-render issues
- Prefer `useMemo` / `useCallback` for expensive computations, not for every function
- Lazy load components below the fold with `dynamic()` or `React.lazy`Why it works: Establishes a consistent component architecture so Cursor generates components that feel like they belong in your codebase, not generic examples.
Python FastAPI Cursor Rules
# .cursorrules — Python FastAPI You are an expert Python developer using FastAPI, Pydantic v2, and SQLAlchemy 2.0. ## Code Style - Python 3.11+ features (type hints, match statements, f-strings) - Use Pydantic BaseModel for all request/response schemas - Async functions by default for all route handlers - Type hints on all function parameters and return values ## Project Structure - Routes in `app/api/routes/` — one file per resource - Schemas in `app/schemas/` — request and response models - Services in `app/services/` — business logic separated from routes - Models in `app/models/` — SQLAlchemy ORM models ## API Patterns - Use dependency injection for database sessions and auth - Return Pydantic models from routes, never raw dicts - Use HTTPException with specific status codes and detail messages - Paginate list endpoints with `limit` and `offset` query params ## Database - SQLAlchemy 2.0 style with `select()` statements, not legacy `query()` - Alembic for migrations — never modify tables directly - Use async session for all database operations - Foreign keys and indexes on all relationship columns ## Error Handling - Custom exception handlers for domain-specific errors - Log errors with structlog, include request context - Never expose internal error details in API responses - Validate all inputs at the Pydantic layer before hitting the database
Why it works: Covers FastAPI-specific patterns like dependency injection, Pydantic v2 schemas, and SQLAlchemy 2.0 style that Cursor often gets wrong without explicit guidance.
Cursor Rules Generator
Generate a .cursorrules file for my project. Project details: - Language: {{language}} - Framework: {{framework}} - Styling: {{styling_approach}} - Database: {{database}} - Key libraries: {{key_libraries}} My coding preferences: - {{preference_1}} - {{preference_2}} - {{preference_3}} Generate a comprehensive .cursorrules file that covers: 1. Code style and formatting conventions 2. Framework-specific patterns and anti-patterns 3. File and folder naming conventions 4. State management approach 5. Error handling patterns 6. Testing conventions 7. Performance guidelines 8. Accessibility requirements (if frontend) 9. Database query patterns (if applicable) 10. API design conventions (if applicable) Format as a ready-to-use .cursorrules file with clear markdown headers. Be specific to my stack — generic advice is useless. Include examples where the convention is non-obvious.
Why it works: A generated rules file customized to your exact stack is immediately useful. Requiring examples for non-obvious conventions prevents ambiguous rules that Cursor interprets inconsistently.
Drizzle ORM + PostgreSQL Rules
# .cursorrules — Drizzle ORM + PostgreSQL
You write database code using Drizzle ORM with PostgreSQL.
## Schema Conventions
- All table definitions in a single `schema.ts` file (single source of truth)
- Use camelCase in TypeScript; Drizzle maps to snake_case columns automatically
- All IDs are UUIDs using `uuid('id').defaultRandom().primaryKey()`
- Every table has `createdAt` and `updatedAt` timestamp columns
- Define relations explicitly with `relations()` function
## Query Patterns
- Use Drizzle query builder, not raw SQL, for type safety
- Always select only needed columns — avoid `select *`
- Use `.$with()` for reusable query fragments
- Transactions for multi-table mutations: `db.transaction(async (tx) => {...})`
## Migrations
- Generate migrations with `drizzle-kit generate`
- Review generated SQL before applying
- Never use `db push` in staging or production
- One migration per logical change — do not batch unrelated schema changes
## Naming
- Tables: plural snake_case (`user_prompts`, `api_keys`)
- Columns: snake_case (`created_at`, `user_id`)
- TypeScript types: PascalCase (`UserPrompt`, `ApiKey`)
- Indexes: `idx_tablename_columns` pattern
## Security
- RLS enabled on all user-data tables
- Never use service role client in user-facing routes
- Validate all user input with Zod before database operations
- Parameterized queries only — never string interpolation in SQLWhy it works: Drizzle ORM has specific patterns around schema definition and migration workflow. These rules prevent the most common mistakes: using db push in production, missing RLS, and inconsistent naming.
Testing-Focused Cursor Rules
# .cursorrules — Testing Standards When writing or modifying code, always consider testability. When asked to write tests, follow these conventions. ## Test Framework - Framework: {{test_framework}} - Assertion style: {{assertion_style}} - Mocking: {{mocking_library}} ## Test Structure - File naming: `ComponentName.test.tsx` or `function-name.test.ts` - Describe blocks mirror the module structure - Each test has a clear name: "should [expected behavior] when [condition]" - Arrange-Act-Assert pattern in every test ## What to Test - Public API of every module (exported functions and components) - Edge cases: empty inputs, null values, maximum lengths, concurrent access - Error paths: network failures, invalid data, permission denied - Integration points: API calls, database queries, external services ## What NOT to Test - Implementation details (private functions, internal state) - Third-party library behavior - Styling or layout (use visual regression tools instead) ## Test Quality Rules - No test should depend on another test's state - Mock external dependencies, not internal modules - Test data factories over hardcoded fixtures - Each test file should run in under 5 seconds - Coverage target: {{coverage_target}}% on business logic, not measured on UI components
Why it works: Without testing rules, Cursor writes tests that are either too shallow (just smoke tests) or too coupled (testing implementation details). These rules target the right balance.
Recommended tools & resources
.cursorrules, CLAUDE.md, and Copilot configs for every stack.
Model GuidesTips for getting the best output from Cursor AI models.
Engineer Starter KitPrompt kit built for software engineers using AI tools.
Prompt BuilderGenerate structured prompts for Cursor and other AI editors.
AI Agent SpecsSpecification templates for Cursor agent-mode tasks.
Prompt TemplatesCopy-ready prompts for code generation and review.