TL;DR

Cursor rules make the AI behave like a team member who knows your patterns. Start small, apply rules to specific file globs, and use concrete do/don’t examples. Iterate after testing.

Why Cursor Rules Matter

Cursor rules are like having a coding mentor that never forgets your preferences. They help the AI understand your project’s specific patterns, coding standards, and architectural decisions. But creating effective rules isn’t just about writing instructions—it’s about creating a shared language between you and the AI.

In this guide, I’ll show you how to create Cursor rules that actually work, with concrete examples you can implement today. For background on how I integrate AI into my workflow, see my post on how I’m using AI. You can also explore the PostgreSQL search series for an example of consistent rule-driven authoring across a series.

Understanding the Basics

Cursor rules are markdown files stored in the .cursor/rules/ directory of your project. They follow a specific structure that tells the AI when to apply certain guidelines and what those guidelines should be.

The Rule Structure

Every Cursor rule has three main components:

  • Rule Name: A descriptive identifier for the rule
  • When Condition: When the rule should be applied
  • Enforce Actions: What the AI should do when the condition is met
---
description: Example rule structure for Cursor rules
globs: src/**/*.ts
alwaysApply: false
---
# Example Rule Structure
## When to Apply This Rule
- When working with TypeScript files
- When creating new components
- When modifying existing code
## Guidelines
### Code Style
- Use consistent naming conventions
- Follow established patterns
- Include proper documentation
### Best Practices
- Write clean, readable code
- Include proper error handling
- Use TypeScript features appropriately

Creating Your First Rule

Let’s start with a practical example. Say you want the AI to follow specific patterns when working with React components in your project.

Step 1: Identify the Need

Think about what frustrates you when working with AI on your codebase. Common pain points include:

  • AI not following your naming conventions
  • AI suggesting patterns that don’t match your architecture
  • AI missing important imports or dependencies
  • AI not understanding your project’s specific requirements

Step 2: Define the Scope

Be specific about when the rule should apply. Instead of “when working with React,” try “when creating new React components in the src/components/ directory.”

Step 3: Write Clear Instructions

Here’s a concrete example for React components:

---
description: React component development guidelines
globs: src/components/**/*.tsx
alwaysApply: false
---
# React Component Guidelines
## When to Apply This Rule
- When creating new React components in \`src/components/\`
- When modifying existing React components
- When working with TypeScript and React
## Component Structure
### New Components
- Always use TypeScript with proper interface definitions
- Use functional components with hooks, not class components
- Include PropTypes or TypeScript interfaces for all props
- Use camelCase for component names and PascalCase for component files
- Import React from 'react' even if not explicitly used
- Include JSDoc comments for complex components
- Use the existing design system colors and spacing
### Modifying Existing Components
- Maintain existing prop interfaces unless explicitly changing them
- Follow the established naming patterns in the file
- Preserve existing import structure
- Update JSDoc comments when changing component behavior
## Best Practices
### Code Organization
- Group related imports together
- Use consistent spacing and formatting
- Include proper error boundaries where needed
### Performance Considerations
- Use React.memo for expensive components
- Implement proper dependency arrays in useEffect
- Avoid unnecessary re-renders

Advanced Rule Strategies

File-Type Specific Rules

You can create rules that apply to specific file types or directories:

---
description: API development standards and guidelines
globs: src/api/**/*.ts
alwaysApply: false
---
# API Development Standards
## When to Apply This Rule
- When working with files in \`src/api/\`
- When creating new API endpoints
- When handling database operations
## API Structure
### Database Operations
- Use async/await for all database operations
- Include proper error handling with try/catch blocks
- Return consistent JSON response structures
- Use HTTP status codes appropriately (200, 201, 400, 404, 500)
- Validate input data before processing
- Include request logging for debugging
### New Endpoints
- Follow RESTful naming conventions
- Include input validation using Zod or similar
- Add proper TypeScript types for request/response
- Include error handling for common failure cases
## Best Practices
### Error Handling
- Always wrap database calls in try/catch
- Return meaningful error messages
- Log errors with appropriate context
- Use consistent error response format
### Validation
- Validate all input data
- Use schema validation libraries
- Return clear validation error messages

Project-Specific Patterns

Create rules that reflect your project’s unique architecture:

database_rules
{
"name": "Database Access Patterns",
"description": "Consistent database interaction patterns",
"rules": [
{
"when": "working with database queries",
"enforce": [
"Use Prisma client for all database operations",
"Always include proper error handling",
"Use transactions for multi-step operations",
"Include proper TypeScript types for query results",
"Follow the established naming conventions for models"
]
},
{
"when": "creating new database models",
"enforce": [
"Include proper indexes for frequently queried fields",
"Use appropriate field types (VARCHAR, TEXT, etc.)",
"Include created_at and updated_at timestamps",
"Add proper foreign key relationships",
"Include field validation constraints"
]
}
]
}

Practical Examples for Common Scenarios

Styling and CSS Rules

styling_rules
{
"name": "CSS and Styling Standards",
"description": "Consistent styling patterns across the project",
"rules": [
{
"when": "working with CSS or styling",
"enforce": [
"Use Tailwind CSS classes for styling",
"Follow mobile-first responsive design",
"Use semantic color variables (bg-primary, text-secondary)",
"Include hover and focus states for interactive elements",
"Use consistent spacing scale (p-2, p-4, p-6, p-8)",
"Prefer flexbox and grid for layouts"
]
},
{
"when": "creating new components with styling",
"enforce": [
"Use the existing design system tokens",
"Include proper accessibility attributes",
"Test responsive behavior on multiple screen sizes",
"Use CSS custom properties for theme values"
]
}
]
}

Testing Rules

## Testing Standards
Guidelines for writing effective tests
### Creating test files
- Use Jest as the testing framework
- Follow AAA pattern (Arrange, Act, Assert)
- Use descriptive test names that explain the scenario
- Mock external dependencies appropriately
- Include both positive and negative test cases
- Use beforeEach/afterEach for test setup and cleanup
### Writing unit tests
- Test one thing at a time
- Use meaningful assertions with clear error messages
- Mock time-consuming operations
- Test edge cases and error conditions

Best Practices for Rule Creation

1. Start Small and Iterate

Don’t try to create comprehensive rules all at once. Start with one or two specific scenarios and expand based on what you learn.

Actionable Tip: Begin with a rule for your most common coding task—like creating new components or API endpoints.

2. Be Specific and Concrete

Vague rules lead to inconsistent results. Instead of “write good code,” specify exactly what “good” means in your context.

Example: Instead of “use proper error handling,” write “wrap database operations in try/catch blocks and log errors with console.error.”

3. Test Your Rules

After creating a rule, test it by asking the AI to perform the task it’s designed for. If the results aren’t what you expected, refine the rule.

4. Keep Rules Maintainable

Rules should be easy to understand and modify. Use clear language and organize related rules together.

Common Rule Patterns

Import and Dependency Rules

imports_rules
{
"name": "Import and Dependency Management",
"description": "Consistent import patterns and dependency usage",
"rules": [
{
"when": "adding new imports",
"enforce": [
"Group imports: external libraries first, then internal modules",
"Use named imports instead of default imports when possible",
"Remove unused imports",
"Use absolute imports for internal modules (from '@/components/')",
"Include proper TypeScript types for external libraries"
]
}
]
}

Error Handling Rules

error_handling_rules
{
"name": "Error Handling Standards",
"description": "Consistent error handling patterns",
"rules": [
{
"when": "writing functions that may fail",
"enforce": [
"Use try/catch blocks for async operations",
"Log errors with appropriate context",
"Return meaningful error messages to users",
"Use custom error classes for specific error types",
"Handle both expected and unexpected errors"
]
}
]
}

Organizing Your Rules

File Structure

Organize your rules logically:

.cursor/rules/
├── react_components.mdc
├── api_development.mdc
├── testing_standards.mdc
├── styling_guidelines.mdc
└── project_specific.mdc

Rule Categories

Group related rules together:

  • Language-specific rules (React, TypeScript, Python)
  • Architecture rules (API patterns, database access)
  • Process rules (testing, deployment, documentation)
  • Project-specific rules (naming conventions, file structure)

Troubleshooting Common Issues

Rule Not Working?

  • Check the “when” condition: Is it specific enough?
  • Verify file location: Rules must be in .cursor/rules/
  • Test with simple examples: Start with basic scenarios
  • Check for conflicts: Multiple rules might contradict each other

AI Still Not Following Rules?

  • Be more specific: Add concrete examples to your rules
  • Use positive language: Tell the AI what to do, not what not to do
  • Include context: Explain why the rule exists
  • Iterate: Rules improve with testing and refinement

Advanced Techniques

Conditional Rules

You can create rules that apply based on file content or project structure:

conditional_rules
{
"name": "Conditional Development Rules",
"description": "Rules that apply based on specific conditions",
"rules": [
{
"when": "working with files containing 'useState' or 'useEffect'",
"enforce": [
"Ensure proper dependency arrays in useEffect",
"Use functional updates for state that depends on previous state",
"Clean up subscriptions and timers in useEffect cleanup"
]
},
{
"when": "working with files in src/pages/",
"enforce": [
"Use Next.js routing patterns",
"Include proper meta tags for SEO",
"Handle loading and error states"
]
}
]
}

Integration with Project Tools

tool_integration_rules
{
"name": "Tool Integration Guidelines",
"description": "Rules for working with project tools and services",
"rules": [
{
"when": "working with database migrations",
"enforce": [
"Use Prisma migrations for schema changes",
"Include both up and down migrations",
"Test migrations on development data first",
"Document breaking changes in migration comments"
]
},
{
"when": "creating new API documentation",
"enforce": [
"Use OpenAPI/Swagger format",
"Include request/response examples",
"Document all possible error responses",
"Use consistent parameter naming"
]
}
]
}

Measuring Rule Effectiveness

Success Metrics

Track how well your rules are working:

  • Consistency: Are similar tasks producing similar results?
  • Time savings: Are you spending less time correcting AI suggestions?
  • Code quality: Is the generated code meeting your standards?
  • Developer satisfaction: Are you happier with the AI’s output?

Continuous Improvement

Regularly review and update your rules:

  • Monthly reviews: Check if rules are still relevant
  • Feedback loops: Note when AI doesn’t follow rules
  • Evolution: Update rules as your project grows
  • Documentation: Keep rule explanations clear and current

Real-World Example: E-commerce Project

Here’s a comprehensive example for an e-commerce project:

ecommerce_rules
{
"name": "E-commerce Development Standards",
"description": "Comprehensive rules for e-commerce application development",
"rules": [
{
"when": "creating product-related components",
"enforce": [
"Use TypeScript interfaces for Product, Category, and Order types",
"Include proper loading states for product images",
"Handle out-of-stock scenarios gracefully",
"Use price formatting utilities for consistent display",
"Include proper alt text for product images",
"Use semantic HTML for product listings"
]
},
{
"when": "working with shopping cart functionality",
"enforce": [
"Persist cart data in localStorage or session storage",
"Handle cart updates optimistically",
"Include proper error handling for failed cart operations",
"Use debouncing for cart quantity updates",
"Validate cart items before checkout"
]
},
{
"when": "implementing checkout flow",
"enforce": [
"Use multi-step form pattern with progress indicator",
"Validate all form inputs before proceeding",
"Include proper error messages for validation failures",
"Handle payment processing errors gracefully",
"Send confirmation emails after successful orders",
"Update inventory after successful purchase"
]
},
{
"when": "working with user authentication",
"enforce": [
"Use secure session management",
"Implement proper password hashing",
"Include rate limiting for login attempts",
"Use JWT tokens for API authentication",
"Handle token expiration gracefully",
"Include proper logout functionality"
]
}
]
}

Conclusion: Building Your Rule System

Creating effective Cursor rules is an iterative process. Start with the most common scenarios in your workflow, test them thoroughly, and gradually expand your rule system.

Key Takeaways:

  • Start specific: Target one area of your workflow at a time
  • Be concrete: Use clear, actionable instructions
  • Test and iterate: Refine rules based on actual usage
  • Stay organized: Group related rules and maintain clear documentation
  • Evolve: Update rules as your project and team grow

The goal isn’t to create perfect rules immediately, but to build a system that improves your AI coding experience over time. With practice, you’ll develop a rule set that makes Cursor feel like it truly understands your project and coding style.

Next Steps:

  • Create your first rule for your most common coding task
  • Test it with a few examples
  • Refine based on the results
  • Gradually expand to cover more scenarios

Remember, the best rules are the ones that actually get used and improve your workflow. Start small, stay focused, and let your rule system grow organically with your needs.

Additional Resources: