One of the most frustrating experiences for developers using Cursor is when the AI assistant completely ignores your carefully crafted custom rules. You've spent time setting up specific coding standards, project conventions, and workflow preferences, only to watch Cursor generate code that completely disregards everything you've configured.
If you're searching for "cursor doesn't follow rules ai" because you're facing this exact problem, you're not alone. This comprehensive guide will help you diagnose, understand, and solve the most common issues that prevent Cursor from following your custom rules.
Cursor rules are designed to transform your coding experience by:
When these rules stop working, your productivity takes a significant hit, and code quality becomes inconsistent.
You might be experiencing one or more of these issues:
🚨 Signs Your Cursor Rules Aren't Working
- Cursor generates code in completely different styles than specified
- AI suggestions ignore your project's naming conventions
- Custom snippets and templates are never suggested
- Cursor uses default patterns instead of your customized ones
- Code completion doesn't reflect your established project structure
- Import statements don't follow your preferred organization
The most common reason Cursor doesn't follow your rules is that it can't find or access your rule files.
Common Location Problems:
# ❌ Wrong locations where Cursor can't find rules
~/Documents/my-rules.cursor-rules
/random/folder/.cursorrules
project-folder/configs/cursor.rules
# ✅ Correct locations where Cursor looks for rules
project-root/.cursorrules
project-root/.cursor-rules
~/.cursorrules (global rules)
File Naming Issues:
# ❌ Incorrect file names
.cursor_rules
cursor-rules.txt
cursorrules.md
.cursor-config
# ✅ Correct file names
.cursorrules
.cursor-rules
Cursor rules need to follow specific syntax patterns to be properly interpreted by the AI.
Syntax Issues Example:
# ❌ Poor rule formatting that Cursor ignores
Use TypeScript
Make it work with React
Add some error handling
# ✅ Clear, actionable rule formatting
- Always use TypeScript for all new files
- Import React components using named imports: `import { ComponentName } from 'library'`
- Wrap all async operations in try-catch blocks with proper error logging
- Use interface declarations instead of type aliases for object shapes
Rules that are too vague or lack proper context often get ignored by the AI.
Scope Issues Example:
# ❌ Vague rules without context
Write good code
Follow best practices
Make it clean
# ✅ Specific, contextual rules
- For React components: Always use functional components with TypeScript interfaces for props
- For API routes: Return consistent response objects with { data, error, message } structure
- For styling: Use Tailwind CSS classes, avoid inline styles, group related classes together
- For imports: Group imports in this order: React/Next.js, third-party libraries, local components, utilities
Sometimes rules contradict each other or conflict with Cursor's training, causing the AI to ignore them entirely.
Conflict Example:
# ❌ Conflicting rules that confuse the AI
- Always use semicolons at the end of statements
- Never use semicolons, follow Prettier's defaults
- Use single quotes for strings
- Use double quotes for all strings
- Prefer arrow functions
- Always use function declarations
# ✅ Consistent, non-conflicting rules
- Use TypeScript strict mode settings
- Follow Prettier formatting: no semicolons, single quotes, trailing commas
- Prefer arrow functions for inline callbacks, function declarations for named functions
- Use const assertions for immutable data structures
First, verify that your rule file is in the correct location and properly formatted.
Quick Diagnostic Commands:
# Check if rule file exists in correct location
ls -la .cursorrules
ls -la .cursor-rules
ls -la ~/.cursorrules
# Display rule file contents
cat .cursorrules
# Verify file permissions
ls -la .cursorrules | grep cursorrules
Rule File Structure Validation:
# ✅ Well-structured rule file template
# Project: [Your Project Name]
# Updated: [Date]
## Code Style
- Use TypeScript for all new files
- Follow ESLint configuration in .eslintrc.js
- Use Prettier for code formatting
## Component Patterns
- React components should use functional syntax with TypeScript
- Props interfaces should be defined above the component
- Use default exports for main components, named exports for utilities
## Import Organization
1. React and Next.js imports
2. Third-party library imports
3. Local component imports
4. Utility and helper imports
5. Type-only imports last
## Error Handling
- Wrap all async operations in try-catch blocks
- Use custom error types defined in types/errors.ts
- Log errors using the logger utility from lib/logger.ts
## Testing
- Write unit tests for all utility functions
- Use React Testing Library for component tests
- Mock external dependencies in tests
Cursor's AI has a limited context window, and if your rules are too long or buried in a large file, they might not be considered during code generation.
Context Optimization:
# ❌ Rules that exceed context limits
[... 2000 lines of detailed rules ...]
# ✅ Concise, prioritized rules
## TOP PRIORITY RULES
1. Use TypeScript interfaces for all prop definitions
2. Implement error boundaries for all route components
3. Use Tailwind CSS for styling, avoid CSS modules
## SECONDARY RULES
[Additional, less critical rules...]
## REFERENCE PATTERNS
[Code examples and templates...]
Test whether your rules are specific enough by creating minimal test cases.
Testing Rule Effectiveness:
// Test prompt: "Create a React component for user profile"
// Expected behavior based on rules:
// ✅ What you should see if rules are working:
interface UserProfileProps {
user: {
id: string
name: string
email: string
}
onEdit: () => void
}
export default function UserProfile({ user, onEdit }: UserProfileProps) {
return (
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-xl font-semibold mb-4">{user.name}</h2>
<p className="text-gray-600 mb-4">{user.email}</p>
<button
onClick={onEdit}
className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
>
Edit Profile
</button>
</div>
)
}
// ❌ What you might see if rules are being ignored:
function UserProfile(props) {
return React.createElement('div', {style: {backgroundColor: 'white'}},
React.createElement('h2', null, props.user.name)
)
}
Step 1: Create the correct rule file
# Navigate to your project root
cd /path/to/your/project
# Create the rule file with correct name
touch .cursorrules
# Or alternative naming
touch .cursor-rules
Step 2: Verify file visibility
# Make sure the file is visible
ls -la | grep cursor
# Check file permissions
chmod 644 .cursorrules
Step 3: Test with a simple rule
# Add this minimal test rule to .cursorrules
When creating React components, always use TypeScript interfaces for props.
Before: Ineffective rule structure
I want you to write good React code that follows our team standards and makes sure everything works properly with TypeScript and includes proper error handling.
After: Effective rule structure
## React Component Standards
### Component Definition
- Use functional components with TypeScript
- Define props interface above component
- Use default export for main component
### Example Pattern:
```typescript
interface ComponentProps {
title: string
onClick: () => void
}
export default function Component({ title, onClick }: ComponentProps) {
return (
<button onClick={onClick} className="btn">
{title}
</button>
)
}
### Solution 3: Optimize for Context Window
**Prioritized Rule Structure:**
```markdown
# CURSOR RULES - [Project Name]
## 🔥 CRITICAL RULES (Always Apply)
1. TypeScript for all new files (.ts/.tsx extensions)
2. Functional React components with interface props
3. Tailwind CSS for styling (no inline styles)
## 📋 COMPONENT PATTERNS
```typescript
// Standard component template
interface Props {
// Define props here
}
export default function ComponentName({ prop }: Props) {
// Component logic
return <div className="tailwind-classes">{/* JSX */}</div>
}
import React from 'react'
import { NextPage } from 'next'
import { ComponentName } from '@/components'
import { utilityFunction } from '@/lib/utils'
### Solution 4: Test and Validate Rules
**Create a test workflow:**
```markdown
## Rule Testing Checklist
### Test 1: Component Creation
Prompt: "Create a user card component"
Expected: TypeScript interface, functional component, Tailwind classes
### Test 2: API Route
Prompt: "Create an API route for user data"
Expected: TypeScript, error handling, consistent response format
### Test 3: Form Handling
Prompt: "Create a contact form"
Expected: Form validation, error states, TypeScript types
### Test 4: Import Organization
Prompt: "Add imports for React, axios, and Button component"
Expected: Grouped imports in correct order
Sometimes global rules conflict with project-specific rules. Here's how to manage this:
Global Rules (~/.cursorrules):
# Global Cursor Rules - Apply to all projects
## Universal Standards
- Use TypeScript when possible
- Prefer functional programming patterns
- Write descriptive variable names
- Include error handling for async operations
## Code Quality
- Add JSDoc comments for public functions
- Use const assertions for immutable data
- Prefer named exports for utilities
Project Rules (.cursorrules):
# Project-Specific Rules - Override global when needed
## This Project Uses
- Next.js App Router (not Pages Router)
- Shadcn/UI components (not custom CSS)
- Prisma for database operations
- BetterAuth for authentication
## Project Patterns
[Specific patterns that override global rules]
Make your rules more effective by providing context about when they should apply:
## Context-Aware Rules
### For React Components (.tsx files)
- Always use functional components
- Define TypeScript interfaces for props
- Use Tailwind for styling
### For API Routes (app/api/**/route.ts)
- Return NextResponse.json() objects
- Include try-catch error handling
- Validate request data with Zod schemas
### For Database Operations (lib/db/*.ts)
- Use Prisma client instance
- Handle connection errors gracefully
- Use transactions for multi-step operations
### For Utility Functions (lib/utils/*.ts)
- Export as named exports
- Include JSDoc documentation
- Add unit tests in adjacent .test.ts files
For complex projects, consider organizing rules by feature or module:
Main .cursorrules file:
# Main Cursor Rules
## Project Overview
This is a Next.js e-commerce application with the following key areas:
- Authentication (uses BetterAuth)
- Product catalog (with search and filtering)
- Shopping cart and checkout
- Admin dashboard
- User profiles
## Core Standards
[Universal rules that apply everywhere]
## Feature-Specific Rules
When working on authentication features, follow auth-specific patterns.
When working on product features, use the catalog data structures.
When working on admin features, implement proper role-based access.
Track whether your rules are being applied consistently:
Rule Effectiveness Tracking:
## Rule Compliance Checklist
### Daily Review Questions
- Are new components following the TypeScript interface pattern?
- Do API routes include proper error handling?
- Are imports organized according to the specified order?
- Is Tailwind being used instead of inline styles?
### Weekly Rule Audit
- Review recent commits for rule compliance
- Update rules based on new project requirements
- Remove or modify rules that are consistently ignored
- Add new rules for emerging patterns
Keep your rules current and relevant:
## Rule Maintenance Schedule
### Monthly Tasks
- Review rule effectiveness
- Remove outdated rules
- Add rules for new technologies or patterns
- Test rules with common development scenarios
### Quarterly Tasks
- Major rule restructuring if needed
- Performance optimization of rule files
- Team review of rule compliance
- Documentation updates
For team projects, ensure everyone has consistent rules:
Team Rule Synchronization:
# Include rule files in version control
git add .cursorrules
git commit -m "feat: update Cursor rules for new component patterns"
# Create team rule validation script
#!/bin/bash
# validate-cursor-rules.sh
echo "Validating Cursor rules..."
if [ ! -f .cursorrules ]; then
echo "❌ Missing .cursorrules file"
exit 1
fi
if [ ! -s .cursorrules ]; then
echo "❌ Empty .cursorrules file"
exit 1
fi
echo "✅ Cursor rules file validated"
Create automated tests to verify rule compliance:
Rule Testing Script:
// test-cursor-rules.js
const fs = require('fs')
const path = require('path')
function validateCursorRules() {
const ruleFile = path.join(process.cwd(), '.cursorrules')
if (!fs.existsSync(ruleFile)) {
throw new Error('Missing .cursorrules file')
}
const rules = fs.readFileSync(ruleFile, 'utf8')
// Check for common rule patterns
const requiredPatterns = [
'TypeScript',
'interface',
'component',
'error handling'
]
const missingPatterns = requiredPatterns.filter(pattern =>
!rules.toLowerCase().includes(pattern.toLowerCase())
)
if (missingPatterns.length > 0) {
console.warn(`⚠️ Missing rule patterns: ${missingPatterns.join(', ')}`)
}
console.log('✅ Cursor rules validation passed')
}
validateCursorRules()
Problem: Rules that are too detailed can overwhelm the AI context window.
# ❌ Over-specified rules
When creating a React component, make sure to use TypeScript with strict mode enabled, define interfaces for all props with proper JSDoc comments including @param tags for each property, use functional components with arrow function syntax unless you need component lifecycle methods in which case use class components but prefer hooks, implement proper error boundaries with componentDidCatch, use React.memo for performance optimization when props are stable, implement proper key props for list items, use useCallback and useMemo appropriately to prevent unnecessary re-renders...
# ✅ Right level of specification
- Use TypeScript functional components with interface props
- Implement error boundaries for route-level components
- Use React.memo, useCallback, useMemo for performance when needed
Problem: Contradictory rules confuse the AI.
# ❌ Conflicting rules
- Always use arrow functions
- Prefer function declarations for components
- Use semicolons for consistency
- Follow Prettier settings (no semicolons)
# ✅ Consistent rules
- Use arrow functions for inline callbacks and utility functions
- Use function declarations for React components and main functions
- Follow Prettier configuration: no semicolons, single quotes, trailing commas
Problem: Rules that don't consider the AI's context limitations.
# ❌ Context-ignorant rules
[5000 words of detailed coding standards...]
# ✅ Context-aware rules
## PRIORITY 1 (Always Apply)
[3-5 most important rules]
## PRIORITY 2 (Apply When Relevant)
[Secondary rules]
## REFERENCE (Examples Only)
[Code examples and patterns]
Track these metrics to measure rule effectiveness:
📊 Rule Effectiveness Metrics
- Consistency Score: Percentage of generated code that follows established patterns
- Rule Compliance: How often Cursor applies your specific rules
- Developer Satisfaction: Team feedback on AI assistance quality
- Time Saved: Reduction in manual code formatting and restructuring
- Error Reduction: Fewer bugs related to coding standard violations
## Rule Success Checklist
### ✅ Your rules are working well when:
- Cursor generates code in your preferred style consistently
- New team members' AI-generated code matches project standards
- Code reviews require fewer style-related comments
- Import statements are automatically organized correctly
- Error handling patterns are consistently applied
### ⚠️ Signs your rules need improvement:
- Inconsistent code generation across sessions
- AI ignores specific formatting preferences
- Generated code requires significant manual adjustment
- Team members report different AI behavior
- Rules are applied only sometimes
As AI models evolve, your rules should adapt too:
## Evolution-Ready Rule Structure
### Core Principles (Stable)
- Type safety with TypeScript
- Component-based architecture
- Error handling patterns
- Code organization standards
### Implementation Details (Flexible)
- Specific syntax preferences (may change with language updates)
- Tool-specific configurations (may change with new tools)
- Framework-specific patterns (may evolve with framework updates)
### Review Schedule
- Monthly: Check rule effectiveness
- Quarterly: Update for new tools/frameworks
- Annually: Major rule architecture review
Make rule compliance part of your development process:
Git Hooks Integration:
#!/bin/sh
# .git/hooks/pre-commit
echo "Checking Cursor rule compliance..."
# Run rule validation
npm run validate-cursor-rules
if [ $? -ne 0 ]; then
echo "❌ Cursor rules validation failed"
exit 1
fi
echo "✅ Cursor rules validation passed"
CI/CD Integration:
# .github/workflows/cursor-rules.yml
name: Validate Cursor Rules
on: [push, pull_request]
jobs:
validate-rules:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Validate Cursor Rules
run: |
if [ ! -f .cursorrules ]; then
echo "❌ Missing .cursorrules file"
exit 1
fi
echo "✅ Cursor rules file exists"
When Cursor doesn't follow your AI rules, the solution usually lies in one of these key areas:
.cursorrules
is in the correct location🎯 Key Takeaways
- Start Simple: Begin with a few critical rules and expand gradually
- Be Specific: Vague rules are often ignored; specific patterns are followed
- Test Regularly: Validate that your rules are working as expected
- Maintain Actively: Rules need regular updates to stay effective
- Prioritize Context: Keep the most important rules within the AI's context window
By following this troubleshooting guide, you should be able to diagnose and fix most issues where Cursor doesn't follow your custom rules. Remember that effective rule writing is an iterative process – start with the basics, test frequently, and refine based on real-world usage.
The key to success is understanding that Cursor's AI works best with clear, specific, and contextually appropriate guidance. When your rules are well-crafted and properly configured, Cursor becomes an incredibly powerful assistant that consistently follows your project's standards and accelerates your development workflow.
This troubleshooting guide is continuously updated based on community feedback and the latest Cursor developments. If you discover new solutions or encounter different issues, please share your experience with the community.
Expert developer passionate about modern web technologies and AI-assisted development.
Get the latest articles and tutorials delivered to your inbox.