DEV Community

Survivor Forge
Survivor Forge

Posted on

The Best Cursor Rules for Every Framework in 2026 (20+ Examples)

The Best Cursor Rules for Every Framework in 2026 (20+ Examples)

If you're using Cursor as your daily editor but haven't set up a .cursorrules file yet, you're leaving an enormous amount of productivity on the table.

Here's the reality: Cursor is already a great AI-powered editor out of the box. But without project-specific rules, the AI assistant has to guess what your codebase looks like, which conventions you follow, and how you want code to be structured. Sometimes it guesses right. Often it doesn't.

A well-crafted .cursorrules file turns Cursor from a general-purpose AI assistant into a context-aware coding partner that understands your stack, your patterns, and your preferences. I've seen developers go from accepting 30% of AI suggestions to accepting 80%+ — just by adding a single file to their project root.

This guide covers everything you need to know about Cursor rules: what they are, how to write them, real examples you can steal, and the mistakes that trip most people up.


What Are Cursor Rules?

Cursor rules are instructions that tell Cursor's AI how to behave when working in your specific project. They live in a file called .cursorrules in your project root directory (right next to your package.json, pyproject.toml, or go.mod).

When you open a project in Cursor, the editor automatically reads this file and applies those instructions to every AI interaction — whether you're using Cmd+K inline edits, Chat, or Composer.

Think of it like a system prompt, but scoped to your codebase.

Where to Put Them

my-project/
├── .cursorrules      <-- right here, project root
├── src/
├── package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

The file gets picked up automatically. No configuration needed, no settings to toggle. Just create the file and start writing rules.

What Happens Without Them

Without a .cursorrules file, Cursor still works. But the AI falls back to generic patterns:

  • It might generate class components when your React codebase uses only functional components
  • It might use var instead of const in your modern TypeScript project
  • It might ignore your project's error handling conventions
  • It might write tests in Jest when you use Vitest
  • It might add comments everywhere when your team prefers self-documenting code

None of these are catastrophic on their own. But multiply them across dozens of interactions per day, and you're spending a significant chunk of your time fixing AI output instead of building with it.


Why Cursor Rules Matter

The difference between a Cursor setup with rules and one without is stark. Here's what changes:

1. Dramatically Higher Accept Rates

The single biggest impact of good cursor rules is that you accept more suggestions as-is. Without rules, you might accept a generated function but then spend two minutes renaming variables, adjusting patterns, and reformatting. With rules, the output matches your conventions on the first try.

2. Consistent Code Across Team Members

When your .cursorrules file is checked into version control (and it should be), every developer on the team gets the same AI behavior. No more "well, Cursor generates it differently on my machine." One file, one set of conventions, consistent output.

3. Fewer Review Cycles

Code review comments like "we don't use default exports here" or "please use our custom error class" disappear when the AI already knows those conventions. Your cursor rules become a living style guide that the AI actually follows.

4. Onboarding Gets Easier

New team members can read the .cursorrules file to understand project conventions at a glance. It's documentation that also happens to be executable. And when they start using Cursor, the AI immediately generates code that matches the team's style.

5. The AI Becomes Context-Aware

This is the big one. Good cursor rules don't just enforce style — they teach the AI about your architecture. When Cursor knows you're using a repository pattern with dependency injection, it generates new services that follow that pattern automatically. When it knows your API uses a specific response envelope format, every endpoint it creates matches that format.


How to Write Good Cursor Rules

Writing effective cursor rules is part art, part engineering. Here's the framework that works.

Start With Your Stack Declaration

The first thing your rules file should do is tell Cursor what you're working with. Be specific:

You are an expert in TypeScript, Next.js 14 (App Router), React 19,
Tailwind CSS v4, Shadcn/UI, and Drizzle ORM with PostgreSQL.
Enter fullscreen mode Exit fullscreen mode

This immediately narrows the AI's focus. Instead of considering all possible ways to build a web app, it focuses on your specific combination of tools.

Declare Your Conventions Explicitly

Don't assume the AI will infer your patterns from context. State them directly:

Code Style:
- Use functional components with arrow function syntax
- Prefer named exports over default exports
- Use TypeScript strict mode conventions
- Write self-documenting code; avoid unnecessary comments
- Use early returns to reduce nesting
Enter fullscreen mode Exit fullscreen mode

The more explicit you are, the less guessing the AI has to do.

Define File and Project Structure

Tell Cursor where things live and how your project is organized:

Project Structure:
- /app — Next.js App Router pages and layouts
- /components/ui — Reusable UI components (Shadcn)
- /components/features — Feature-specific components
- /lib — Utility functions and shared logic
- /server — Server-side code (actions, db queries)
- /types — TypeScript type definitions
Enter fullscreen mode Exit fullscreen mode

This context is gold. When you ask Cursor to create a new component, it knows exactly where to put it and what patterns nearby files use.

Include Do's and Don'ts

Explicit prohibitions are just as valuable as positive instructions:

Do:
- Use server actions for form submissions
- Implement optimistic updates for mutations
- Use Zod for all runtime validation

Don't:
- Never use `any` type — use `unknown` and narrow instead
- Don't use useEffect for data fetching — use server components
- Don't create API route handlers when a server action would work
- Never use inline styles — always use Tailwind classes
Enter fullscreen mode Exit fullscreen mode

Provide Small Examples for Complex Patterns

For patterns that are hard to describe in words, a short code example is worth a thousand rules:

When creating server actions, follow this pattern:

"use server"

import { z } from "zod"
import { actionClient } from "@/lib/safe-action"

export const createPost = actionClient
  .schema(z.object({ title: z.string().min(1), body: z.string() }))
  .action(async ({ parsedInput }) => {
    // implementation
  })
Enter fullscreen mode Exit fullscreen mode

The AI will replicate this pattern precisely for every new server action it generates.

Keep Rules Prioritized

Put the most important rules first. AI models pay more attention to content that appears early. Your non-negotiable conventions should be at the top; nice-to-haves go toward the bottom.


Example Cursor Rules

Here are a few real-world examples showing what good cursor rules look like for different stacks. These are condensed versions — production rules files are typically more comprehensive.

React / Next.js (App Router)

You are an expert in TypeScript, Next.js 14 App Router, React 19,
Tailwind CSS v4, and Shadcn/UI.

Key Conventions:
- Use functional components with TypeScript interfaces for props
- Prefer named exports: export function Component() not export default
- Use server components by default; add "use client" only when needed
- File naming: kebab-case for files, PascalCase for components

Component Pattern:
- Props interface above component: interface ButtonProps { ... }
- Destructure props in function signature
- Use cn() utility for conditional Tailwind classes
- Keep components under 80 lines; extract sub-components when larger

State Management:
- Server state: React Server Components + server actions
- Client state: useReducer for complex state, useState for simple
- URL state: useSearchParams for filter/sort/pagination
- No Redux, no Zustand — keep it simple

Error Handling:
- Use error.tsx boundaries for page-level errors
- Use try/catch in server actions, return { error: string } shape
- Display errors with toast notifications (sonner)

Data Fetching:
- Fetch in server components, not in useEffect
- Use Suspense boundaries with loading.tsx fallbacks
- Revalidate with revalidatePath() after mutations
Enter fullscreen mode Exit fullscreen mode

This is about 40% of what a complete React/Next.js rules file would contain. But even this condensed version dramatically improves Cursor's output for a Next.js project.

Python (FastAPI + SQLAlchemy)

You are an expert in Python 3.12, FastAPI, SQLAlchemy 2.0 (async),
Pydantic v2, and Alembic.

Style:
- Use type hints on ALL function signatures and variables
- Use Annotated types for FastAPI dependencies
- Prefer async/await for all I/O operations
- Use f-strings for string formatting, never .format() or %
- Maximum function length: 30 lines. Extract helpers aggressively.

Architecture:
- /app/api/routes — Route handlers (thin, delegate to services)
- /app/services — Business logic layer
- /app/models — SQLAlchemy ORM models
- /app/schemas — Pydantic request/response schemas
- /app/core — Config, security, database setup

Patterns:
- Route handlers validate input and call services. No business logic
  in route handlers.
- Services accept Pydantic models, return Pydantic models.
- Use dependency injection for database sessions:
  async def get_user(db: AsyncSession = Depends(get_db))
- All database queries go through repository functions, never raw SQL
  in services.

Error Handling:
- Raise HTTPException in routes only, never in services
- Services raise custom exceptions (app/core/exceptions.py)
- Use a global exception handler to map service errors to HTTP codes

Testing:
- Use pytest with pytest-asyncio
- Use factory_boy for test data
- Test services independently from routes
- Use httpx.AsyncClient for integration tests
Enter fullscreen mode Exit fullscreen mode

Notice how this doesn't just describe syntax preferences — it describes an entire architecture. When you ask Cursor to add a new endpoint, it knows to create the route handler, the service function, the Pydantic schemas, and the repository query — all following the right patterns.

Go (Standard Library + sqlc)

You are an expert in Go 1.22, standard library HTTP (net/http),
sqlc for database queries, and pgx for PostgreSQL.

Conventions:
- Follow Effective Go and Go Code Review Comments
- Use standard library where possible; avoid unnecessary dependencies
- Error handling: always check errors, never use _ for error returns
- Use structured logging with log/slog
- Context must be the first parameter in any function that accepts it

Project Layout:
- /cmd/server — Application entry point
- /internal/handler — HTTP handlers
- /internal/service — Business logic
- /internal/store — Database layer (sqlc generated + custom)
- /internal/middleware — HTTP middleware
- /migrations — SQL migration files

HTTP Patterns:
- Use http.NewServeMux for routing (Go 1.22 enhanced patterns)
- Handlers are methods on a struct that holds dependencies
- Middleware wraps http.Handler (func(http.Handler) http.Handler)
- Return JSON with a helper: encode(w, status, data)
- Parse request bodies with a helper: decode(r, &target)

Error Handling:
- Define domain errors in /internal/domain/errors.go
- Services return domain errors
- Handlers map domain errors to HTTP status codes
- Never panic in production code

Testing:
- Table-driven tests for all business logic
- Use httptest.NewServer for handler tests
- Use testcontainers-go for database integration tests
- Test files live next to the code they test
Enter fullscreen mode Exit fullscreen mode

Even this abbreviated Go rules file saves significant time. Without it, Cursor might generate Go code that uses Gin or Echo (popular frameworks) instead of the standard library approach this project uses.

What These Examples Have in Common

Look at the pattern across all three examples:

  1. Stack declaration at the top (what tools/versions)
  2. Style conventions (formatting, naming, preferences)
  3. Architecture description (where things live, how layers interact)
  4. Patterns with examples (how specific operations should be done)
  5. Testing conventions (how to write tests for this project)

This structure works for virtually any language or framework.


Common Mistakes to Avoid

After reviewing hundreds of cursor rules files, these are the mistakes I see most often.

1. Rules That Are Too Vague

# Bad
Write clean code and follow best practices.

# Good
- Use early returns to avoid nesting beyond 2 levels
- Extract functions longer than 30 lines
- Name boolean variables with is/has/should prefix
Enter fullscreen mode Exit fullscreen mode

"Clean code" means different things to different people. The AI needs specific, actionable instructions.

2. Rules That Contradict Each Other

This happens more than you'd think, especially in longer rules files:

# Earlier in the file
- Use server components by default

# Later in the file
- Always wrap data fetching in useEffect hooks
Enter fullscreen mode Exit fullscreen mode

These two instructions are fundamentally incompatible in Next.js. The AI will get confused and produce inconsistent results. Review your rules file for contradictions periodically.

3. Putting Every Rule With Equal Weight

If everything is a priority, nothing is. Structure your rules from most important to least important. The conventions that matter most (architecture patterns, error handling) should be at the top. Minor style preferences (trailing commas, quote style) can go at the bottom — or better yet, be handled by your linter.

4. Not Including Negative Rules

Telling the AI what not to do is sometimes more effective than telling it what to do. If you've noticed Cursor repeatedly generating a pattern you don't want, add an explicit prohibition:

NEVER:
- Do not use barrel exports (index.ts re-exporting everything)
- Do not use enum — use const objects with 'as const' instead
- Do not create wrapper components that only pass props through
Enter fullscreen mode Exit fullscreen mode

5. Ignoring Framework-Specific Patterns

Generic TypeScript rules are fine, but they miss the nuances of your specific framework. A Next.js project needs rules about server vs. client components, data fetching patterns, and routing conventions. A Remix project needs completely different rules about loaders and actions. Make your rules framework-specific, not just language-specific.

6. Never Updating the Rules

Your project evolves. Your rules should too. When you adopt a new library, change an architecture pattern, or discover a better convention, update the .cursorrules file. Treat it like living documentation. A stale rules file can be worse than no rules file at all — it actively pushes the AI toward outdated patterns.

7. Making the File Too Long

There's a sweet spot. Cursor rules that are under 500 words probably aren't detailed enough to be useful. Rules that are over 5,000 words start to dilute the most important instructions. Aim for 1,000-2,500 words for most projects. If you need more, consider whether some of those rules should be enforced by your linter or formatter instead.


Ready-Made Cursor Rules Collections

Writing cursor rules from scratch takes time. You need to think through your conventions, test how the AI responds to different instructions, and iterate. For a single project, that might take an hour or two. If you work across multiple languages and frameworks, you're looking at a full day of work.

That's why curated collections of cursor rules have become popular in the developer community. A good collection gives you battle-tested rules files for specific frameworks that you can drop into your project and immediately start getting better AI output. You customize the parts that are unique to your project and keep the framework-specific conventions as-is.

The key things to look for in a rules collection:

  • Framework-specific, not generic. Rules for "React" are less useful than rules for "Next.js 14 App Router with Tailwind and Shadcn." The more specific the rules are to a particular stack combination, the better the AI output.

  • Architecture patterns, not just style. Good rules go beyond formatting. They describe how your codebase is organized, how data flows between layers, and how errors are handled. This is the stuff that saves the most time.

  • Tested against real projects. Rules that look good on paper might produce weird AI behavior in practice. You want rules that someone has actually used in production and refined based on real output.

  • Regularly updated. Frameworks change fast. Cursor rules for Next.js 13 (Pages Router) are actively harmful in a Next.js 14+ (App Router) project. Make sure any collection you use tracks the latest framework versions.


Advanced Tips

Once you have the basics down, these techniques take your cursor rules to the next level.

Use Section Headers

Structure your rules file with clear markdown headers. This helps both human readers and the AI parse the content:

# Stack
...

# Code Style
...

# Architecture
...

# Patterns
...

# Testing
...
Enter fullscreen mode Exit fullscreen mode

Reference Your Actual File Structure

Instead of abstract descriptions, reference real paths in your project:

When creating a new API endpoint, create these files:
1. Route handler: /app/api/[resource]/route.ts
2. Validation schema: /lib/validations/[resource].ts
3. Service function: /server/services/[resource].ts
4. Test file: /__tests__/api/[resource].test.ts
Enter fullscreen mode Exit fullscreen mode

Include Response Format Preferences

Tell Cursor how you want it to communicate, not just code:

When responding:
- Show only the changed code, not the entire file
- Explain architectural decisions briefly
- If multiple approaches exist, recommend one and explain why
- Always consider error cases and edge cases
Enter fullscreen mode Exit fullscreen mode

Create Rules for Your CI/CD Pipeline

If your CI enforces specific checks, include those as rules so the AI doesn't generate code that fails in CI:

CI Requirements:
- All exports must have explicit return types (enforced by eslint)
- No console.log in production code (use logger utility)
- All async functions must have error handling
- Test coverage must be maintained above 80%
Enter fullscreen mode Exit fullscreen mode

Conclusion

Cursor rules are one of those small investments that pay compounding returns. A few hours of work on a .cursorrules file saves you minutes on every single AI interaction — and those minutes add up fast when you're using Cursor dozens of times per day.

The formula is straightforward:

  1. Declare your exact stack
  2. Define your conventions explicitly
  3. Describe your architecture and project structure
  4. Include examples for complex patterns
  5. Add prohibitions for things you never want
  6. Keep it updated as your project evolves

Whether you write your rules from scratch or start with a proven template, the important thing is to start. Even a basic rules file with your stack declaration and top 10 conventions will noticeably improve your Cursor experience.


Want to skip the setup work? The Cursor Rules Mega Pack includes 20+ production-ready .cursorrules files for every major framework and language — React, Next.js, Vue, Svelte, Python, Go, Rust, TypeScript, and more. Each rules file is battle-tested on real projects and updated for 2026 framework versions. Drop them into your project root and start getting dramatically better AI output in seconds.

Get the Cursor Rules Mega Pack ($19) →

Top comments (0)