Cursor Rules - Custom AI Instructions
Configure AI behavior with .cursorrules files for consistent, project-specific code generation
💡 What You'll Learn
- Create .cursorrules files to guide AI behavior
- Set project-wide coding standards and conventions
- Examples of effective Cursor Rules
- Team Rules vs. Project Rules
📜 What are Cursor Rules?
Cursor Rules are custom instructions that tell the AI how to generate code for your project. They ensure consistency across your team and enforce your coding standards automatically.
🎯 Perfect For:
- 🎨 Enforcing code style (tabs vs spaces, naming conventions)
- 📦 Specifying preferred libraries and frameworks
- 🏗️ Defining project architecture patterns
- 📝 Setting documentation requirements
- 🚫 Avoiding deprecated or unwanted patterns
📁 Creating a .cursorrules File
Create a file named .cursorrules in your project root:
├── .cursorrules ← Create this file
├── package.json
├── src/
└── ...
✍️ Example .cursorrules Files
Example 1: React + TypeScript Project
# React + TypeScript Project Rules
## Code Style
- Use TypeScript for all files (.ts, .tsx)
- Use functional components with hooks
- Use arrow functions: const MyComponent = () => {}
- Use named exports, not default exports
- Use 2 spaces for indentation
- Use single quotes for strings
- Add semicolons at end of statements
## Component Guidelines
- Use TypeScript interfaces for props
- Name components with PascalCase
- Keep components small and focused (< 200 lines)
- Extract complex logic into custom hooks
- Use Tailwind CSS for styling (no CSS modules)
## State Management
- Use React hooks (useState, useEffect, useContext)
- For global state, use Zustand
- Never use Redux
## File Organization
- Components in src/components/
- Hooks in src/hooks/
- Types in src/types/
- Utils in src/utils/
## Documentation
- Add JSDoc comments for complex functions
- Include prop descriptions in TypeScript interfaces
- Add README.md for each major feature
## Testing
- Write tests using Vitest
- Use React Testing Library for component tests
- Aim for 80% coverage
## Avoid
- Class components
- PropTypes (use TypeScript)
- Inline styles (use Tailwind)
- Any type (be specific)
- console.log in production codeExample 2: Next.js App Router Project
# Next.js 15 App Router Rules ## Framework Conventions - Use Next.js 15 App Router (not Pages Router) - Server Components by default - Add "use client" only when necessary - Use Server Actions for mutations - Use route handlers for API endpoints ## File Structure - Pages in src/app/ - Components in src/components/ - Server actions in src/app/actions/ - API routes in src/app/api/ ## Data Fetching - Use async Server Components for data fetching - Use fetch with Next.js caching - Use Server Actions for form submissions - Never use useEffect for data fetching ## Styling - Use Tailwind CSS - Use CSS variables for theming - Mobile-first responsive design ## Performance - Use next/image for images - Use next/font for fonts - Implement loading.tsx and error.tsx - Use Suspense for streaming ## SEO - Add metadata to every page - Use generateMetadata for dynamic pages - Include OpenGraph and Twitter cards ## TypeScript - Strict mode enabled - No any types - Define return types for functions
Example 3: Python Backend Project
# Python FastAPI Backend Rules ## Code Style - Follow PEP 8 style guide - Use type hints for all functions - Use async/await for I/O operations - Use 4 spaces for indentation - Maximum line length: 88 characters (Black formatter) ## Framework - Use FastAPI for API endpoints - Use Pydantic for data validation - Use SQLAlchemy for database ORM - Use Alembic for migrations ## Project Structure - API routes in app/routes/ - Models in app/models/ - Schemas in app/schemas/ - Database logic in app/db/ - Business logic in app/services/ ## Error Handling - Use HTTPException for API errors - Include descriptive error messages - Log errors with proper severity levels - Never expose internal errors to clients ## Security - Use environment variables for secrets - Validate all user input with Pydantic - Use OAuth2 with JWT tokens - Hash passwords with bcrypt ## Testing - Use pytest for testing - Mock external dependencies - Aim for 90% code coverage - Include integration tests for API endpoints ## Documentation - Add docstrings to all functions (Google style) - Keep OpenAPI/Swagger docs up to date - Include example requests/responses
⚙️ Team Rules vs. Project Rules
Cursor 1.7.38 supports Team Rules for organization-wide standards:
📁 Project Rules
.cursorrules in project root
- ✅ Project-specific patterns
- ✅ File organization
- ✅ Architecture decisions
- ✅ Committed to git
- ✅ Applies to this project only
👥 Team Rules
Settings → Cursor Settings → Rules for Cursor AI
- ✅ Company-wide standards
- ✅ Code style preferences
- ✅ Security requirements
- ✅ Shared across all projects
- ✅ Set once per workspace
🎯 Rules Best Practices
✅ Effective Rules
- Be specific: "Use Zustand" not "Use good state management"
- Include examples: Show preferred patterns
- Explain why: Help AI understand reasoning
- Keep it organized: Use headers and sections
- Update regularly: Evolve with your project
❌ Ineffective Rules
- "Write good code" (too vague)
- "Follow best practices" (unclear)
- Extremely long rules (>1000 lines)
- Contradictory requirements
- Generic rules copied from elsewhere
📝 Rules Template
Start with this template and customize for your project:
# [Project Name] Cursor Rules ## Overview [Brief description of project and tech stack] ## Code Style - Language: [e.g., TypeScript, Python] - Formatter: [e.g., Prettier, Black] - Linter: [e.g., ESLint, Pylint] - Indentation: [spaces/tabs, size] - Quotes: [single/double] - [Other style preferences] ## Framework & Libraries - Primary framework: [e.g., Next.js, FastAPI] - Preferred libraries: - [Library 1]: [Use case] - [Library 2]: [Use case] - Avoid: - [Library to avoid]: [Reason] ## File Organization - [Directory]: [Purpose] - [Directory]: [Purpose] - Naming conventions: [Details] ## Component/Function Guidelines - [Specific patterns to follow] - [Size limits] - [Documentation requirements] ## State Management - [Approach to use] - [When to use what] ## Error Handling - [How to handle errors] - [Logging approach] ## Testing - Framework: [e.g., Jest, pytest] - Coverage target: [e.g., 80%] - [Testing conventions] ## Security - [Security requirements] - [Authentication approach] ## Performance - [Performance guidelines] - [Optimization strategies] ## Documentation - [Documentation requirements] - [Comment style] ## Avoid - [Anti-patterns] - [Deprecated features] - [Known issues]
⚡ Pro Tips
💡 Tip 1: Start simple and add rules as patterns emerge
💡 Tip 2: Reference your rules in prompts: "Follow .cursorrules"
💡 Tip 3: Review AI-generated code against rules regularly
💡 Tip 4: Share .cursorrules with your team in git
💡 Tip 5: Use both Team Rules (global) and Project Rules (specific)
🎓 Practice Exercise
Create Your .cursorrules:
- Create
.cursorrulesfile in your project root - Add your code style preferences (indentation, quotes, etc.)
- List your preferred libraries and frameworks
- Define your file organization structure
- Add 3-5 "Avoid" items (anti-patterns)
- Test it: Ask Cursor to create a new component
- Verify the AI follows your rules
📊 Before vs. After Rules
❌ Without Rules
- Inconsistent code style
- Mixed patterns across files
- Wrong library choices
- Need to correct AI constantly
- Time spent on code review
✅ With Rules
- Consistent, predictable code
- Follows project conventions
- Uses preferred libraries
- AI "gets it right" first time
- Faster development
🐛 Common Issues
AI doesn't follow my rules
Rules might be too vague. Be more specific and explicit. Also, mention "follow .cursorrules" in your prompts.
.cursorrules file not being detected
Ensure file is named exactly .cursorrules (with the dot) and is in project root. Restart Cursor if needed.
Rules are too complex
Start simple with 10-20 rules. Add more as needed. The AI can only process so much context.
🔗 Next Steps
Now that you've set up rules, learn about keyboard shortcuts for maximum speed: Essential Settings & Shortcuts →