- Learn
- AI Code Editors
- Cursor
- Configuring Rules for AI
Set up project-specific instructions and coding standards that guide how Cursor's AI works with your codebase.
Configuring Rules for AI
Rules for AI let you customize how Cursor's AI responds to you. Instead of repeating the same instructions every time, you define them once and they apply to all AI interactions in your project.
What Are Rules for AI?
Rules are instructions that get included with every AI request. They can specify:
- Coding standards and conventions
- Preferred libraries and frameworks
- Project architecture decisions
- What to avoid or never do
- How to format responses
Types of Rules
1. Global Rules
Apply to all your projects. Set in Cursor Settings:
Settings → Cursor Settings → Rules for AI
Good for:
- Personal coding style preferences
- Common instructions you always want
2. Project Rules (.cursor/rules/)
Create rule files in the .cursor/rules/ directory using the .mdc format:
mkdir -p .cursor/rules
touch .cursor/rules/general.mdc
Each .mdc file has YAML frontmatter for metadata:
---
description: General coding standards
globs:
- "**/*.ts"
- "**/*.tsx"
alwaysApply: true
---
# Coding Standards
Your rule content here...
3. Multiple Rule Files
Organize rules by concern using multiple .mdc files:
project/
├── .cursor/
│ └── rules/
│ ├── general.mdc # Project-wide rules
│ ├── components.mdc # Component patterns
│ ├── api.mdc # API conventions
│ └── testing.mdc # Test standards
Note: The
.cursorrulesfile format is deprecated. Migrate to.cursor/rules/*.mdcfor better organization and glob-based targeting.
Writing Effective Rules
Basic Structure
A simple .cursor/rules/general.mdc file:
---
description: Project coding standards and conventions
globs:
- "**/*.ts"
- "**/*.tsx"
alwaysApply: true
---
# Project Rules
You are working on a Next.js 15 application with TypeScript.
## Tech Stack
- Next.js 15 with App Router
- TypeScript in strict mode
- Tailwind CSS v4 for styling
- Prisma for database
- Zod for validation
## Conventions
- Use named exports instead of default exports
- Use function declarations for components
- Prefer const arrow functions for handlers
- Use absolute imports starting with @/
Be Specific About Patterns
## Component Patterns
Components should follow this structure:
```tsx
interface ComponentNameProps {
// props here
}
export function ComponentName({ prop1, prop2 }: ComponentNameProps) {
// hooks first
// handlers next
// render logic last
return (
// JSX
)
}
API Routes
All API routes should:
- Validate input with Zod
- Use try/catch for error handling
- Return consistent response shapes
- Include appropriate status codes
### Include What Not To Do
```markdown
## Avoid
- Never use `any` type
- Never use inline styles
- Never commit console.log statements
- Do not use class components
- Avoid default exports except for pages
- Do not use var, only const and let
Reference Your Architecture
## Project Structure
- `/app` - Next.js pages and API routes
- `/components` - Reusable React components
- `/lib` - Utility functions and shared logic
- `/hooks` - Custom React hooks
- `/types` - TypeScript type definitions
- `/prisma` - Database schema and migrations
When creating new files, place them in the appropriate directory.
Real-World Examples
Next.js Full-Stack Project
# .cursorrules
You are an expert Next.js developer working on a SaaS application.
## Stack
- Next.js 14 (App Router)
- TypeScript
- Tailwind CSS + shadcn/ui
- Prisma + PostgreSQL
- NextAuth.js for authentication
- Stripe for payments
## Code Style
### TypeScript
- Enable strict mode
- Prefer interfaces over types for object shapes
- Use Zod schemas that infer TypeScript types
### Components
- Server components by default
- Add 'use client' only when necessary
- Use Suspense boundaries for loading states
- Implement error boundaries for error handling
### Data Fetching
- Fetch data in Server Components
- Use React Query for client-side caching
- Handle loading and error states
### Forms
- Use React Hook Form
- Validate with Zod
- Show inline validation errors
- Disable submit during submission
## UI Guidelines
- Use shadcn/ui components
- Follow the design system in @/components/ui
- Support dark mode
- Ensure mobile responsiveness
- Use Tailwind's cn() helper for conditional classes
## Security
- Validate all inputs on the server
- Use parameterized queries (Prisma handles this)
- Sanitize user-generated content
- Check authentication in API routes
- Use CSRF protection
## Responses
When generating code:
1. Include all necessary imports
2. Add TypeScript types
3. Include error handling
4. Add comments for complex logic
5. Suggest tests when appropriate
Python Backend Project
# .cursorrules
You are a senior Python developer building a FastAPI backend.
## Stack
- Python 3.11+
- FastAPI
- SQLAlchemy 2.0 with async
- PostgreSQL
- Alembic for migrations
- Pydantic for validation
- Pytest for testing
## Code Style
- Follow PEP 8
- Use type hints everywhere
- Docstrings in Google style
- Maximum line length: 88 (black)
- Sort imports with isort
## Patterns
### API Endpoints
```python
@router.get("/items/{item_id}")
async def get_item(
item_id: int,
db: AsyncSession = Depends(get_db)
) -> ItemResponse:
"""Get item by ID.
Args:
item_id: The item's unique identifier
Returns:
The item data
Raises:
HTTPException: If item not found
"""
item = await crud.get_item(db, item_id)
if not item:
raise HTTPException(404, "Item not found")
return item
Database Queries
- Use async SQLAlchemy
- Repository pattern in /app/crud
- Pydantic models for responses
Testing
- Write tests for all endpoints
- Use pytest fixtures
- Mock external services
- Aim for >80% coverage
### React Component Library
```markdown
# .cursorrules
Building a component library with Storybook.
## Stack
- React 18
- TypeScript
- Tailwind CSS
- CVA for variants
- Radix UI primitives
- Storybook 7
## Component Guidelines
Every component should have:
1. TypeScript props interface
2. Variants using CVA
3. Storybook stories
4. Unit tests with Testing Library
5. JSDoc documentation
### Component Template
```tsx
import { cva, type VariantProps } from "class-variance-authority"
import { forwardRef } from "react"
const componentVariants = cva(
"base-classes",
{
variants: {
variant: {
default: "...",
secondary: "...",
},
size: {
sm: "...",
md: "...",
lg: "...",
},
},
defaultVariants: {
variant: "default",
size: "md",
},
}
)
export interface ComponentProps
extends React.HTMLAttributes<HTMLElement>,
VariantProps<typeof componentVariants> {
// additional props
}
export const Component = forwardRef<HTMLElement, ComponentProps>(
({ className, variant, size, ...props }, ref) => {
return (
<element
ref={ref}
className={cn(componentVariants({ variant, size }), className)}
{...props}
/>
)
}
)
Component.displayName = "Component"
Accessibility
- All interactive elements must be keyboard accessible
- Include proper ARIA attributes
- Support screen readers
- Meet WCAG 2.1 AA standards
## Managing Rules
### Keeping Rules Focused
Rules that are too long can be less effective. Keep them:
- Under 2000 tokens ideally
- Focused on the most important patterns
- Updated as your project evolves
### Versioning Rules
Since `.cursorrules` is a file, it's version controlled:
```bash
git add .cursorrules
git commit -m "Add cursor rules for project conventions"
Team Collaboration
Your team can:
- Discuss and agree on rules
- Review rules in PRs
- Update rules as patterns evolve
- Share best practices across projects
Common Mistakes
Too Vague
# ❌ Too vague
Write good code.
Follow best practices.
Make it clean.
Too Verbose
Don't include things the AI already knows:
# ❌ Unnecessary
When I ask you to write JavaScript code, you should write JavaScript code.
Contradictory Rules
# ❌ Contradictory
Always use default exports.
Never use default exports.
Testing Your Rules
To verify rules are working:
- Open Composer
- Ask a simple question that should trigger your rules
- Check if the response follows your conventions
Example test prompt:
Create a simple button component
The output should follow your defined patterns.
Summary
- Global rules apply to all projects
- .cursorrules files apply to specific projects or directories
- Be specific about patterns and conventions
- Include examples of what good code looks like
- Say what to avoid as well as what to do
- Keep rules focused and maintainable
Next Steps
Rules define what AI should do. Context management controls what AI can see—understanding how to manage context makes your AI interactions more precise and efficient.