How to Write Effective Cursor Rules: A Complete Guide
Learn how to write .cursorrules and .cursor/rules/ files that actually improve your AI coding experience. MDC format, examples, best practices, and common mistakes.
How to Write Effective Cursor Rules: A Complete Guide
Cursor rules are the single most impactful thing you can configure to improve your AI coding experience. A well-written rules file transforms generic AI suggestions into code that matches your exact project conventions — right framework, right patterns, right style — on the first try.
This guide covers both the legacy .cursorrules single-file format and the newer .cursor/rules/ directory format with MDC files. You'll learn how to structure rules, what to include, common mistakes, and real-world examples you can adapt.
What Are Cursor Rules?
Cursor rules are persistent instructions that tell Cursor's AI how to generate code for your specific project. They act as an always-active system prompt — every time the AI generates code, completes a line, or answers a question, it reads your rules first.
Without rules, Cursor uses generic defaults. The AI doesn't know your team uses Tailwind instead of CSS modules, prefers named exports over defaults, or wants Prisma instead of raw SQL. You end up correcting the same patterns over and over.
With rules, you tell the AI once and it remembers for every interaction.
Two Formats: Which One to Use
Legacy: .cursorrules (Single File)
The original format. A single .cursorrules file at your project root. Simple to set up, but all rules apply globally to every file.
You are an expert Next.js developer using TypeScript and Tailwind CSS.
## Standards
- Use functional components with hooks
- Prefer Server Components by default
- Use Prisma for database access
- Always handle errors with try/catch
Use this if: You're on an older Cursor version, want the simplest setup, or your project is small enough that one set of rules covers everything.
Modern: .cursor/rules/ Directory (MDC Format)
The newer, more powerful format. A directory of .mdc files, each with frontmatter specifying which files the rule applies to. This lets you have different rules for different parts of your codebase.
.cursor/
rules/
react-components.mdc
api-routes.mdc
testing.mdc
database.mdc
Each .mdc file has a frontmatter section with description and globs:
---
description: React component conventions
globs: ["src/components/**/*.tsx", "src/app/**/*.tsx"]
---
- Use functional components with TypeScript interfaces for props
- Export components as named exports
- Place hooks at the top of the component body
- Use Tailwind CSS for all styling
- Never use inline styles or CSS modules
Use this if: You want granular control — different rules for components vs. API routes vs. tests vs. database models.
Why MDC Is Better for Larger Projects
Consider a full-stack Next.js project. Your API routes follow different conventions than your React components. Your test files have different requirements than your production code. With a single .cursorrules file, every rule applies everywhere, which can cause conflicts.
With MDC, you can scope precisely:
api-routes.mdc(globs:src/app/api/**/*.ts) — "Always validate request bodies with Zod. Return proper HTTP status codes. Use try/catch with specific error types."components.mdc(globs:src/components/**/*.tsx) — "Use Tailwind CSS. Accept props via TypeScript interfaces. Use forwardRef for components that need ref access."tests.mdc(globs:**/*.test.ts,**/*.spec.ts) — "Use Vitest. Preferdescribe/itblocks. Mock external dependencies. Never test implementation details."
The AI only sees the relevant rules for the file it's working on, which produces more focused output.
What to Include in Your Rules
1. Project Context
Start with a concise description of what your project is and what stack it uses. This gives the AI baseline context for every interaction.
This is a SaaS application built with Next.js 16 (App Router), TypeScript in strict mode,
Tailwind CSS v4, Prisma with PostgreSQL, and NextAuth.js for authentication.
2. Tech Stack with Versions
Be specific about versions. "React" isn't enough — "React 19 with Server Components" tells the AI to use the latest patterns instead of class components or older hooks patterns.
## Tech Stack
- Next.js 16.x with App Router (NOT Pages Router)
- React 19 with Server Components by default
- TypeScript 5.x in strict mode
- Tailwind CSS v4 (NOT v3 — use the new CSS-first config)
- Prisma 6.x with PostgreSQL
- NextAuth.js v5 (Auth.js)
3. Coding Standards
Define how code should look. Focus on the decisions your team has made that deviate from defaults.
## Coding Standards
- Use `async/await` over `.then()` chains
- Use named exports, not `export default` (except for pages and layouts)
- Error handling: wrap async operations in try/catch, return typed error objects
- Use `interface` for object shapes, `type` for unions and intersections
- Maximum function length: ~50 lines — extract helpers when longer
4. Naming Conventions
AI assistants often guess at naming. Remove the guessing.
## Naming
- Components: PascalCase (`UserProfile.tsx`)
- Hooks: camelCase with `use` prefix (`useAuth.ts`)
- Utilities: camelCase (`formatDate.ts`)
- Constants: SCREAMING_SNAKE_CASE (`MAX_RETRY_COUNT`)
- API routes: kebab-case paths (`/api/user-profile`)
- Database models: PascalCase singular (`User`, not `Users`)
5. Negative Rules (What NOT to Do)
These are often more useful than positive rules because they prevent the AI's most common mistakes.
## Don'ts
- Never use `any` type — define proper types or use `unknown`
- Never use inline styles — use Tailwind classes
- Don't use `var` — use `const` by default, `let` only when reassignment is needed
- Don't add dependencies without explicit approval
- Don't use `console.log` in production code — use the logger utility
- Never modify database schemas directly — always use Prisma migrations
6. File Organization
Tell the AI where things go. This prevents it from creating files in the wrong directories.
## File Organization
- Pages and layouts: `src/app/`
- Reusable components: `src/components/`
- Server actions: `src/actions/`
- Database queries: `src/lib/db/`
- Utility functions: `src/lib/utils/`
- Type definitions: `src/types/`
- Tests: colocate with source files as `*.test.ts`
7. Preferred Libraries
The AI will often suggest alternatives unless you specify preferences.
## Preferred Libraries
- Dates: date-fns (NOT moment, NOT dayjs)
- Validation: Zod
- Forms: react-hook-form + Zod resolver
- Animations: Framer Motion
- Icons: Lucide React
- HTTP client: native fetch (NOT axios)
Real-World Before and After
Here's a concrete example of how rules change AI output.
Without Rules
You ask Cursor: "Create a user profile component"
import React from 'react';
import './UserProfile.css';
class UserProfile extends React.Component {
render() {
return (
<div style={{ padding: '20px' }}>
<h1>{this.props.name}</h1>
<p>{this.props.email}</p>
</div>
);
}
}
export default UserProfile;
The AI used: class components, CSS file, inline styles, default export, no TypeScript, no Tailwind.
With Rules
Same request with proper rules:
interface UserProfileProps {
name: string;
email: string;
avatarUrl?: string;
}
export function UserProfile({ name, email, avatarUrl }: UserProfileProps) {
return (
<div className="rounded-lg border bg-card p-6">
<div className="flex items-center gap-4">
{avatarUrl && (
<Image
src={avatarUrl}
alt={name}
width={48}
height={48}
className="rounded-full"
/>
)}
<div>
<h2 className="text-lg font-semibold">{name}</h2>
<p className="text-sm text-muted-foreground">{email}</p>
</div>
</div>
</div>
);
}
The AI used: functional component, TypeScript interface, named export, Tailwind CSS, next/image, proper patterns. Every aspect matches the project conventions.
Best Practices
1. Start Small, Then Expand
Don't try to write 500 lines of rules on day one. Start with the 10-20 most important conventions. Then watch what you keep correcting the AI on — those corrections become new rules.
2. Be Specific, Not Vague
❌ "Write clean code" ✅ "Use early returns to avoid deep nesting. Maximum function length ~50 lines."
❌ "Handle errors properly"
✅ "Wrap async operations in try/catch. Return { success: false, error: string } objects instead of throwing."
3. Include Examples for Complex Patterns
For patterns that are hard to describe in words, show a concrete example:
## API Route Pattern
Every API route should follow this structure:
\`\`\`ts
export async function POST(request: Request) {
try {
const body = await request.json();
const validated = schema.parse(body);
const result = await performAction(validated);
return NextResponse.json(result);
} catch (error) {
if (error instanceof ZodError) {
return NextResponse.json({ error: "Validation failed" }, { status: 400 });
}
return NextResponse.json({ error: "Internal error" }, { status: 500 });
}
}
\`\`\`
4. Review Monthly
Your project evolves. New libraries get added, patterns change, frameworks update. Set a monthly reminder to review your rules and remove anything outdated.
5. Version Control Your Rules
Commit .cursorrules or .cursor/rules/ to your repository. This ensures every team member gets the same AI behavior. Include rules changes in your PR reviews.
6. Use Our Generator for the Starting Point
If you're starting from scratch, our Cursor Rules Generator creates a project-specific rules file based on your tech stack. It gives you a solid foundation that you can customize.
Common Mistakes
Writing Rules That Are Too Vague
"Write good code" and "follow best practices" give the AI no actionable information. Every rule should be specific enough that a human developer could follow it without asking for clarification.
Making Rules Too Long
Extremely long rules files (1,000+ lines) can dilute the AI's attention. Focus on the 80/20 — the 20% of rules that cover 80% of your coding patterns. If you need more detail, use the MDC format to split rules across multiple scoped files.
Contradicting Yourself
"Always use Server Components" combined with "Use useState for all state management" creates a contradiction. Server Components can't use hooks. Review your rules for logical conflicts.
Forgetting to Update
Rules that reference deprecated APIs, old library versions, or patterns your team no longer uses confuse the AI. Stale rules are worse than no rules because they actively push the AI toward wrong patterns.
Not Including Negative Rules
The AI defaults to common patterns from its training data. If your team has strong opinions about what NOT to do (no default exports, no inline styles, no any types), you need to say so explicitly.
Templates for Common Stacks
Next.js + TypeScript + Tailwind
Browse our Next.js Cursor rules for ready-to-use configurations.
Python + FastAPI
Browse our Python Cursor rules for backend templates.
React Native + Expo
Browse our React Native rules for mobile development.
Or generate a custom rules file for any stack with our Cursor Rules Generator.
Cross-Tool Compatibility
The content of your rules is largely transferable between tools:
- Windsurf: Use
.windsurfrules— same content, single file format. See our Windsurf rules. - Claude Code: Use
CLAUDE.md— same content, supports subdirectory overrides. See our Claude Code rules.
For a deeper comparison of how each tool handles rules, see our Cursor vs Windsurf vs Claude Code comparison.
Conclusion
Cursor rules are the highest-leverage configuration you can make in your AI coding workflow. Start with project context and your most important conventions, expand as you notice patterns, and review regularly. The time you invest in rules pays back many times over in reduced corrections and better first-try AI output.
Explore our rules directory for 500+ community-contributed rules across every major framework, or use the Cursor Rules Generator to create a custom starting point for your project.
Need more help? Browse Cursor rules for your framework, check out our prompt engineering guide for better AI interactions, or try the free Prompt Grader to improve your prompts.
Related Articles
Cursor vs Windsurf vs Claude Code: Which AI Coding Assistant is Best in 2026?
An in-depth comparison of the top AI coding assistants. We compare features, pricing, agentic workflows, MCP support, and real-world performance to help you choose.
How to Build a Custom GPT: Complete Step-by-Step Guide
Learn how to create your own Custom GPT in ChatGPT. This comprehensive guide covers planning, instructions, knowledge files, actions, and best practices for building effective AI assistants.
How to Use AI for Code Review: Prompts + Workflow Guide
Learn how to leverage AI for effective code reviews. Complete workflow with prompts for security audits, performance checks, and best practices enforcement.