Cursor Rules: Difference between revisions
Line 49: | Line 49: | ||
* If the AI repeatedly makes mistakes (e.g., forgetting nullish coalescing in [[JavaScript]]), add a rule: | * If the AI repeatedly makes mistakes (e.g., forgetting nullish coalescing in [[JavaScript]]), add a rule: | ||
<pre> | <pre> | ||
Use ?? for default values instead of || in | Use ?? for default values instead of || in JavaScript/TypeScript. | ||
</pre> | </pre> | ||
* For dynamic fixes, ask [[Cursor AI]] in a chat: "Write me a [[Cursor Rule]] to stop doing X," and append the output to your rules file. | * For dynamic fixes, ask [[Cursor AI]] in a chat: "Write me a [[Cursor Rule]] to stop doing X," and append the output to your rules file. | ||
Line 56: | Line 56: | ||
* Include a brief description of the project and its structure at the top: | * Include a brief description of the project and its structure at the top: | ||
<pre> | <pre> | ||
This is a | This is a Django app with a REST API, using PostgreSQL and structured as: /apps, /core, /utils. | ||
</pre> | </pre> | ||
* This helps the AI understand the bigger picture without needing constant manual context in prompts. | * This helps the AI understand the bigger picture without needing constant manual context in prompts. |
Revision as of 07:05, 14 March 2025
Cursor Rules are a key feature in Cursor AI, an AI-powered code editor forked from VS Code, designed to assist developers by generating code, suggesting edits, and automating repetitive tasks. These rules allow users to define custom instructions that guide the AI's behavior, tailoring its output to meet project-specific needs, coding standards, and personal preferences. Historically stored in a single .cursorrules file, they are now typically organized as .mdc files within nested /rules directories in a project's root or subdirectories, offering a mechanism to enhance the AI's context awareness and consistency.
Overview
What Are Cursor Rules?
Cursor Rules are text-based instructions that developers provide to Cursor AI to influence how it generates and edits code. They serve as a way to "teach" the AI about your project’s conventions, structure, and requirements, reducing the need for repetitive manual corrections and improving the relevance of its suggestions.
Why Use Cursor Rules?
The benefits of using Cursor Rules include:
- Customized AI Behavior: Tailor the AI’s output to align with your project’s specific needs, such as preferred libraries, frameworks, or coding patterns.
- Consistency: Enforce coding standards (e.g., DRY principles, proper typing) across your codebase.
- Context Awareness: Provide details about your project’s purpose, file structure, or commonly used functions, leading to more accurate suggestions and fewer "hallucinations" (e.g., fictional functions).
- Improved Productivity: Reduce manual editing by preemptively addressing recurring issues or preferences, allowing faster development of boilerplate or repetitive code.
- Team Alignment: Share rules with team members to ensure consistent AI assistance across collaborative projects.
- Problem Mitigation: Address specific issues, such as "Do not revert nullish coalescing operators in JavaScript code," to prevent repeated mistakes.
Without rules, Cursor AI relies solely on its training data and immediate prompt context, which can result in generic or suboptimal output. Cursor Rules bridge this gap by embedding project-specific knowledge into the AI’s decision-making process.
Setting Up Your Cursor Rules
Basic Setup
1. Locate or Create the Rules File:
- Historically, Cursor AI used a single .cursorrules file in the project root. As of version 0.47.x, it supports nested .cursor/rules/*.mdc files for granular control (e.g., in monorepos).
- To create a new rule: Open Cursor AI, press Cmd+Shift+P (or Ctrl+Shift+P), and select "New Cursor Rule". This generates an .mdc file in the appropriate directory.
2. Add Instructions:
- Write plain text or structured instructions. Start with a brief project overview, followed by specific guidelines.
- Example:
# Project Overview This is a Next.js project using TypeScript, Tailwind CSS, and Supabase for authentication and database management. # Rules - Use nullish coalescing (??) instead of || for default values in JavaScript/TypeScript. - Follow a flat file structure: no nested folders beyond /components, /lib, and /pages. - Prefer functional components over class components in React.
3. Apply and Test:
- Save the file. Cursor AI automatically applies the rules to its suggestions within the project scope.
- Test by asking the AI to generate code and verify adherence to your instructions.
Finding Inspiration
- Community Resources: Explore repositories like Awesome CursorRules (GitHub link) for curated .cursorrules examples across stacks (e.g., React, Python, Go).
- Adapt and Simplify: Copy relevant rules for your tech stack, but keep them minimal to avoid overwhelming the AI with excessive input.
Best Practices for Using Cursor Rules
Keep It Simple
- Start with a minimal set of rules (e.g., 5-10 lines) and expand as needed. Overloading the file with details can confuse the AI or degrade performance.
- Example: Instead of listing every best practice (DRY, SOLID), focus on project-specific quirks, like "Always use fetch over axios for API calls."
Address Recurring Issues
- If the AI repeatedly makes mistakes (e.g., forgetting nullish coalescing in JavaScript), add a rule:
Use ?? for default values instead of || in JavaScript/TypeScript.
- For dynamic fixes, ask Cursor AI in a chat: "Write me a Cursor Rule to stop doing X," and append the output to your rules file.
Provide Project Context
- Include a brief description of the project and its structure at the top:
This is a Django app with a REST API, using PostgreSQL and structured as: /apps, /core, /utils.
- This helps the AI understand the bigger picture without needing constant manual context in prompts.
Use Nested Rules for Large Projects
- In monorepos or complex projects, leverage nested .cursor/rules/*.mdc files for specific subdirectories:
- /rules/frontend.mdc for React-specific rules.
- /rules/backend.mdc for Python/Django rules.
Pair with Manual Context
- Combine rules with explicit file references in prompts (e.g., @utils.ts @schedule.ts) to guide the AI to relevant code, enhancing accuracy without bloating the rules file.
Tips for Optimizing Cursor AI with Rules
General Workflow Tips
- Use Composer (Agent) Sparingly: Reserve Composer for simple, low-impact changes (e.g., boilerplate generation). Use Chat (Ask) for complex tasks to maintain control over edits.
- Review Every Change: Never blindly accept AI-generated code. Treat it like a junior developer’s pull request—verify it works and fits your intent.
- Ask Clarifying Questions: Prompt the AI with "Is this the best way to do this?" or "Have you considered X?" to refine its output.
- Break Down Big Tasks: For foundational features, ask the AI to pose questions first (e.g., "What questions do you have before coding this?") to ensure it understands requirements.
Avoiding Common Pitfalls
- Bug Fixing Caution: Cursor AI struggles with complex bug fixes, often introducing new issues. Use it for trivial bugs only; manually handle critical ones.
- Over-Reliance: Regularly refactor key code manually to maintain understanding and improve future AI outputs. Over-dependence can atrophy coding skills, especially for juniors.
- Context Overload: Too much input (long rules or chats) can degrade output quality. Keep interactions concise.
- Secrets Management: Add sensitive files (e.g., .env) to .cursorignore to prevent accidental exposure.
Language and Stack Considerations
- Cursor AI’s performance varies by language and stack. It excels with popular frameworks like Next.js, TypeScript, and Python but may falter with less common ones like Elixir. Adjust rules and expectations accordingly.
Example Cursor Rules
Here’s a sample .mdc file for a typical web project:
# Project Overview A [[Next.js]] 15 app with [[React]] 19, [[TypeScript]], [[Tailwind CSS]], and [[Vercel AI SDK]]. Uses a [[monorepo]] structure with /apps and /packages. # Rules - Use ?? over || for default values in [[TypeScript]]. - Prefer arrow functions over function declarations. - Organize components in /apps/web/components with a flat structure. - Use [[Tailwind]] classes over inline CSS. - Avoid unnecessary null checks; trust [[TypeScript]]’s type system unless specified.
Advanced Usage
- Dynamic Rules: Ask Cursor AI to generate rules on the fly (e.g., "Create a rule to enforce X") and append them to your file.
- Team Collaboration: Share .cursorrules files via version control to align AI behavior across a team.
- Experimentation: Test different models (e.g., Claude 3.7, DeepSeek R1) with your rules to find the best fit for your stack.
Limitations and Considerations
- AI Variability: Output quality depends on the underlying model (e.g., Claude, GPT), which may change with updates or degrade over time.
- Skill Atrophy: Overuse without manual coding can weaken reasoning and problem-solving skills, a concern echoed by developers on Hacker News.
- Cost and Context: Cursor AI’s flat-fee model may lead to context pruning, reducing effectiveness for large codebases. Alternatives like Cline (pay-per-token) might offer better control.
Community Resources
- Awesome CursorRules: A GitHub repository (link) with a collection of .cursorrules examples for various stacks.
- Hacker News Discussions: Insights from threads like "I use Cursor daily - here's how I avoid the garbage parts" (link) offer real-world tips and critiques.
- Cursor Forum: Official support and user discussions (link).
How to Use
Method One (Manual)
- Install Cursor AI (or update to the latest version).
- Create a .cursorrules or .mdc file in your project’s root or via Cmd+Shift+P → New Cursor Rule.
- Populate with guidelines, references, and known pitfalls.
- Test and refine based on AI output.
Method Two (Using Extension)
- Install Cursor AI.
- Install the vscode-cursor-rules extension (if available).
- Open the command palette (Cmd+Shift+P or Ctrl+Shift+P) and select “Cursor Rules: Add .cursorrules.”
- Choose a template and customize.