Prompts Guide Cursor Configuration

Cursor Rules: The Complete Guide to .cursorrules

Configure Cursor AI to write better, more secure code for your projects

Quick Answer

Cursor rules are project-specific instructions that guide Cursor AI's behavior. Create a .cursorrules file in your project root (or use .cursor/rules/) with your tech stack, coding standards, and security rules. This guide includes copy-paste templates with security rules that prevent common vulnerabilities.

What are Cursor rules?

Cursor rules are configuration files that tell Cursor AI how to generate code for your specific project. Instead of explaining your tech stack and preferences in every prompt, you write them once in a rules file. Cursor reads these rules before responding, making output more consistent, secure, and aligned with your coding standards.

Think of cursor rules as a persistent system prompt for your project. They're especially valuable for vibe coders because AI tools tend to generate working code without considering security. Rules like "always use parameterized queries" guide Cursor toward secure patterns from the start.

The community has embraced cursor rules - the awesome-cursorrules repository has over 36,000 stars with 150+ community-contributed rule sets for different frameworks and use cases.

How to create a .cursorrules file

Create a file named .cursorrules in your project root. Cursor automatically detects and applies these rules to all AI interactions in that project. Here's the basic structure:

Project Structure
your-project/
├── .cursorrules          # Legacy location (still works)
├── .cursor/
│   └── rules/            # New recommended location
│       ├── core.md       # Always-on rules
│       ├── security.md   # Security patterns
│       └── testing.md    # Test conventions
├── src/
└── package.json

The newer .cursor/rules/ folder approach offers more flexibility: organize rules into separate files, use frontmatter for activation modes, and keep rules focused. Cursor merges all applicable rules into the context.

Rule file format (with frontmatter)

.cursor/rules/security.md
---
description: "Security rules for database and auth patterns"
alwaysApply: true
globs: ["**/*.ts", "**/*.tsx", "**/*.js"]
---

# Security Rules

## Database Security
- NEVER use template literals for SQL queries
- ALWAYS use parameterized queries or ORM methods
- Validate input types before database operations

## Authentication
- Check auth on EVERY API route
- Use middleware for auth, not inline checks
- Never trust client-side auth state alone

Cursor rules activation modes

Rules can be applied in different ways depending on your needs. Use frontmatter to control when rules activate:

Always Apply

alwaysApply: true

Active in every conversation. Use for core project rules, security requirements, and tech stack definitions.

Intelligent (AI Decides)

alwaysApply: false

AI reads the description and decides if relevant. Good for specialized rules like testing or deployment.

File-Specific

globs: ["*.ts"]

Triggered when working with matching files. Use for language-specific conventions (TypeScript vs Python).

Manual

@rule-name

Activated by mentioning in chat. Good for optional workflows or specialized tasks.

Rule precedence: Team Rules → Project Rules → User Rules. Higher levels override lower ones, so team-wide security rules take priority over individual preferences.

Essential cursor rules categories

Every project should include rules in these categories. Security rules are especially critical for vibe coders since AI tools often generate vulnerable patterns by default.

1. Project Context

Tech stack, framework versions, key architectural decisions. Helps Cursor understand what libraries and patterns to use.

2. Code Style

Naming conventions, formatting preferences, component patterns. Keeps generated code consistent with your existing codebase.

3. Framework Rules

Next.js App Router patterns, React hooks conventions, API structure. Framework-specific best practices.

4. Security Rules (Critical!)

Database query patterns, authentication requirements, input validation. This is where most vibe coders fall short. See our security rules library below.

5. Response Format

How Cursor should structure responses, comment style, explanation level. Customize the AI's communication style.

Security rules for Cursor (copy-paste ready)

These security rules prevent the most common vulnerabilities in vibe coded projects. Copy the entire block into your .cursorrules file or create a dedicated .cursor/rules/security.md.

Complete Security Rules
# Security Rules

## Database Security
- NEVER use template literals for SQL queries
- ALWAYS use parameterized queries or ORM methods
- Validate input types before any database operation
- Use allowlists for dynamic table/column names

Patterns:
- SECURE: db.query('SELECT * FROM users WHERE id = $1', [userId])
- SECURE: prisma.user.findUnique({ where: { id: userId } })
- VULNERABLE: db.query(`SELECT * FROM users WHERE id = ${userId}`)

## Authentication
- Check authentication on EVERY API route and Server Action
- Use middleware for auth checks, not inline code
- Never trust client-side auth state for server decisions
- Implement proper session validation

Pattern for protected routes:
1. Get session/token
2. Validate session exists and is valid
3. Check user permissions if needed
4. THEN process the request

## Input Validation
- Validate ALL user input on the server
- Use Zod or similar for schema validation
- Never pass raw user input to:
  - Database queries
  - File system operations
  - Shell commands
  - URL redirects
  - HTML rendering (dangerouslySetInnerHTML)

Pattern:
const schema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100)
})
const result = schema.safeParse(input)
if (!result.success) return error(400, 'Invalid input')

## Secret Handling
- NEVER hardcode API keys, passwords, or tokens
- Use environment variables: process.env.SECRET_NAME
- Never log secrets or include in error messages
- Never commit .env files (add to .gitignore)
- Use different secrets for dev/staging/prod

Pattern:
- SECURE: const apiKey = process.env.STRIPE_SECRET_KEY
- VULNERABLE: const apiKey = "sk_live_abc123..."

## Path Traversal Prevention
- Validate file paths before any file operation
- Use allowlists for permitted directories
- Sanitize user-provided filenames
- Never construct paths with user input directly

Pattern:
- SECURE: const safePath = path.join(UPLOAD_DIR, path.basename(userFile))
- VULNERABLE: const unsafePath = path.join('/uploads', userProvidedPath)

## Authorization (Beyond Auth)
- Check resource OWNERSHIP, not just authentication
- Verify user can access the specific resource requested
- Use WHERE clauses that include user ID
- Never expose internal IDs without ownership check

Pattern:
- SECURE: where: { id: resourceId, userId: session.user.id }
- VULNERABLE: where: { id: resourceId } // Missing ownership check

These rules address the vulnerabilities we cover in our security guides: SQL injection, hardcoded secrets, missing authentication, IDOR, and path traversal.

Cursor rules examples by stack

Complete cursor rules templates for popular vibe coding stacks. Copy the one that matches your project and customize as needed.

Next.js + TypeScript

App Router with Server Components

# Next.js + TypeScript Project

## Tech Stack
- Next.js 14 with App Router
- TypeScript in strict mode
- Tailwind CSS for styling
- Supabase for backend

## Code Patterns
- Use Server Components by default
- Client Components only when needed (interactivity, hooks)
- Use Server Actions for mutations
- Prefer named exports over default exports

## Security Rules
- NEVER use template literals for database queries
- ALWAYS validate input with Zod on server
- Check authentication in every Server Action
- Use parameterized queries: `$1, $2` not `${var}`
- Never expose server secrets in client code

## File Organization
- `/app` - Routes and layouts
- `/components` - Reusable UI components
- `/lib` - Utilities and helpers
- `/types` - TypeScript interfaces

React + Supabase

Vite-based SPA with Supabase backend

# React + Supabase Project

## Tech Stack
- React 18 with Vite
- TypeScript strict mode
- Supabase for auth and database
- React Query for data fetching

## Auth Patterns
- Use Supabase auth helpers
- Check session in protected routes
- Handle auth state with context
- Refresh tokens automatically

## Database Security
- Enable RLS on ALL tables
- Use auth.uid() in RLS policies
- Never expose service_role key
- Validate all inputs before queries

## Code Style
- Functional components only
- Custom hooks for reusable logic
- Collocate related files
- Use TypeScript interfaces for props

Python + FastAPI

Modern Python API with type hints

# Python + FastAPI Project

## Tech Stack
- Python 3.11+
- FastAPI for API framework
- SQLAlchemy with async support
- Pydantic for validation

## Security Rules
- Use Pydantic models for ALL input validation
- NEVER use f-strings for SQL queries
- Use SQLAlchemy ORM or parameterized queries
- Implement rate limiting on auth endpoints
- Hash passwords with bcrypt

## Code Patterns
- Type hints on all functions
- Async/await for database operations
- Dependency injection for auth
- Separate routes, services, and models

## Error Handling
- Return proper HTTP status codes
- Never expose stack traces in production
- Log errors with context, not user input

Cursor rules best practices

Do

  • Keep rules under 500 lines total
  • Be specific with examples
  • Include anti-patterns (what NOT to do)
  • Update rules as project evolves
  • Split into focused modules
  • Use file references @filename
  • Version control your rules

Don't

  • Write novel-length rules
  • Use vague language ("write good code")
  • Only show happy paths
  • Set and forget (review quarterly)
  • Put everything in one giant file
  • Copy-paste code instead of referencing
  • Include sensitive information

Cursor rules vs CLAUDE.md

If you use both Cursor and Claude Code, you might wonder which configuration to use. Here's the breakdown:

Feature.cursorrulesCLAUDE.md
ToolCursor IDEClaude Code (CLI)
Location.cursor/rules/ or root4-tier hierarchy
FormatMarkdown + frontmatterMarkdown with imports
Activation4 modes (always, intelligent, glob, manual)Path-specific rules
Best forIDE workflows, team rulesCLI workflows, complex projects

For teams using both tools, create an AGENTS.md file with shared rules - it's supported by both Cursor and Claude Code as a universal fallback. See our CLAUDE.md guide for more details.

Frequently asked questions

What is a .cursorrules file?

A .cursorrules file is a project-specific configuration file that tells Cursor AI how to write code for your project. It contains instructions about your tech stack, coding conventions, and security requirements. Cursor reads these rules before generating code, making output more consistent and secure.

Where do I put my cursor rules?

You have two options: create a .cursorrules file in your project root (legacy but still works), or use the newer .cursor/rules/ folder with separate .md files for different rule sets. The folder approach lets you organize rules by category (security.md, typescript.md, etc.) and supports frontmatter for activation modes.

What should I include in cursor rules?

Include: your tech stack (Next.js, TypeScript, etc.), code style preferences, security rules (parameterized queries, auth checks), framework conventions, and project-specific patterns. The most important are security rules that prevent vulnerabilities AI tools commonly generate.

Do cursor rules work with all models?

Yes. Cursor rules work regardless of which underlying model you use (Claude, GPT-4, etc.). The rules are injected into the system context before your prompts, so all models receive the same instructions. Different models may follow rules with varying precision, but all respect the configuration.

How long should cursor rules be?

Keep rules under 500 lines total. Shorter, focused rules work better than long documents. Split into multiple files in .cursor/rules/ if you have many rules. Each rule should be specific and actionable - "use parameterized queries" is better than "write secure code".

What is the difference between .cursorrules and system prompts?

.cursorrules are project-specific and live in your codebase (version controlled, shared with team). System prompts are user-level and apply globally. Use .cursorrules for project conventions and security rules; use system prompts for personal preferences like response format.

Can cursor rules prevent security issues?

Yes, but they reduce rather than eliminate risk. Rules like "always use parameterized queries" and "check authentication on every route" guide Cursor toward secure patterns. However, always review generated code - rules are guidance, not guarantees. Combine with scanning tools for defense in depth.

Scan Your Cursor Projects for Vulnerabilities

Rules help prevent vulnerabilities, but they can't catch everything. VibeShip Scanner automatically detects SQL injection, XSS, hardcoded secrets, and more in your vibe coded projects.

Scan Your Code Free →

Related content

External resources