Automatic Context
Rules become part of the AI’s context automatically, like having a senior developer always guiding the junior
Ta treść nie jest jeszcze dostępna w Twoim języku.
Project rules are the foundation of effective AI-assisted development. In this 10-minute guide, you’ll learn to create rules that ensure consistent code generation aligned with your team’s standards.
.cursor/rules/├── always/ # Applied to every AI interaction├── auto-attached/ # Applied based on file patterns├── agent-requested/ # AI decides when to apply└── manual/ # Only when explicitly referenced
Automatic Context
Rules become part of the AI’s context automatically, like having a senior developer always guiding the junior
Version Controlled
Check rules into Git so your entire team benefits from shared knowledge and standards
Hierarchical
Rules cascade from project root to subdirectories, with local rules overriding global ones
Dynamic Updates
Update rules on the fly - AI immediately adopts new guidelines without restart
Open Command Palette: Cmd/Ctrl + Shift + P
Run Generation Command: “Generate Cursor Rules”
Review Generated Structure:
.cursor/rules/├── code-style.mdc├── architecture.mdc├── testing.mdc└── documentation.mdc
Customize Generated Rules: Edit each file to match your standards
Cursor analyzes your codebase and creates rules for:
Always Applied Rules
Rules that apply to every AI interaction. Use sparingly for universal standards.
---description: Core coding standardsalwaysApply: true---
# Universal Standards
- Never commit secrets or API keys- Always handle errors explicitly- Use TypeScript strict mode- Follow ESLint configuration- Include unit tests for new functions
---description: React component standardsglobs: ["src/components/**/*.tsx"]---
# React Component Rules
- Use functional components only- Implement proper TypeScript props- Include Storybook stories- Use CSS modules for styling- Follow atomic design principles
## Component Structure```typescriptinterface ComponentProps { // Documented props}
export const Component: FC<ComponentProps> = (props) => { // Implementation};
---description: API endpoint standardsglobs: ["src/api/**/*.ts"]---
# API Development Rules
- Use RESTful conventions- Implement proper error handling- Include OpenAPI documentation- Validate all inputs with Zod- Return consistent response formats
## Response Format```typescript{ success: boolean; data?: T; error?: { code: string; message: string }; meta?: { page: number; total: number };}
---description: Database and ORM patternsglobs: ["src/db/**/*.ts", "prisma/**/*"]---
# Database Rules
- Use migrations for schema changes- Never use raw SQL in application code- Implement soft deletes- Add indexes for foreign keys- Use transactions for multi-table updates
## Naming Conventions- Tables: plural_snake_case- Columns: snake_case- Indexes: idx_table_columns
---description: Performance optimization guidelines - AI uses when optimizing codealwaysApply: false---
# Performance Optimization
When optimizing code:- Profile before optimizing- Document performance improvements- Consider memory vs CPU tradeoffs- Use caching strategically- Implement lazy loading where appropriate
---description: Legacy code handling - use @legacy-rulesalwaysApply: false---
# Legacy Code Guidelines
When working with legacy code:- Maintain backward compatibility- Add deprecation warnings- Create migration guides- Test extensively before refactoring
Be Specific and Actionable
❌ "Write good code"✅ "Use const for immutable values, let for mutable"
Include Examples
## Error Handling Pattern```typescripttry { const result = await riskyOperation(); return { success: true, data: result };} catch (error) { logger.error('Operation failed', { error, context }); return { success: false, error: error.message };}
Provide Context
# Why This RuleWe use dependency injection to improve testabilityand reduce coupling between modules.
Keep Rules Focused
---description: Security best practicesalwaysApply: true---
# Security Standards
## Authentication- Use JWT tokens with short expiration- Implement refresh token rotation- Store sensitive data in environment variables- Hash passwords with bcrypt (min 10 rounds)
## Input Validation- Sanitize all user inputs- Use parameterized queries- Implement rate limiting- Validate file uploads
## NEVER- Log passwords or tokens- Use eval() or dynamic code execution- Trust client-side validation- Store secrets in code
---description: Testing standards and patternsglobs: ["**/*.test.ts", "**/*.spec.ts"]---
# Testing Guidelines
## Test Structure- Use AAA pattern (Arrange, Act, Assert)- One assertion per test when possible- Descriptive test names that explain the scenario
## Coverage Requirements- Minimum 80% code coverage- 100% coverage for critical paths- Test edge cases and error scenarios
## Example Test```typescriptdescribe('UserService', () => { describe('createUser', () => { it('should hash the password before saving', async () => { // Arrange const userData = { email: 'test@example.com', password: 'plain' };
// Act const user = await userService.createUser(userData);
// Assert expect(user.password).not.toBe('plain'); expect(bcrypt.compareSync('plain', user.password)).toBe(true); }); });});
---description: Documentation standardsalwaysApply: false---
# Documentation Requirements
## Code Comments- JSDoc for all public functions- Explain WHY, not WHAT- Document complex algorithms- Include examples for utilities
## JSDoc Template
/** * Calculates the compound interest * @param principal - Initial amount * @param rate - Annual interest rate (as decimal) * @param time - Time period in years * @param n - Compounding frequency per year * @returns The final amount after compound interest * @example * calculateCompoundInterest(1000, 0.05, 2, 12) // $1104.94 */
## README Sections1. Project Overview2. Quick Start3. Architecture4. API Documentation5. Contributing Guidelines
During Development:
AI: "I'll use PostgreSQL for this feature"You: "# Always use MySQL for our projects, not PostgreSQL"
Rule Gets Added:
# Database ChoiceAlways use MySQL for our projects, not PostgreSQL
Immediate Effect: Next request will use MySQL
After a productive session:
/Generate Cursor Rules
in chat.cursor/rules/├── features/│ ├── authentication/│ │ ├── jwt-tokens.mdc│ │ └── oauth-flow.mdc│ ├── payments/│ │ ├── stripe-integration.mdc│ │ └── invoice-generation.mdc│ └── notifications/│ ├── email-templates.mdc│ └── push-notifications.mdc
.cursor/rules/├── presentation/│ ├── components.mdc│ └── styles.mdc├── business/│ ├── services.mdc│ └── validation.mdc└── data/ ├── repositories.mdc └── migrations.mdc
.cursor/rules/├── performance/│ ├── caching.mdc│ └── optimization.mdc├── security/│ ├── authentication.mdc│ └── encryption.mdc└── quality/ ├── testing.mdc └── code-review.mdc
---description: Environment-specific rulesglobs: ["src/**/*.ts"]---
# Environment Rules
## DevelopmentWhen NODE_ENV is development:- Use verbose logging- Enable debug endpoints- Skip email sending
## ProductionWhen NODE_ENV is production:- Use structured logging- Disable debug endpoints- Implement rate limiting
---description: Architecture patterns---
# Follow Our Architecture
Implement patterns from:@architecture/diagrams/system-design.png@architecture/decisions/adr-001.md
Key principles:- Event-driven communication- CQRS for complex domains- Repository pattern for data access
---description: Refactoring guidelinesglobs: ["src/legacy/**/*"]---
# Legacy Code Refactoring
## Phase 1: Add Types- Add TypeScript types to interfaces- Document existing behavior- Don't change functionality
## Phase 2: Extract Functions- Break large functions < 50 lines- Extract reusable utilities- Add unit tests
## Phase 3: Modernize- Convert to async/await- Use modern JS features- Update dependencies
Over-Specification
Don’t create rules for every tiny detail - focus on important patterns
Contradictions
Ensure rules don’t conflict with each other or existing tools
Outdated Rules
Review and update rules quarterly as your project evolves
Vague Instructions
Replace “write clean code” with specific, measurable guidelines
Create Test Scenario:
"Create a new API endpoint for user profiles"
Verify AI Follows Rules:
Iterate if Needed:
Commit to Git:
git add .cursor/rules/git commit -m "Add project coding standards"git push
Document in README:
## AI Coding Standards
This project uses Cursor rules for consistent AI assistance.Rules are in `.cursor/rules/` and automatically apply.
To update rules:1. Edit relevant `.mdc` files2. Test with AI3. Commit changes
Regular Reviews:
Continue to PRD Workflow
Now let’s master the PRD → Plan → Todo workflow that transforms how you build features.
Time: 15 minutes