Prompts Cursor

Cursor Rules File: Complete .cursorrules Syntax Reference

Technical reference for Cursor AI configuration files - frontmatter options, file locations, rule precedence, and syntax patterns.

Quick Answer

A Cursor rules file (.cursorrules or .cursor/rules/*.md) is a markdown file that teaches Cursor AI your project's patterns. Use YAML frontmatter for options: description (AI relevance), alwaysApply (auto-load), and globs (file patterns). Team rules override project rules, which override user rules.

What is a cursor rules file?

A cursor rules file is a markdown configuration that customizes how Cursor AI generates code for your project. It contains your coding standards, architecture patterns, and security requirements in a format Cursor reads before every suggestion.

When you're vibe coding with Cursor, these rules transform generic AI suggestions into project-specific code. Instead of getting boilerplate React patterns, Cursor learns your exact stack: your ORM, auth library, and folder structure.

Two file formats

.cursorrules - Legacy single-file format (still works)
.cursor/rules/*.md - Modern multi-file format (recommended)

Where do cursor rules files go?

Cursor reads rules from multiple locations with a clear precedence hierarchy. Understanding this lets you set organization-wide standards while allowing project-specific overrides.

Highest Priority

Team Rules

.cursor/rules/*.md (shared via git)

Committed to repo, shared with all team members. Overrides everything else.

Medium Priority

Project Rules

.cursorrules (project root)

Legacy format. Works but prefer .cursor/rules/ for new projects.

Lowest Priority

User Rules

~/.cursor/rules/*.md

Personal preferences. Applied to all projects but overridden by project/team rules.

Folder Structure
project/
├── .cursor/
│   └── rules/
│       ├── core.md          # Always-on project rules
│       ├── security.md      # Security patterns (alwaysApply: true)
│       ├── typescript.md    # TS rules (globs: ["**/*.ts"])
│       └── testing.md       # Test patterns (globs: ["**/*.test.*"])
├── .cursorrules             # Legacy (optional, deprecated)
└── AGENTS.md                # Cross-tool fallback

What frontmatter options are available?

Frontmatter is YAML metadata at the top of rule files that controls when and how rules apply. These three options give you precise control over rule activation.

OptionTypeDescriptionExample
descriptionstringHelps AI decide if rule is relevant to current task"TypeScript type safety patterns"
alwaysApplybooleanLoad this rule in every conversationtrue or false
globsarrayApply only when working with matching files["**/*.ts", "**/*.tsx"]
YAML
---
description: "React component patterns for Next.js App Router"
alwaysApply: false
globs: ["app/**/*.tsx", "components/**/*.tsx"]
---

# React Component Rules
...

How do rule activation modes work?

Cursor supports four activation modes that determine when rules are loaded into context. Choose based on how universally the rule should apply.

Always Apply

alwaysApply: true

Active in every chat. Use for security rules, core standards.

Best for: Auth, validation, secrets

Apply Intelligently

alwaysApply: false + description

AI decides relevance from description. Reduces context noise.

Best for: Framework patterns, style guides

File-Specific

globs: ["*.ts"]

Triggered only when working with matching file patterns.

Best for: Language rules, test patterns

Manual

@rule-name in chat

User explicitly activates via @mention. Lowest overhead.

Best for: Rarely-used, specialized rules

What glob patterns can I use?

Glob patterns filter which files trigger rule activation. Cursor uses standard glob syntax, the same patterns you'd use in .gitignore or tsconfig.

PatternMatchesUse Case
**/*.tsAll TypeScript files, any depthTypeScript rules
**/*.tsxAll React TSX filesComponent rules
app/**/*Everything in app/ folderNext.js App Router rules
**/*.test.*All test filesTesting rules
src/lib/**/*.tsTypeScript in src/lib/Library code rules
*.config.*Config files in rootConfig file patterns
YAML
---
description: "Frontend component rules"
globs: ["**/*.tsx", "**/*.jsx", "components/**/*"]
---

How do I reference other files in rules?

Use @filename syntax to include context from other project files without copy-pasting code. Cursor reads the referenced file and includes it in context.

Markdown
# API Route Patterns

Follow the patterns in our existing routes:
@src/app/api/users/route.ts
@src/app/api/posts/route.ts

## Type Definitions
Use types from our schema:
@src/types/user.ts
@src/types/post.ts

## Validation
Follow Zod schema patterns:
@src/lib/validations/user.ts
Pro tip

Reference your best code as examples. @filename is more maintainable than copying code into rules because updates to the source file automatically update the rule context.

What should I include in a cursor rules file?

Every cursor rules file should cover your stack, patterns, and security requirements. Here are copy-paste templates for common setups.

Basic Project Rules
---
description: "Project coding standards and patterns"
alwaysApply: true
---

# Project Rules

## Tech Stack
- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Database: Supabase with RLS
- Styling: Tailwind CSS

## Code Patterns
- Use server components by default
- Client components only when needed (interactivity)
- Validate all inputs with Zod schemas

## Security
- NEVER hardcode API keys or secrets
- ALWAYS use parameterized queries
- Check authentication on every API route
TypeScript-Specific Rules (with globs)
---
description: "TypeScript-specific rules for type safety"
alwaysApply: false
globs: ["**/*.ts", "**/*.tsx"]
---

# TypeScript Rules

## Type Safety
- No `any` types - use `unknown` and narrow
- Export types from dedicated /types folder
- Use Zod for runtime validation

## Patterns
```typescript
// Good: Explicit return types
function getUser(id: string): Promise<User | null> {
  return db.user.findUnique({ where: { id } })
}

// Bad: Implicit any
function getUser(id) {
  return db.user.findUnique({ where: { id } })
}
```
Security Rules (Always Apply)
---
description: "Security patterns to prevent common vulnerabilities"
alwaysApply: true
---

# Security Rules

## Database Queries
NEVER use string concatenation for SQL:
```typescript
// WRONG - SQL injection risk
db.query(`SELECT * FROM users WHERE id = ${userId}`)

// CORRECT - parameterized query
db.query('SELECT * FROM users WHERE id = $1', [userId])
```

## Authentication
Check auth on EVERY API route:
```typescript
export async function POST(request: Request) {
  const session = await getServerSession()
  if (!session) {
    return new Response('Unauthorized', { status: 401 })
  }
  // Process request...
}
```

## Input Validation
Validate ALL user input:
```typescript
const schema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100)
})

const result = schema.safeParse(input)
if (!result.success) {
  return new Response('Invalid input', { status: 400 })
}
```

What are cursor rules file best practices?

Follow these patterns from the awesome-cursorrules community (36k+ stars) and official Cursor documentation.

Do

  • Keep individual rule files under 500 lines
  • Use specific examples, not vague guidance
  • Include anti-patterns (what NOT to do)
  • Split rules into focused modules
  • Use @filename references for code examples
  • Set security rules to alwaysApply: true

Don't

  • Create one massive rules file
  • Use vague language ("format properly")
  • Only show happy path examples
  • Set and forget - update as project evolves
  • Copy-paste large code blocks (use @filename)
  • Duplicate rules across multiple files

How does .cursorrules compare to other AI tools?

Each vibe coding tool has its own configuration format. Here's how Cursor compares to alternatives.

FeatureCursorClaude CodeWindsurfCline
Config File.cursor/rules/CLAUDE.md.windsurf/rules/.clinerules/
FrontmatterYes (YAML)Yes (YAML)NoNo
Glob PatternsYesYes (paths:)YesNo
File References@filename@importNoNo
Rule PrecedenceTeam > Project > UserEnterprise > Project > UserWorkspace > GlobalProject > Global

Frequently asked questions

What is a .cursorrules file?

A .cursorrules file is a markdown configuration file that teaches Cursor AI your project's coding standards, architecture, and security rules. Place it in your project root or use the newer .cursor/rules/ folder for modular organization.

Where should I put my cursor rules file?

Use .cursor/rules/ folder for new projects (recommended) or .cursorrules in project root for legacy setups. Both work. The folder approach allows multiple focused rule files instead of one large file.

What is the character limit for cursor rules?

Cursor rules have no hard character limit, but keep individual rule files under 500 lines for best performance. Split large configurations into multiple files in .cursor/rules/ folder.

How do I make rules apply only to specific files?

Use the globs frontmatter option. Add globs: ["**/*.ts", "**/*.tsx"] at the top of your rule file to apply rules only when working with TypeScript files.

What is rule precedence in Cursor?

Team Rules override Project Rules, which override User Rules. Within a project, rules with alwaysApply: true load first, then glob-matched rules, then manually-triggered rules via @mention.

Can I reference other files in cursor rules?

Yes. Use @filename syntax to reference other files in your project. For example, @src/types/user.ts shows Cursor your type definitions without copying code into rules.

Verify Your Cursor Rules Are Working

After setting up cursor rules, test if Cursor follows your security patterns. Ask it to "create an API route" and check if it includes auth, validation, and parameterized queries.

Scan Your Cursor-Generated Code

Related content

Official documentation