Skip to main content
commandsSource-backedReview first Safety Privacy
Cursor logo

/cursor-rules - Cursor Rules Generator for Claude Code

Generate .cursorrules files for AI-native development with project-specific patterns, coding standards, and intelligent context awareness

by JSONbored·added 2025-10-16·
HarnessClaude CodeCursor
Invocation:/cursor-rules [options] <project_type>
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://cursor.com/docs/rules, https://github.com/JSONbored/awesome-claude/blob/main/content/commands/cursor-rules.mdx
Brand
Cursor
Brand domain
cursor.com
Brand asset source
brandfetch
Safety notes
Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project., Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.
Privacy notes
Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution., Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-10-16

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

2 listed

Difficulty

100/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

2 safety and 2 privacy notes across 4 risk areas. Review closely: credentials & tokens, permissions & scopes, third-party handling.

4 areas
  • SafetyExecution & processesReview generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project.
  • SafetyPermissions & scopesLimit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.
  • PrivacyThird-party handlingPrompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution.
  • PrivacyCredentials & tokensRedact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.

Safety notes

  • Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project.
  • Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.

Privacy notes

  • Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution.
  • Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.

Schema details

Install type
cli
Reading time
9 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Runtime and command metadata
Command syntax
/cursor-rules [options] <project_type>
Script body
The `/cursor-rules` command generates comprehensive `.cursorrules` files tailored to your project's technology stack, coding standards, and architectural patterns for optimal AI-assisted development.

## Usage

```
/cursor-rules [options] <project_type>
```

## Options

### Project Types
- `--nextjs` - Next.js application (default)
- `--react` - React application
- `--node` - Node.js backend
- `--fullstack` - Full-stack application
- `--python` - Python project
- `--go` - Go project

### Framework Integration
- `--typescript` - TypeScript project (default: true)
- `--tailwind` - TailwindCSS styling
- `--prisma` - Prisma ORM
- `--trpc` - tRPC for APIs
- `--graphql` - GraphQL APIs

### Code Standards
- `--strict` - Strict mode with comprehensive checks
- `--eslint-config=<config>` - ESLint configuration preset
- `--prettier-config=<config>` - Prettier configuration
- `--naming-convention=<style>` - Naming convention (camelCase, PascalCase)

### Features
- `--security-focused` - Include security best practices
- `--performance-focused` - Include performance optimization rules
- `--accessibility` - Include WCAG 2.2 guidelines
- `--testing` - Include testing patterns

## Examples

### Next.js 15 + React 19 Full-Stack Application

**Command:**
```
/cursor-rules --nextjs --typescript --tailwind --prisma --trpc --strict --security-focused --accessibility
```

**Generated `.cursorrules`:**
```markdown
# Next.js 15 + React 19 Project Rules

You are an expert full-stack developer specializing in Next.js 15, React 19, TypeScript, TailwindCSS v4, Prisma, and tRPC.

## Technology Stack

- **Frontend**: React 19.1.1, Next.js 15.5.2
- **Styling**: TailwindCSS v4.1.13, shadcn/ui
- **Type Safety**: TypeScript 5.x strict mode
- **Database**: PostgreSQL with Prisma ORM
- **API**: tRPC for end-to-end type safety
- **Authentication**: better-auth v1.3.9
- **State Management**: React Server Components, Zustand for client state
- **Forms**: react-hook-form + Zod validation
- **Testing**: Vitest, Playwright

## Code Style & Conventions

### TypeScript
- Use TypeScript 5.x with strict mode enabled
- Never use `any` type - use `unknown` instead
- Prefer type inference when possible
- Use discriminated unions for complex state
- Define interfaces for public APIs, types for internal use

```typescript
// ❌ Bad
function processData(data: any) {
  return data.value;
}

// ✅ Good
interface DataInput {
  value: string;
  timestamp: number;
}

function processData(data: DataInput): string {
  return data.value;
}
```

### React Best Practices
- Use React Server Components by default
- Only use 'use client' when necessary (interactivity, hooks, browser APIs)
- Prefer async Server Components for data fetching
- Use Suspense boundaries for loading states
- Implement error boundaries for error handling

```typescript
// ✅ Server Component (default)
export default async function UserProfile({ userId }: { userId: string }) {
  const user = await db.user.findUnique({ where: { id: userId } });
  
  return <div>{user.name}</div>;
}

// ✅ Client Component (only when needed)
'use client';

import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```

### File Organization
```
app/
├── (auth)/
│   ├── login/
│   │   └── page.tsx
│   └── layout.tsx
├── (dashboard)/
│   ├── dashboard/
│   │   └── page.tsx
│   └── layout.tsx
└── api/
    └── trpc/
        └── [trpc]/
            └── route.ts

components/
├── ui/              # shadcn/ui components
├── forms/           # Form components
└── layout/          # Layout components

lib/
├── api/             # API clients
├── auth/            # Authentication
├── db/              # Database (Prisma)
├── utils/           # Utilities
└── validators/      # Zod schemas
```

### Naming Conventions
- **Files**: kebab-case for files (`user-profile.tsx`)
- **Components**: PascalCase (`UserProfile`)
- **Functions**: camelCase (`getUserById`)
- **Constants**: UPPER_SNAKE_CASE (`MAX_RETRY_COUNT`)
- **Types/Interfaces**: PascalCase (`UserProfile`, `ApiResponse`)
- **Private**: Prefix with underscore (`_internalHelper`)

## Security Best Practices

### Input Validation
- Always validate user input with Zod
- Sanitize HTML content with DOMPurify
- Never trust client-side data

```typescript
import { z } from 'zod';

const userSchema = z.object({
  email: z.string().email().toLowerCase(),
  password: z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/),
});

export async function createUser(input: unknown) {
  const validated = userSchema.parse(input);
  // Safe to use validated data
}
```

### Authentication
- Use better-auth for authentication
- Implement session management with JWT
- Apply rate limiting to auth endpoints
- Use httpOnly, secure cookies

### API Security
- Implement CSRF protection
- Use Content Security Policy (CSP)
- Apply rate limiting
- Validate authorization on every request

```typescript
// app/api/users/[id]/route.ts
import { auth } from '@/lib/auth';

export async function GET(req: Request, { params }: { params: { id: string } }) {
  const session = await auth();
  
  if (!session?.user) {
    return new Response('Unauthorized', { status: 401 });
  }
  
  // Check authorization
  if (session.user.id !== params.id && session.user.role !== 'admin') {
    return new Response('Forbidden', { status: 403 });
  }
  
  // Proceed with request
}
```

## Performance Optimization

### React Performance
- Use React.memo() for expensive components
- Implement useCallback and useMemo appropriately
- Leverage useTransition for non-urgent updates
- Use useDeferredValue for expensive renders

```typescript
import { useTransition, useDeferredValue } from 'react';

function SearchResults({ query }: { query: string }) {
  const [isPending, startTransition] = useTransition();
  const deferredQuery = useDeferredValue(query);
  
  // Expensive filtering uses deferred value
  const results = filterResults(data, deferredQuery);
  
  return <div style={{ opacity: isPending ? 0.5 : 1 }}>{/* results */}</div>;
}
```

### Next.js Optimization
- Use Next.js Image component for images
- Implement dynamic imports for large components
- Use generateStaticParams for static pages
- Leverage Partial Prerendering (PPR)

```typescript
import Image from 'next/image';
import dynamic from 'next/dynamic';

// ✅ Optimized images
<Image src="/hero.jpg" alt="Hero" width={1200} height={600} priority />

// ✅ Code splitting
const HeavyComponent = dynamic(() => import('./heavy-component'));
```

### Database Optimization
- Use Prisma select to fetch only needed fields
- Implement pagination for large datasets
- Use database indexes appropriately
- Batch queries when possible

```typescript
// ✅ Efficient query
const users = await db.user.findMany({
  select: { id: true, name: true, email: true },
  where: { active: true },
  take: 20,
  skip: page * 20,
});
```

## Accessibility (WCAG 2.2 Level AA)

### Semantic HTML
- Use proper HTML5 semantic elements
- Implement proper heading hierarchy
- Use landmark roles appropriately

```typescript
// ✅ Semantic structure
<header>
  <nav aria-label="Main navigation">
    <ul>{/* nav items */}</ul>
  </nav>
</header>
<main>
  <article>
    <h1>Page Title</h1>
  </article>
</main>
<footer>{/* footer content */}</footer>
```

### ARIA and Keyboard Navigation
- Add ARIA labels to interactive elements
- Ensure keyboard navigation works
- Implement focus management
- Provide focus indicators

```typescript
<button
  onClick={handleClick}
  aria-label="Close dialog"
  aria-describedby="dialog-description"
>
  <X className="h-4 w-4" />
  <span className="sr-only">Close</span>
</button>
```

### Color Contrast
- Ensure 4.5:1 contrast ratio for text
- Use TailwindCSS color utilities
- Test with accessibility tools

## Testing Strategy

### Unit Tests (Vitest)
```typescript
import { describe, it, expect } from 'vitest';
import { calculateDiscount } from './pricing';

describe('calculateDiscount', () => {
  it('should apply basic discount', () => {
    expect(calculateDiscount(100, 10)).toBe(10);
  });
  
  it('should cap discount at 50%', () => {
    expect(calculateDiscount(100, 60)).toBe(50);
  });
});
```

### E2E Tests (Playwright)
```typescript
import { test, expect } from '@playwright/test';

test('user can sign in', async ({ page }) => {
  await page.goto('/login');
  await page.fill('input[name="email"]', 'user@example.com');
  await page.fill('input[name="password"]', 'password123');
  await page.click('button[type="submit"]');
  
  await expect(page).toHaveURL('/dashboard');
});
```

## Error Handling

### API Error Handling
```typescript
import { TRPCError } from '@trpc/server';

export const userRouter = router({
  getUser: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input }) => {
      const user = await db.user.findUnique({ where: { id: input.id } });
      
      if (!user) {
        throw new TRPCError({
          code: 'NOT_FOUND',
          message: 'User not found',
        });
      }
      
      return user;
    }),
});
```

### UI Error Boundaries
```typescript
'use client';

import { Component, type ReactNode } from 'react';

export class ErrorBoundary extends Component<
  { children: ReactNode },
  { hasError: boolean }
> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <div>Something went wrong</div>;
    }

    return this.props.children;
  }
}
```

## Git Commit Conventions

Follow Conventional Commits:
```
feat: Add user authentication
fix: Resolve login redirect issue
refactor: Simplify database queries
docs: Update API documentation
test: Add user service tests
chore: Update dependencies
```

## AI Assistant Instructions

When generating code:
1. Always use TypeScript with proper types
2. Follow the file organization structure
3. Implement proper error handling
4. Add accessibility attributes
5. Include security best practices
6. Write self-documenting code with clear variable names
7. Add JSDoc comments for complex functions
8. Suggest tests for new functionality

When reviewing code:
1. Check for type safety violations
2. Verify security best practices
3. Ensure accessibility compliance
4. Identify performance bottlenecks
5. Suggest improvements for code quality
```

### Python + FastAPI Backend

**Command:**
```
/cursor-rules --python --strict --security-focused --testing
```

**Generated `.cursorrules`:**
```markdown
# Python + FastAPI Backend Rules

You are an expert Python backend developer specializing in FastAPI, async programming, and RESTful API design.

## Technology Stack

- **Framework**: FastAPI 0.110+
- **Async**: asyncio, aiohttp
- **ORM**: SQLAlchemy 2.0 (async)
- **Validation**: Pydantic v2
- **Testing**: pytest, pytest-asyncio
- **Linting**: Ruff, mypy

## Code Style

### Type Hints
- Always use type hints for function signatures
- Use `typing` module for complex types
- Enable mypy strict mode

```python
from typing import Optional, List
from datetime import datetime

def get_users(
    limit: int = 10,
    offset: int = 0,
    active_only: bool = True
) -> List[User]:
    """Retrieve users with pagination."""
    return db.query(User).limit(limit).offset(offset).all()
```

### Async/Await
- Use async functions for I/O operations
- Properly await all async calls
- Use `asyncio.gather()` for parallel operations

```python
import asyncio

async def fetch_user_data(user_id: str) -> UserData:
    profile, settings, posts = await asyncio.gather(
        fetch_profile(user_id),
        fetch_settings(user_id),
        fetch_posts(user_id)
    )
    return UserData(profile=profile, settings=settings, posts=posts)
```

### Error Handling
```python
from fastapi import HTTPException

@app.get("/users/{user_id}")
async def get_user(user_id: str) -> User:
    user = await db.get(User, user_id)
    
    if not user:
        raise HTTPException(
            status_code=404,
            detail="User not found"
        )
    
    return user
```

## Security Best Practices

- Use environment variables for secrets
- Implement OAuth2 with JWT
- Apply rate limiting
- Validate all input with Pydantic
- Use parameterized queries

```python
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    user = await verify_token(token)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return user
```
```

## Best Practices

1. **Project-Specific**: Tailor rules to your exact tech stack
2. **Clear Examples**: Include both good and bad code examples
3. **Security First**: Always include security best practices
4. **Performance**: Add performance optimization guidelines
5. **Accessibility**: Include WCAG guidelines for frontend projects
6. **Testing**: Specify testing requirements and patterns
7. **Git Conventions**: Define commit message standards
8. **AI Instructions**: Guide AI on how to generate and review code
Full copyable content
/cursor-rules [options] <project_type>

About this resource

The /cursor-rules command generates comprehensive .cursorrules files tailored to your project's technology stack, coding standards, and architectural patterns for optimal AI-assisted development.

Usage

/cursor-rules [options] <project_type>

Options

Project Types

  • --nextjs - Next.js application (default)
  • --react - React application
  • --node - Node.js backend
  • --fullstack - Full-stack application
  • --python - Python project
  • --go - Go project

Framework Integration

  • --typescript - TypeScript project (default: true)
  • --tailwind - TailwindCSS styling
  • --prisma - Prisma ORM
  • --trpc - tRPC for APIs
  • --graphql - GraphQL APIs

Code Standards

  • --strict - Strict mode with comprehensive checks
  • --eslint-config=<config> - ESLint configuration preset
  • --prettier-config=<config> - Prettier configuration
  • --naming-convention=<style> - Naming convention (camelCase, PascalCase)

Features

  • --security-focused - Include security best practices
  • --performance-focused - Include performance optimization rules
  • --accessibility - Include WCAG 2.2 guidelines
  • --testing - Include testing patterns

Examples

Next.js 15 + React 19 Full-Stack Application

Command:

/cursor-rules --nextjs --typescript --tailwind --prisma --trpc --strict --security-focused --accessibility

Generated .cursorrules:

# Next.js 15 + React 19 Project Rules

You are an expert full-stack developer specializing in Next.js 15, React 19, TypeScript, TailwindCSS v4, Prisma, and tRPC.

## Technology Stack

- **Frontend**: React 19.1.1, Next.js 15.5.2
- **Styling**: TailwindCSS v4.1.13, shadcn/ui
- **Type Safety**: TypeScript 5.x strict mode
- **Database**: PostgreSQL with Prisma ORM
- **API**: tRPC for end-to-end type safety
- **Authentication**: better-auth v1.3.9
- **State Management**: React Server Components, Zustand for client state
- **Forms**: react-hook-form + Zod validation
- **Testing**: Vitest, Playwright

## Code Style & Conventions

### TypeScript

- Use TypeScript 5.x with strict mode enabled
- Never use `any` type - use `unknown` instead
- Prefer type inference when possible
- Use discriminated unions for complex state
- Define interfaces for public APIs, types for internal use

```typescript
// ❌ Bad
function processData(data: any) {
  return data.value;
}

// ✅ Good
interface DataInput {
  value: string;
  timestamp: number;
}

function processData(data: DataInput): string {
  return data.value;
}
```

React Best Practices

  • Use React Server Components by default
  • Only use 'use client' when necessary (interactivity, hooks, browser APIs)
  • Prefer async Server Components for data fetching
  • Use Suspense boundaries for loading states
  • Implement error boundaries for error handling
// ✅ Server Component (default)
export default async function UserProfile({ userId }: { userId: string }) {
  const user = await db.user.findUnique({ where: { id: userId } });

  return <div>{user.name}</div>;
}

// ✅ Client Component (only when needed)
'use client';

import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

File Organization

app/
├── (auth)/
│   ├── login/
│   │   └── page.tsx
│   └── layout.tsx
├── (dashboard)/
│   ├── dashboard/
│   │   └── page.tsx
│   └── layout.tsx
└── api/
    └── trpc/
        └── [trpc]/
            └── route.ts

components/
├── ui/              # shadcn/ui components
├── forms/           # Form components
└── layout/          # Layout components

lib/
├── api/             # API clients
├── auth/            # Authentication
├── db/              # Database (Prisma)
├── utils/           # Utilities
└── validators/      # Zod schemas

Naming Conventions

  • Files: kebab-case for files (user-profile.tsx)
  • Components: PascalCase (UserProfile)
  • Functions: camelCase (getUserById)
  • Constants: UPPER_SNAKE_CASE (MAX_RETRY_COUNT)
  • Types/Interfaces: PascalCase (UserProfile, ApiResponse)
  • Private: Prefix with underscore (_internalHelper)

Security Best Practices

Input Validation

  • Always validate user input with Zod
  • Sanitize HTML content with DOMPurify
  • Never trust client-side data
import { z } from "zod";

const userSchema = z.object({
  email: z.string().email().toLowerCase(),
  password: z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/),
});

export async function createUser(input: unknown) {
  const validated = userSchema.parse(input);
  // Safe to use validated data
}

Authentication

  • Use better-auth for authentication
  • Implement session management with JWT
  • Apply rate limiting to auth endpoints
  • Use httpOnly, secure cookies

API Security

  • Implement CSRF protection
  • Use Content Security Policy (CSP)
  • Apply rate limiting
  • Validate authorization on every request
// app/api/users/[id]/route.ts
import { auth } from "@/lib/auth";

export async function GET(
  req: Request,
  { params }: { params: { id: string } },
) {
  const session = await auth();

  if (!session?.user) {
    return new Response("Unauthorized", { status: 401 });
  }

  // Check authorization
  if (session.user.id !== params.id && session.user.role !== "admin") {
    return new Response("Forbidden", { status: 403 });
  }

  // Proceed with request
}

Performance Optimization

React Performance

  • Use React.memo() for expensive components
  • Implement useCallback and useMemo appropriately
  • Leverage useTransition for non-urgent updates
  • Use useDeferredValue for expensive renders
import { useTransition, useDeferredValue } from 'react';

function SearchResults({ query }: { query: string }) {
  const [isPending, startTransition] = useTransition();
  const deferredQuery = useDeferredValue(query);

  // Expensive filtering uses deferred value
  const results = filterResults(data, deferredQuery);

  return <div style={{ opacity: isPending ? 0.5 : 1 }}>{/* results */}</div>;
}

Next.js Optimization

  • Use Next.js Image component for images
  • Implement dynamic imports for large components
  • Use generateStaticParams for static pages
  • Leverage Partial Prerendering (PPR)
import Image from 'next/image';
import dynamic from 'next/dynamic';

// ✅ Optimized images
<Image src="/hero.jpg" alt="Hero" width={1200} height={600} priority />

// ✅ Code splitting
const HeavyComponent = dynamic(() => import('./heavy-component'));

Database Optimization

  • Use Prisma select to fetch only needed fields
  • Implement pagination for large datasets
  • Use database indexes appropriately
  • Batch queries when possible
// ✅ Efficient query
const users = await db.user.findMany({
  select: { id: true, name: true, email: true },
  where: { active: true },
  take: 20,
  skip: page * 20,
});

Accessibility (WCAG 2.2 Level AA)

Semantic HTML

  • Use proper HTML5 semantic elements
  • Implement proper heading hierarchy
  • Use landmark roles appropriately
// ✅ Semantic structure
<header>
  <nav aria-label="Main navigation">
    <ul>{/* nav items */}</ul>
  </nav>
</header>
<main>
  <article>
    <h1>Page Title</h1>
  </article>
</main>
<footer>{/* footer content */}</footer>

ARIA and Keyboard Navigation

  • Add ARIA labels to interactive elements
  • Ensure keyboard navigation works
  • Implement focus management
  • Provide focus indicators
<button
  onClick={handleClick}
  aria-label="Close dialog"
  aria-describedby="dialog-description"
>
  <X className="h-4 w-4" />
  <span className="sr-only">Close</span>
</button>

Color Contrast

  • Ensure 4.5:1 contrast ratio for text
  • Use TailwindCSS color utilities
  • Test with accessibility tools

Testing Strategy

Unit Tests (Vitest)

import { describe, it, expect } from "vitest";
import { calculateDiscount } from "./pricing";

describe("calculateDiscount", () => {
  it("should apply basic discount", () => {
    expect(calculateDiscount(100, 10)).toBe(10);
  });

  it("should cap discount at 50%", () => {
    expect(calculateDiscount(100, 60)).toBe(50);
  });
});

E2E Tests (Playwright)

import { test, expect } from "@playwright/test";

test("user can sign in", async ({ page }) => {
  await page.goto("/login");
  await page.fill('input[name="email"]', "user@example.com");
  await page.fill('input[name="password"]', "password123");
  await page.click('button[type="submit"]');

  await expect(page).toHaveURL("/dashboard");
});

Error Handling

API Error Handling

import { TRPCError } from "@trpc/server";

export const userRouter = router({
  getUser: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input }) => {
      const user = await db.user.findUnique({ where: { id: input.id } });

      if (!user) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "User not found",
        });
      }

      return user;
    }),
});

UI Error Boundaries

'use client';

import { Component, type ReactNode } from 'react';

export class ErrorBoundary extends Component<
  { children: ReactNode },
  { hasError: boolean }
> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <div>Something went wrong</div>;
    }

    return this.props.children;
  }
}

Git Commit Conventions

Follow Conventional Commits:

feat: Add user authentication
fix: Resolve login redirect issue
refactor: Simplify database queries
docs: Update API documentation
test: Add user service tests
chore: Update dependencies

AI Assistant Instructions

When generating code:

  1. Always use TypeScript with proper types
  2. Follow the file organization structure
  3. Implement proper error handling
  4. Add accessibility attributes
  5. Include security best practices
  6. Write self-documenting code with clear variable names
  7. Add JSDoc comments for complex functions
  8. Suggest tests for new functionality

When reviewing code:

  1. Check for type safety violations
  2. Verify security best practices
  3. Ensure accessibility compliance
  4. Identify performance bottlenecks
  5. Suggest improvements for code quality

### Python + FastAPI Backend

**Command:**

/cursor-rules --python --strict --security-focused --testing


**Generated `.cursorrules`:**
```markdown
# Python + FastAPI Backend Rules

You are an expert Python backend developer specializing in FastAPI, async programming, and RESTful API design.

## Technology Stack

- **Framework**: FastAPI 0.110+
- **Async**: asyncio, aiohttp
- **ORM**: SQLAlchemy 2.0 (async)
- **Validation**: Pydantic v2
- **Testing**: pytest, pytest-asyncio
- **Linting**: Ruff, mypy

## Code Style

### Type Hints
- Always use type hints for function signatures
- Use `typing` module for complex types
- Enable mypy strict mode

```python
from typing import Optional, List
from datetime import datetime

def get_users(
    limit: int = 10,
    offset: int = 0,
    active_only: bool = True
) -> List[User]:
    """Retrieve users with pagination."""
    return db.query(User).limit(limit).offset(offset).all()

Async/Await

  • Use async functions for I/O operations
  • Properly await all async calls
  • Use asyncio.gather() for parallel operations
import asyncio

async def fetch_user_data(user_id: str) -> UserData:
    profile, settings, posts = await asyncio.gather(
        fetch_profile(user_id),
        fetch_settings(user_id),
        fetch_posts(user_id)
    )
    return UserData(profile=profile, settings=settings, posts=posts)

Error Handling

from fastapi import HTTPException

@app.get("/users/{user_id}")
async def get_user(user_id: str) -> User:
    user = await db.get(User, user_id)

    if not user:
        raise HTTPException(
            status_code=404,
            detail="User not found"
        )

    return user

Security Best Practices

  • Use environment variables for secrets
  • Implement OAuth2 with JWT
  • Apply rate limiting
  • Validate all input with Pydantic
  • Use parameterized queries
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    user = await verify_token(token)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return user

## Best Practices

1. **Project-Specific**: Tailor rules to your exact tech stack
2. **Clear Examples**: Include both good and bad code examples
3. **Security First**: Always include security best practices
4. **Performance**: Add performance optimization guidelines
5. **Accessibility**: Include WCAG guidelines for frontend projects
6. **Testing**: Specify testing requirements and patterns
7. **Git Conventions**: Define commit message standards
8. **AI Instructions**: Guide AI on how to generate and review code

Source citations

Add this badge to your README

Show that /cursor-rules - Cursor Rules Generator for Claude Code is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/commands/cursor-rules.svg)](https://heyclau.de/entry/commands/cursor-rules)

How it compares

/cursor-rules - Cursor Rules Generator for Claude Code side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

Generate .cursorrules files for AI-native development with project-specific patterns, coding standards, and intelligent context awareness

Open dossier

Use the built-in /hooks menu to inspect Claude Code hooks and configure them in settings.json so shell commands run deterministically at lifecycle events like PreToolUse, PostToolUse, and Stop.

Open dossier

Use the built-in /context command to inspect Claude Code's context-window usage, plus a custom .claude/commands recipe for repeatable codebase-context analysis before refactors.

Open dossier

Claude Code slash command that generates a new .claude/commands/*.md file from a template, with optional arguments, frontmatter, and team-sharing support.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
BrandCursor logoCursor
Categorycommandscommandscommandscommands
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-10-162025-10-252025-10-252025-10-25
Platforms
Claude CodeCursor
Claude Code
Claude Code
Claude Code
Source repo
Safety notesReview generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project. Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.Hooks execute shell commands automatically with your user permissions whenever their event fires. A misconfigured or malicious hook can run destructive commands (file deletion, network calls, credential access) without further confirmation. PreToolUse hooks can allow or deny tool calls and PostToolUse hooks run after tools succeed; review hook commands before committing them to a shared .claude/settings.json so teammates do not inherit unexpected execution. Prefer `.claude/settings.json` for reviewed, team-shared hooks and `.claude/settings.local.json` for personal, gitignored hooks; use `disableAllHooks` to turn off user/project hooks when running untrusted code.The custom /analyze-context command makes Claude read files across your repository; scope it with a path argument to limit how much is pulled into context. Analysis output reflects Claude's reading of the code in that session, not a deterministic static-analysis tool — verify any load-bearing metrics or recommendations against the actual source.Creates .md files in .claude/commands/ in the current project directory; review generated content before committing.
Privacy notesPrompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution. Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.Command and HTTP hooks receive event JSON on stdin including `session_id`, `transcript_path`, `cwd`, and tool input (such as file paths and Bash commands); a hook that forwards this data over the network can expose local file contents, paths, or command arguments to third parties. HTTP hooks can include headers with interpolated environment variables (restricted by `allowedEnvVars`); avoid embedding secrets in hook configuration that is committed to a repository.Both /context and a custom analysis command operate on whatever files and project memory are loaded in the session; no data leaves your machine beyond the normal Claude Code model request, but file contents you ask Claude to read become part of the conversation context sent to the model.Creates .md files in your local .claude/commands/ directory; no content is sent externally.
Prerequisites— none listed— none listed— none listed— none listed
Install
/cursor-rules [options] <project_type>
/slash-command-gen [command-name] [options]
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.