DEV Community

Cover image for Setting Up Cursor Rules: The Complete Guide to AI-Enhanced Development
Vitalii
Vitalii

Posted on

Setting Up Cursor Rules: The Complete Guide to AI-Enhanced Development

Transform your coding experience with properly configured Cursor Rules that actually work

What Are Cursor Rules?

Think of Cursor Rules as your AI assistant's instruction manual. They're custom guidelines that tell Cursor's AI how to behave when writing code, making suggestions, and helping with your project. Instead of generic responses, you get context-aware help that understands your specific tech stack, coding patterns, and project structure.

Why Most Developers Set Up Cursor Rules Wrong

Most developers either:

  1. Skip rules entirely - Missing out on 80% of Cursor's potential
  2. Copy-paste generic rules - Getting mediocre, one-size-fits-all responses
  3. Write overly complex rules - Confusing the AI with too many instructions
  4. Use outdated .cursorrules files - Missing the new powerful features

The Right Way: Project Rules vs Global Rules

Project Rules (Recommended)

Store rules in .cursor/rules/ directory - they're version-controlled and specific to your project.

Global Rules

Set in Cursor Settings for preferences that apply to all projects (coding style, communication preferences).

Setting Up Your First Rule

Step 1: Create a Basic Rule File

# Create the rules directory mkdir -p .cursor/rules # Create your first rule touch .cursor/rules/project-overview.mdc 
Enter fullscreen mode Exit fullscreen mode

Step 2: Write Your Rule

Create a file with this structure:

--- description: "Core project context and patterns" globs: alwaysApply: true --- 
Enter fullscreen mode Exit fullscreen mode

Then add your rule content:

# My Project Rules ## Tech Stack - Frontend: React 18 + TypeScript + Vite - Backend: Node.js + Express + MongoDB - Styling: Tailwind CSS ## Code Standards - Use TypeScript for all new files - Prefer functional components over classes - Always include error handling - Use descriptive variable names ## File Structure - Components in `/src/components/` - Utilities in `/src/utils/` - API calls in `/src/services/` 
Enter fullscreen mode Exit fullscreen mode

Rule Types Explained

1. Always Applied Rules

YAML Configuration:

--- description: Core project context alwaysApply: true --- 
Enter fullscreen mode Exit fullscreen mode

Perfect for: Project overview, tech stack, coding standards

2. Auto-Attached Rules

YAML Configuration:

--- description: React component patterns globs: ["**/*.tsx", "**/*.jsx"] alwaysApply: false --- 
Enter fullscreen mode Exit fullscreen mode

Perfect for: File-type specific patterns (React components, API routes, etc.)

3. Manual Rules

YAML Configuration:

--- description: Database migration guide alwaysApply: false --- 
Enter fullscreen mode Exit fullscreen mode

Perfect for: Specific workflows you trigger with @rule-name

Real-World Example: CraftYourStartup Boilerplate

Let me show you how we set up Cursor Rules for our production FastAPI + React boilerplate:

Core Project Rule

File: .cursor/rules/000-core-project.mdc

Configuration:

--- description: CraftYourStartup boilerplate architecture alwaysApply: true --- 
Enter fullscreen mode Exit fullscreen mode

Rule Content:

# CraftYourStartup Boilerplate ## Architecture - **Backend**: FastAPI + SQLModel + PostgreSQL - **Frontend**: React 18 + TypeScript + MUI v6 - **Authentication**: JWT + OAuth (Google) - **Payments**: Stripe integration ## Clean Architecture Pattern ALWAYS follow: Controllers → Services → Models - **Controllers** (`app/controllers/`): HTTP handling only - **Services** (`app/services/`): Business logic - **Models** (`app/models.py`): Database models ## Development Commands 
Enter fullscreen mode Exit fullscreen mode
# Backend task run-backend # Start server task alembic-upgrade-local # Run migrations # Frontend  npm run dev # Start frontend npm run generate-client # Sync API types 
Enter fullscreen mode Exit fullscreen mode

Backend-Specific Rules

File: .cursor/rules/backend/backend-patterns.mdc

Configuration:

--- description: FastAPI backend patterns globs: ["app/**/*.py"] alwaysApply: false --- 
Enter fullscreen mode Exit fullscreen mode

Rule Content:

# Backend Development Patterns ## Service Layer Pattern 
Enter fullscreen mode Exit fullscreen mode

Example Service:

class ArticleService: def __init__(self, db: Session): self.db = db async def create_article(self, data: ArticleCreate, user_id: uuid.UUID): # Validation  if len(data.title.strip()) < 3: raise ValidationException("Title too short") # Business logic  article = Article(**data.model_dump(), user_id=user_id) self.db.add(article) self.db.commit() return ArticleRead.model_validate(article) 
Enter fullscreen mode Exit fullscreen mode

Example Controller:

@router.post("/articles", response_model=ArticleRead) async def create_article( article_data: ArticleCreate, current_user: User = Depends(get_current_user), service: ArticleService = Depends(get_article_service), ): return await service.create_article(article_data, current_user.id) 
Enter fullscreen mode Exit fullscreen mode

Frontend-Specific Rules

File: .cursor/rules/frontend/frontend-patterns.mdc

Configuration:

--- description: React component patterns globs: ["frontend/**/*.tsx", "frontend/**/*.ts"] alwaysApply: false --- 
Enter fullscreen mode Exit fullscreen mode

Rule Content:

# Frontend Development Patterns ## Component Structure 
Enter fullscreen mode Exit fullscreen mode

Example Component:

interface ComponentProps { title: string; onAction?: (id: string) => void; } const Component: React.FC<ComponentProps> = ({ title, onAction }) => { const { data, isLoading, error } = useQuery(); const { handleError } = useErrorHandler(); if (error) { handleError(error); return null; } return ( <Container> {isLoading ? <CircularProgress /> : <Content />} </Container>  ); }; 
Enter fullscreen mode Exit fullscreen mode

Example API Integration:

export const useCreateArticle = () => { return useMutation({ mutationFn: ArticlesService.createArticle, onError: handleApiError, }); }; 
Enter fullscreen mode Exit fullscreen mode

Advanced Rules: Templates and References

Using Template References

File: .cursor/rules/templates/service-guide.mdc

Configuration:

--- description: Service template for new features --- 
Enter fullscreen mode Exit fullscreen mode

Rule Content:

# Service Template When creating new services, use this template: @templates/service-template.py This ensures consistent patterns across all services. 
Enter fullscreen mode Exit fullscreen mode

Template File Example

File: .cursor/rules/templates/service-template.py

from sqlmodel import Session, select from app.core.exceptions import NotFoundException, ValidationException from app.models import {ModelName} from app.schemas.{schema_name} import {ModelName}Create, {ModelName}Update, {ModelName}Read class {ModelName}Service: def __init__(self, db: Session): self.db = db async def create_{model_name}(self, data: {ModelName}Create, user_id: uuid.UUID) -> {ModelName}Read: # Add validation logic here  # Create instance  instance = {ModelName}(**data.model_dump(), user_id=user_id) self.db.add(instance) self.db.commit() self.db.refresh(instance) return {ModelName}Read.model_validate(instance) async def get_{model_name}(self, {model_name}_id: int, user_id: uuid.UUID) -> {ModelName}Read: statement = select({ModelName}).where( {ModelName}.id == {model_name}_id, {ModelName}.user_id == user_id ) result = self.db.exec(statement).first() if not result: raise NotFoundException(f"{ModelName} not found") return {ModelName}Read.model_validate(result) 
Enter fullscreen mode Exit fullscreen mode

Testing Your Rules

Quick Test Commands

# Test if rules are loading ls -la .cursor/rules/ # Test auto-attached rules # Open a Python file and ask: "Create a new service following our patterns" # Open a React file and ask: "Create a new component following our conventions" # Test manual rules # Type: @database-migration help me create a migration 
Enter fullscreen mode Exit fullscreen mode

Validation Checklist

  • [ ] Rules appear in Cursor's sidebar when active
  • [ ] Auto-attached rules trigger in correct file types
  • [ ] Manual rules respond when using @rule-name
  • [ ] Templates are referenced correctly
  • [ ] AI responses follow your established patterns

Common Mistakes to Avoid

1. Rules Too Long

Bad: 1000+ line rules that overwhelm the AI

Good: Focused rules under 500 lines each

2. Vague Instructions

Bad: "Write good code"

Good: "Use TypeScript interfaces for all props"

3. Missing Context

Bad: Just listing technologies

Good: Explaining how technologies work together

4. No Examples

Bad: "Follow our patterns"

Good: Including actual code examples

Best Practices

1. Start Simple

Begin with one core rule covering your tech stack and basic patterns.

2. Use Clear Descriptions

--- description: "React component patterns with MUI and error handling" --- 
Enter fullscreen mode Exit fullscreen mode

3. Reference Real Files

Look at @components/UserCard.tsx for component structure examples. 
Enter fullscreen mode Exit fullscreen mode

4. Keep Rules Updated

Update rules when you change patterns or add new technologies.

5. Test Regularly

Regularly test that your rules produce the expected behavior.

Advanced Organization

Directory Structure

.cursor/rules/ ├── 000-core-project.mdc # Always applied ├── 100-api-workflow.mdc # Manual workflows ├── backend/ │ └── backend-patterns.mdc # Auto-attached to .py files ├── frontend/ │ └── frontend-patterns.mdc # Auto-attached to .tsx files └── templates/ ├── service-template.py └── component-template.tsx 
Enter fullscreen mode Exit fullscreen mode

Rule Naming Convention

  • 000-099: Always applied rules
  • 100-199: Manual workflow rules
  • 200-299: Auto-attached rules
  • templates/: Referenced templates

Troubleshooting

Rules Not Working?

  1. Check file extension (must be .mdc)
  2. Verify frontmatter syntax
  3. Ensure correct glob patterns
  4. Restart Cursor after changes

AI Ignoring Rules?

  1. Rules might be too long
  2. Multiple conflicting rules
  3. Need more specific examples
  4. Try breaking into smaller rules

The AI Velocity Advantage

When you properly configure Cursor Rules, you unlock what we call "AI Velocity" - the ability to build features dramatically faster while maintaining quality. With our CraftYourStartup boilerplate, developers report:

  • 10x faster feature development - From idea to working code in minutes
  • Consistent code quality - AI follows your established patterns
  • Reduced context switching - AI understands your entire stack
  • Better documentation - Rules serve as living documentation

This velocity advantage becomes your competitive edge, allowing you to iterate faster, ship more features, and respond to market needs with unprecedented speed.

Ready to Transform Your Development?

Cursor Rules aren't just a nice-to-have - they're essential for any developer serious about leveraging AI effectively. Start with a simple project rule, add auto-attached patterns for your main file types, and watch your productivity soar.

The future of development is AI-assisted, and properly configured Cursor Rules are your ticket to that future.


Want to see these patterns in action? Check out our complete startup boilerplate at CraftYourStartup.com - it includes production-ready Cursor Rules that have helped hundreds of developers ship faster.

Top comments (0)