Intermediate20 min1 prerequisite

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:

Terminal
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:

Terminal
mkdir -p .cursor/rules
touch .cursor/rules/general.mdc

Each .mdc file has YAML frontmatter for metadata:

Terminal
---
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:

Terminal
project/
├── .cursor/
   └── rules/
       ├── general.mdc       # Project-wide rules
       ├── components.mdc    # Component patterns
       ├── api.mdc           # API conventions
       └── testing.mdc       # Test standards

Note: The .cursorrules file format is deprecated. Migrate to .cursor/rules/*.mdc for better organization and glob-based targeting.

Writing Effective Rules

Basic Structure

A simple .cursor/rules/general.mdc file:

Terminal
---
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

Terminal
## 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:

  1. Validate input with Zod
  2. Use try/catch for error handling
  3. Return consistent response shapes
  4. Include appropriate status codes
Terminal

### 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

Terminal
## 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

Terminal
# .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

Terminal
# .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
Terminal

### 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
Terminal

## 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:

  1. Discuss and agree on rules
  2. Review rules in PRs
  3. Update rules as patterns evolve
  4. Share best practices across projects

Common Mistakes

Too Vague

Terminal
#  Too vague
Write good code.
Follow best practices.
Make it clean.

Too Verbose

Don't include things the AI already knows:

Terminal
#  Unnecessary
When I ask you to write JavaScript code, you should write JavaScript code.

Contradictory Rules

Terminal
#  Contradictory
Always use default exports.
Never use default exports.

Testing Your Rules

To verify rules are working:

  1. Open Composer
  2. Ask a simple question that should trigger your rules
  3. Check if the response follows your conventions

Example test prompt:

Terminal
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.

Mark this lesson as complete to track your progress