comparison12 min read

Best Cursor Rules in 2026 — 20 Rules to Supercharge Your AI Coding

Curated list of 20 tested .cursorrules files for React, Vue, Go, Python, Next.js, and more. Learn how to configure Cursor AI for maximum productivity.

WI
William Wang · Apr 12, 2026

William Wang — Founder of TokRepo & GEOScore AI. Building tools for AI developer productivity and search visibility.

Best Cursor Rules in 2026 — 20 Rules to Supercharge Your AI Coding
Table of Contents

Learn how to configure Cursor AI with 20 tested .cursorrules files that cover frontend, backend, full-stack, and general development workflows. Each rule has been tested on real projects — we show you the format, the content, and how to combine multiple rules for maximum impact.

Prerequisites

  • Cursor installed (v0.45+)
  • A project directory where you want rules active
  • Basic understanding of how AI code assistants work

What Are Cursor Rules?

Cursor Rules are instruction files that tell Cursor AI how to behave in your project. Drop a .cursorrules file in your project root, and Cursor reads it every time you interact with its AI features — autocomplete, chat, Composer, and inline edits.

<!-- .cursorrules -->
You are an expert React developer.

## Code Style
- Use functional components with hooks
- Prefer named exports over default exports
- Use TypeScript strict mode

## Architecture
- Follow the feature-based folder structure
- Keep components under 200 lines
- Extract shared logic into custom hooks

The file sits at your project root alongside package.json or go.mod. Cursor loads it automatically — no configuration needed.

How Rules Get Applied

┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  .cursorrules │────▶│  Cursor AI   │────▶│  Generated   │
│  (your rules) │     │  (context)   │     │  Code Output │
└──────────────┘     └──────────────┘     └──────────────┘
                           ▲
                           │
                     ┌──────────────┐
                     │  Your Prompt │
                     └──────────────┘

Rules are prepended to every AI interaction. They act as a system prompt for your project, ensuring consistent behavior regardless of who's prompting.

Frontend Rules

1. React + TypeScript

The most popular Cursor rule. Enforces functional components, strict TypeScript, and modern React patterns.

<!-- .cursorrules -->
You are an expert React and TypeScript developer.

## Rules
- Use functional components exclusively — no class components
- TypeScript strict mode: no `any`, no implicit returns
- Use React.FC sparingly; prefer explicit prop types
- State management: Zustand for global, useState for local
- Styling: Tailwind CSS utility classes, no inline styles

## Component Structure
interface Props {
  title: string;
  onAction: () => void;
}

export function MyComponent({ title, onAction }: Props) {
  return <button onClick={onAction}>{title}</button>;
}

Best for: Teams using Create React App, Vite, or any React project with TypeScript.

2. Vue 3 + Composition API

Enforces <script setup>, composables, and Pinia state management.

<!-- .cursorrules -->
You are an expert Vue 3 developer using the Composition API.

## Rules
- Always use <script setup lang="ts">
- Prefer composables (use*) for shared logic
- State management: Pinia stores only
- No Options API — ever
- Use defineProps and defineEmits with TypeScript generics

## File Structure
<script setup lang="ts">
import { ref, computed } from 'vue'

const props = defineProps<{ title: string }>()
const count = ref(0)
const doubled = computed(() => count.value * 2)
</script>

Best for: Vue 3 projects, especially those migrating from Options API.

3. Next.js App Router

Focuses on the App Router paradigm — Server Components, Server Actions, and the app/ directory structure.

<!-- .cursorrules -->
You are an expert Next.js developer using the App Router (v14+).

## Rules
- Default to Server Components; add 'use client' only when needed
- Use Server Actions for form handling and mutations
- Route handlers in app/api/ for external API endpoints
- Metadata API for SEO (generateMetadata, not Head)
- Image optimization: always use next/image
- Loading states: loading.tsx and Suspense boundaries

## Data Fetching
- Server Components: fetch() with revalidate options
- Client Components: useSWR or React Query
- Never use getServerSideProps or getStaticProps (Pages Router patterns)

Best for: Next.js 14+ projects using the App Router. If you're on Pages Router, use a different rule.

4. Nuxt 3

Covers Nuxt 3 conventions — auto-imports, server routes, and the composables/ directory.

<!-- .cursorrules -->
You are an expert Nuxt 3 developer.

## Rules
- Use auto-imported composables (useState, useRoute, useFetch)
- Server routes in server/api/ with defineEventHandler
- Components auto-imported from components/ directory
- Layouts in layouts/, middleware in middleware/
- Use definePageMeta for page-level configuration
- SSR by default; use <ClientOnly> for browser-only components

Best for: Nuxt 3 projects. See our 15 Best Claude Code Skills for complementary Nuxt tooling.

5. Tailwind CSS

Ensures consistent utility class usage and prevents common Tailwind anti-patterns.

<!-- .cursorrules -->
## Tailwind CSS Rules
- Never use @apply in components — use utility classes directly
- Responsive: mobile-first (sm:, md:, lg:, xl:)
- Dark mode: use dark: prefix, assume class-based dark mode
- Custom values: extend theme in tailwind.config.ts, don't use arbitrary values
- Spacing: stick to the default scale (4, 8, 12, 16...), avoid arbitrary px values
- Colors: use project theme colors, never hardcode hex values

Best for: Any project using Tailwind CSS, regardless of framework.

Backend Rules

6. Go (Golang)

Enforces idiomatic Go — error handling, naming conventions, and package structure.

<!-- .cursorrules -->
You are an expert Go developer following Go idioms.

## Rules
- Always handle errors explicitly — never use _ for error returns
- Use short variable names in small scopes (i, j, n), descriptive names in larger scopes
- Prefer returning errors over panicking
- Package names: short, lowercase, no underscores
- Interfaces: accept interfaces, return structs
- Concurrency: always use context.Context as first parameter
- Testing: table-driven tests with subtests

## Error Handling Pattern
result, err := doSomething()
if err != nil {
    return fmt.Errorf("doSomething failed: %w", err)
}

Best for: Go microservices, CLI tools, and backend APIs.

7. Python (FastAPI)

Covers type hints, Pydantic models, and async patterns.

<!-- .cursorrules -->
You are an expert Python developer using FastAPI.

## Rules
- Type hints on all function signatures — no untyped code
- Pydantic v2 models for request/response schemas
- Async by default: use async def for route handlers
- Dependency injection via Depends()
- Error handling: raise HTTPException with proper status codes
- Database: SQLAlchemy 2.0 async with typed queries

## Route Pattern
@router.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: AsyncSession = Depends(get_db)):
    user = await db.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

Best for: Python backends using FastAPI, SQLAlchemy, and Pydantic.

8. Node.js (Express/Hono)

Covers modern Node patterns — ESM imports, middleware composition, and error handling.

<!-- .cursorrules -->
You are an expert Node.js backend developer.

## Rules
- ESM imports (import/export), never CommonJS (require)
- Use Hono or Express with TypeScript
- Middleware: compose small, focused middleware functions
- Validation: use Zod for request body validation
- Error handling: centralized error handler middleware
- Environment: use dotenv, never hardcode config values
- Logging: structured JSON logs with pino

## Middleware Pattern
const validateBody = (schema: ZodSchema) => async (c: Context, next: Next) => {
  const body = await c.req.json()
  const result = schema.safeParse(body)
  if (!result.success) return c.json({ error: result.error }, 400)
  c.set('body', result.data)
  await next()
}

Best for: Node.js APIs, especially with Hono, Express, or Fastify.

9. Django

Covers Django conventions — model design, views, serializers, and admin.

<!-- .cursorrules -->
You are an expert Django developer.

## Rules
- Use Django REST Framework for APIs
- Models: explicit field types, always add Meta class with ordering
- Views: prefer class-based views (APIView, ViewSet)
- Serializers: always validate at the serializer level
- Migrations: always review auto-generated migrations before applying
- Security: use Django's built-in protections (CSRF, XSS, SQL injection)
- Testing: use pytest-django with fixtures

## Model Pattern
class Article(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

10. Rust

Covers ownership patterns, error handling with Result, and idiomatic Rust.

<!-- .cursorrules -->
You are an expert Rust developer.

## Rules
- Prefer &str over String for function parameters
- Use Result<T, E> for fallible operations, never panic in libraries
- Derive common traits: Debug, Clone, PartialEq
- Use thiserror for library errors, anyhow for application errors
- Prefer iterators over manual loops
- Lifetimes: only annotate when the compiler requires it

## Error Handling
#[derive(Debug, thiserror::Error)]
enum AppError {
    #[error("not found: {0}")]
    NotFound(String),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

Full-Stack Rules

11. T3 Stack (Next.js + tRPC + Prisma)

<!-- .cursorrules -->
You are an expert T3 Stack developer (Next.js, tRPC, Prisma, NextAuth).

## Rules
- tRPC routers in server/api/routers/ with input validation via Zod
- Prisma: always use select/include to avoid over-fetching
- Auth: use NextAuth.js with getServerSession for server-side checks
- Type safety: leverage tRPC's end-to-end type inference — never manually type API responses

12. MERN Stack

<!-- .cursorrules -->
You are an expert MERN stack developer (MongoDB, Express, React, Node).

## Rules
- Backend: Express with TypeScript, Mongoose ODM
- Frontend: React with TypeScript and Vite
- API: RESTful with proper HTTP status codes
- Validation: Zod on backend, React Hook Form on frontend
- Auth: JWT with httpOnly cookies, never localStorage

13. Laravel + Vue

<!-- .cursorrules -->
You are an expert Laravel + Vue developer.

## Rules
- Laravel: use Eloquent relationships, form requests for validation
- Vue: Composition API with <script setup>
- Inertia.js for SPA-like navigation without API routes
- Auth: Laravel Sanctum for SPA authentication
- Testing: PHPUnit for backend, Vitest for frontend

14. Rails + React

<!-- .cursorrules -->
You are an expert Ruby on Rails + React developer.

## Rules
- Rails: follow Rails conventions (fat models, skinny controllers)
- React: served via Rails asset pipeline or separate Vite app
- API: jbuilder or Active Model Serializers for JSON responses
- Testing: RSpec + FactoryBot for Rails, Jest for React
- Database: use migrations, never modify schema directly

15. Supabase Full-Stack

<!-- .cursorrules -->
You are an expert Supabase developer.

## Rules
- Use Supabase client library, never raw PostgreSQL connections
- Auth: Supabase Auth with Row Level Security (RLS)
- Storage: Supabase Storage with signed URLs for private files
- Edge Functions: Deno runtime with Supabase client
- Real-time: use Supabase Realtime for live subscriptions
- Always enable RLS on every table — no exceptions

General Rules

16. Code Style Enforcer

<!-- .cursorrules -->
## Code Style
- Maximum function length: 30 lines
- Maximum file length: 300 lines
- Maximum function parameters: 4 (use options object for more)
- No nested ternaries
- No magic numbers — define constants with descriptive names
- Comments explain WHY, not WHAT
- No commented-out code — delete it, Git remembers

17. Testing Standards

<!-- .cursorrules -->
## Testing Rules
- Every new function must have at least one test
- Test naming: describe("functionName") → it("should do X when Y")
- Arrange-Act-Assert pattern in every test
- No test interdependencies — each test runs in isolation
- Mock external services, never real APIs in tests
- Coverage target: 80% line coverage minimum
- Prefer integration tests over unit tests for API endpoints

18. Security Rules

<!-- .cursorrules -->
## Security Rules
- Never hardcode secrets, API keys, or passwords
- Always parameterize database queries — no string concatenation
- Validate and sanitize all user input on the server side
- Use HTTPS for all external API calls
- Set proper CORS headers — never use wildcard (*) in production
- Hash passwords with bcrypt (cost factor 12+)
- JWT: short expiry (15 min access, 7 day refresh), httpOnly cookies

19. Git Commit Standards

<!-- .cursorrules -->
## Git Commit Rules
- Follow Conventional Commits: type(scope): description
- Types: feat, fix, docs, style, refactor, test, chore
- Subject line: max 72 characters, imperative mood
- Body: explain WHY, not WHAT (the diff shows WHAT)
- One logical change per commit
- Never commit generated files, .env, or node_modules

20. Documentation Standards

<!-- .cursorrules -->
## Documentation Rules
- Public functions: JSDoc with @param, @returns, @throws
- README: project purpose, setup instructions, architecture overview
- API endpoints: document request/response schemas with examples
- Complex algorithms: explain the approach in comments above
- Architecture decisions: ADR format in docs/decisions/
- No stale documentation — update docs in the same PR as code changes

How to Create Your Own Cursor Rule

Step 1: Identify Your Patterns

List the top 10 things you repeat in code reviews. These become your rules.

# Review your last 20 PR comments
# Look for patterns like:
# - "Please use TypeScript strict mode"
# - "Always handle the error case"
# - "Use our Button component, not native <button>"

Step 2: Write the Rule File

<!-- .cursorrules -->
You are an expert [your stack] developer working on [project name].

## Architecture
[Your architecture decisions]

## Code Style
[Your team's conventions]

## Common Patterns
[Code templates for frequent tasks]

## Avoid
[Anti-patterns specific to your project]

Step 3: Test and Iterate

# Drop the file in your project root
echo "your rules" > .cursorrules

# Open Cursor and try common tasks
# If the AI ignores a rule, make it more explicit
# If a rule causes bad output, remove or rephrase it

Step 4: Share With Your Team

# Commit to your repo
git add .cursorrules
git commit -m "docs: add cursor rules for team coding standards"

For a deeper dive into building shareable skills, see How to Create Your First Agent Skill.

Cursor Rules vs Claude Code Skills

How do Cursor Rules compare to Claude Code Skills? They solve similar problems but work differently.

FeatureCursor RulesClaude Code Skills
Format.cursorrules (single file).md files in .claude/commands/
ScopeEntire projectPer skill (invoked on demand)
ActivationAlways activeTriggered by command or pattern
DistributionGit repo onlyGit, TokRepo, or custom registry
EcosystemCommunity .cursorrules reposTokRepo (500+ skills)
Multi-toolCursor onlyClaude Code, Codex CLI, Gemini CLI
ComplexitySimple (one file)Can be complex (multi-file, dependencies)
Best forCoding standardsComplex workflows & automation

Bottom line: Cursor Rules are ideal for enforcing coding standards within Cursor. Claude Code Skills are better for complex, multi-step workflows that go beyond code style — things like project management, debugging, and SEO audits. Many developers use both — Cursor Rules in Cursor, Skills in Claude Code.

For teams evaluating both tools, see our Skills vs MCP vs Rules comparison for a comprehensive breakdown.

FAQ

Can I use multiple .cursorrules files?

Cursor only reads one .cursorrules file from the project root. If you need different rules for different parts of your project, combine them into sections within the single file. For monorepos, place the file at the monorepo root.

How long should a .cursorrules file be?

Keep it under 2,000 words. Longer rules dilute the AI's attention. Focus on your top 10-15 most important conventions. If you have more, prioritize the rules that cause the most code review comments.

Do Cursor Rules work with other AI assistants?

No — .cursorrules is specific to Cursor. For Claude Code, use agent skills. For GitHub Copilot, use .github/copilot-instructions.md. The Agent Skills Standard aims to create a universal format across tools.

Next Steps