ТОП 100 лучших Rules для Cursor AI 2026 для новичков
Полный гайд по настройке Cursor AI Rules для максимальной продуктивности. 100 проверенных правил с объяснениями: от базовых до продвинутых. Научитесь писать код быстрее с правильными инструкциями для AI.
ТОП 100 лучших Rules для Cursor AI 2026
Cursor AI Rules — это инструкции, которые направляют поведение AI-ассистента в вашем проекте. Правильно настроенные правила превращают Cursor из умного помощника в идеального напарника, который понимает ваш стек, стиль кода и требования проекта.
Что такое Cursor Rules и зачем они нужны?
Cursor Rules — это файл .cursorrules или настройки в Settings > Rules, которые определяют:
- Какой стиль кода использовать
- Какие технологии предпочитать
- Как структурировать ответы
- Какие паттерны применять
Без правил AI генерирует generic-код. С правилами — код, идеально подходящий под ваш проект.
Как добавить Rules в Cursor?
Способ 1: Файл .cursorrules
Создайте файл .cursorrules в корне проекта:
my-project/
├── .cursorrules ← ваши правила здесь
├── src/
└── package.jsonСпособ 2: Настройки Cursor
Settings > Rules > New User Rule
БАЗОВЫЕ ПРАВИЛА (1-20)
Фундамент для любого проекта
1. Определите язык общения
Always respond in Russian.
Все объяснения и комментарии пиши на русском языке.Почему важно: AI по умолчанию отвечает на английском. Это правило экономит время на переключение контекста.
2. Укажите основной стек технологий
Tech stack:
- Frontend: React 18 + TypeScript
- Styling: Tailwind CSS
- Backend: Node.js + Express
- Database: PostgreSQLПочему важно: AI будет предлагать решения именно для вашего стека, а не generic-варианты.
3. Запретите устаревшие паттерны
NEVER use:
- Class components in React (use functional components with hooks)
- var keyword (use const/let)
- CommonJS imports (use ES modules)
- Callbacks (use async/await)Почему важно: Предотвращает генерацию legacy-кода.
4. Установите стиль кода
Code style:
- Use 2 spaces for indentation
- Use single quotes for strings
- Always use semicolons
- Maximum line length: 100 charactersПочему важно: Консистентный код легче читать и поддерживать.
5. Определите структуру проекта
Project structure:
src/
components/ - React components
hooks/ - Custom hooks
utils/ - Utility functions
types/ - TypeScript types
pages/ - Page components
api/ - API callsПочему важно: AI будет создавать файлы в правильных директориях.
6. Запретите комментарии (если не нужны)
DO NOT add comments to code unless explicitly asked.
Code should be self-documenting through clear naming.Почему важно: Избавляет от бесполезных комментариев типа "// increment counter".
7. Требуйте TypeScript типизацию
Always use TypeScript with strict typing.
- Define interfaces for all props
- Define types for function parameters and returns
- Never use 'any' type
- Use generics where appropriateПочему важно: Строгая типизация предотвращает баги.
8. Установите правила именования
Naming conventions:
- Components: PascalCase (UserProfile.tsx)
- Functions: camelCase (getUserData)
- Constants: UPPER_SNAKE_CASE (MAX_RETRY_COUNT)
- Types/Interfaces: PascalCase with prefix (IUser, TResponse)
- Files: kebab-case or match export nameПочему важно: Единообразное именование улучшает навигацию по коду.
9. Определите формат ответов
When explaining code:
- Be concise, not verbose
- Show code first, explain after
- Use bullet points for lists
- Highlight key concepts in boldПочему важно: Экономит время на чтение длинных объяснений.
10. Укажите предпочтительные библиотеки
Preferred libraries:
- HTTP: fetch (native) or axios
- State: React Query for server state, Zustand for client
- Forms: React Hook Form
- Validation: Zod
- Testing: Vitest + Testing LibraryПочему важно: AI не будет предлагать альтернативы, которые вы не используете.
11. Требуйте обработку ошибок
Always include error handling:
- Wrap async operations in try/catch
- Provide meaningful error messages
- Log errors appropriately
- Never swallow errors silentlyПочему важно: Код без обработки ошибок — бомба замедленного действия.
12. Установите правила для React компонентов
React component rules:
- One component per file
- Props interface at the top
- Hooks at the beginning of component
- Early returns for loading/error states
- Destructure props in parametersПочему важно: Единообразная структура компонентов.
13. Запретите magic numbers
Never use magic numbers. Define constants:
❌ if (items.length > 10)
✅ const MAX_VISIBLE_ITEMS = 10;
if (items.length > MAX_VISIBLE_ITEMS)Почему важно: Код становится самодокументируемым.
14. Требуйте безопасный код
Security requirements:
- Never expose API keys in frontend code
- Always sanitize user input
- Use parameterized queries for SQL
- Validate data on both client and serverПочему важно: Безопасность — не опция, а требование.
15. Определите стиль экспортов
Export rules:
- Use named exports (not default) for better refactoring
- Export types separately from implementations
- Group related exports in index filesПочему важно: Named exports улучшают автоимпорт и рефакторинг.
16. Установите правила для API
API patterns:
- Use REST conventions (GET, POST, PUT, DELETE)
- Return consistent response format: { data, error, message }
- Use proper HTTP status codes
- Version your API (/api/v1/...)Почему важно: Консистентный API легче поддерживать.
17. Требуйте accessibility
Accessibility requirements:
- All images must have alt text
- Buttons must have aria-labels if icon-only
- Forms must have proper labels
- Use semantic HTML elementsПочему важно: Доступность — это не роскошь, а стандарт.
18. Определите правила для тестов
Testing rules:
- Name tests descriptively: "should return user when ID is valid"
- Use AAA pattern: Arrange, Act, Assert
- Mock external dependencies
- Test behavior, not implementationПочему важно: Хорошие тесты — залог стабильности.
19. Запретите вложенные тернарники
Never use nested ternary operators.
❌ condition1 ? (condition2 ? a : b) : c
✅ Use if/else or separate variablesПочему важно: Вложенные тернарники нечитаемы.
20. Требуйте immutability
Prefer immutable operations:
- Use spread operator for updates
- Use map/filter/reduce instead of forEach with mutations
- Never mutate function parametersПочему важно: Иммутабельность предотвращает side effects.
ПРОДВИНУТЫЕ ПРАВИЛА (21-50)
Для опытных разработчиков
21. Настройте Code Review режим
When reviewing code:
- Point out potential bugs
- Suggest performance improvements
- Check for security vulnerabilities
- Verify TypeScript types are correct
- Rate code quality 1-10 with explanationПочему важно: AI становится вашим code reviewer.
22. Определите правила рефакторинга
When refactoring:
- Preserve existing behavior exactly
- Extract only when there's clear reuse
- Keep functions under 30 lines
- Keep files under 300 linesПочему важно: Предотвращает over-engineering.
23. Установите правила для хуков
Custom hooks rules:
- Name must start with "use"
- Return object for multiple values: { data, loading, error }
- Handle cleanup in useEffect
- Document dependencies clearlyПочему важно: Консистентные хуки легче использовать.
24. Определите архитектурные границы
Architecture rules:
- Components should not contain business logic
- Business logic lives in hooks or services
- API calls only in api/ directory
- No direct database calls from frontendПочему важно: Разделение ответственности = чистый код.
25. Настройте генерацию типов
Type generation rules:
- Infer types from Zod schemas when possible
- Generate API types from OpenAPI spec
- Use 'as const' for literal types
- Prefer interfaces for objects, types for unionsПочему важно: DRY принцип для типов.
26. Требуйте оптимизацию производительности
Performance rules:
- Use React.memo only when measured need
- Memoize expensive calculations with useMemo
- Memoize callbacks passed to children with useCallback
- Avoid inline objects/arrays in JSXПочему важно: Преждевременная оптимизация — зло, но осознанная — благо.
27. Установите правила для состояния
State management rules:
- Local state: useState for UI state
- Server state: React Query with caching
- Global state: Zustand for shared client state
- Form state: React Hook Form
- URL state: useSearchParamsПочему важно: Правильный инструмент для каждого типа состояния.
28. Определите правила для git
When suggesting git commands:
- Use conventional commits: feat:, fix:, refactor:
- Keep commits atomic and focused
- Write descriptive commit messages
- Never force push to mainПочему важно: Чистая git история = легкий debugging.
29. Настройте обработку форм
Form handling rules:
- Use React Hook Form for all forms
- Validate with Zod schemas
- Show errors inline, near inputs
- Disable submit while loading
- Show loading state on buttonПочему важно: Консистентный UX для форм.
30. Требуйте graceful degradation
Error handling UX:
- Show user-friendly error messages
- Provide retry buttons for failed requests
- Use error boundaries for component crashes
- Log technical details to console/serviceПочему важно: Пользователь не должен видеть технические ошибки.
31. Определите правила для CSS
CSS/Styling rules:
- Use Tailwind utility classes
- Extract repeated patterns to components
- Use CSS variables for theming
- Mobile-first responsive design
- Never use !importantПочему важно: Консистентный стиль = меньше CSS багов.
32. Настройте lazy loading
Lazy loading rules:
- Use React.lazy for route-level code splitting
- Lazy load heavy components (charts, editors)
- Preload on hover for critical paths
- Show skeleton loaders while loadingПочему важно: Быстрая начальная загрузка = лучший UX.
33. Требуйте input validation
Input validation rules:
- Validate on blur, not on change (less noise)
- Validate on submit as well
- Show validation errors clearly
- Use Zod for schema validation
- Sanitize before savingПочему важно: Валидация — первая линия защиты.
34. Определите правила для даты/времени
Date/time handling:
- Store in UTC in database
- Display in user's timezone
- Use Intl.DateTimeFormat for formatting
- Use date-fns for manipulations
- Never parse dates manuallyПочему важно: Даты — источник бесконечных багов.
35. Настройте обработку изображений
Image handling rules:
- Always specify width and height
- Use next/image or similar for optimization
- Provide alt text for accessibility
- Use lazy loading for below-fold images
- Support WebP with fallbacksПочему важно: Изображения — главный враг производительности.
36. Требуйте env переменные
Environment variables:
- Never hardcode secrets
- Use .env.example for documentation
- Prefix client vars with VITE_ or NEXT_PUBLIC_
- Validate env at startupПочему важно: Безопасность и гибкость конфигурации.
37. Определите правила для локализации
i18n rules:
- Never hardcode user-facing strings
- Use translation keys: t('user.greeting')
- Support RTL layouts
- Format numbers/dates per localeПочему важно: Готовность к масштабированию.
38. Настройте логирование
Logging rules:
- Use structured logging: { level, message, context }
- Log important business events
- Include correlation IDs for tracing
- Never log sensitive data (passwords, tokens)Почему важно: Логи — ваши глаза в production.
39. Требуйте чистые функции
Prefer pure functions:
- Same input = same output
- No side effects
- No external state modification
- Easy to testПочему важно: Чистые функции = предсказуемый код.
40. Определите правила для API ошибок
API error handling:
- Use consistent error format: { code, message, details }
- Map HTTP codes to error types
- Retry transient failures with backoff
- Show specific messages for known errorsПочему важно: Хорошая обработка ошибок = профессиональный продукт.
41. Настройте кэширование
Caching rules:
- Use React Query for API response caching
- Set appropriate stale times
- Invalidate cache on mutations
- Use optimistic updates for better UXПочему важно: Кэширование улучшает UX и снижает нагрузку.
42. Требуйте документацию для публичных API
Documentation rules:
- JSDoc for exported functions
- README for each package/module
- Storybook for UI components
- OpenAPI spec for REST APIsПочему важно: Код без документации — legacy с первого дня.
43. Определите правила для анимаций
Animation rules:
- Use CSS transitions for simple animations
- Use Framer Motion for complex animations
- Respect prefers-reduced-motion
- Keep animations under 300msПочему важно: Анимации улучшают UX, но могут раздражать.
44. Настройте обработку файлов
File handling rules:
- Validate file type on client and server
- Limit file sizes
- Show upload progress
- Handle errors gracefullyПочему важно: Загрузка файлов — частый источник проблем.
45. Требуйте rate limiting awareness
Rate limiting:
- Implement client-side throttling
- Show clear messages when rate limited
- Use exponential backoff for retries
- Cache aggressively to reduce callsПочему важно: Уважение к API лимитам.
46. Определите правила для WebSocket
WebSocket rules:
- Implement reconnection logic
- Handle connection states in UI
- Use heartbeat for connection health
- Queue messages during disconnectionПочему важно: Real-time требует надежной обработки.
47. Настройте SEO
SEO rules:
- Every page needs unique title and description
- Use semantic HTML structure
- Implement proper meta tags
- Generate sitemap automaticallyПочему важно: SEO начинается с кода.
48. Требуйте feature flags
Feature flags:
- Use for gradual rollouts
- Clean up old flags regularly
- Document flag purpose
- Default to safe/off stateПочему важно: Безопасный деплой новых фич.
49. Определите правила для модальных окон
Modal rules:
- Trap focus inside modal
- Close on Escape key
- Close on backdrop click
- Prevent body scroll when open
- Return focus on closeПочему важно: Модальные окна требуют правильной accessibility.
50. Настройте обработку навигации
Navigation rules:
- Show loading state during navigation
- Preserve scroll position on back
- Confirm before leaving unsaved changes
- Use proper link elements for SEOПочему важно: Навигация — основа UX.
СПЕЦИАЛИЗИРОВАННЫЕ ПРАВИЛА (51-80)
Для конкретных задач
51. Правила для React Query
React Query setup:
- Configure staleTime based on data freshness needs
- Use queryKey consistently
- Implement error boundaries for query errors
- Use select for data transformation52. Правила для Tailwind CSS
Tailwind rules:
- Use @apply only for repeated patterns
- Configure theme in tailwind.config
- Use arbitrary values sparingly [calc(100%-2rem)]
- Prefer design tokens over arbitrary values53. Правила для форм с React Hook Form
React Hook Form rules:
- Use register for simple inputs
- Use Controller for complex components
- Use FormProvider for nested forms
- Validate with resolver and Zod54. Правила для Zustand
Zustand rules:
- One store per domain
- Keep stores flat
- Use selectors to prevent rerenders
- Use persist middleware for localStorage55. Правила для Next.js
Next.js rules:
- Use App Router (not Pages)
- Prefer Server Components
- Use 'use client' only when needed
- Implement proper loading and error files56. Правила для Prisma
Prisma rules:
- Use transactions for related operations
- Select only needed fields
- Use includes sparingly (N+1 queries)
- Generate types after schema changes57. Правила для тестирования с Vitest
Vitest rules:
- Use describe blocks for grouping
- Use it for individual tests
- Mock modules at test file level
- Clean up after each test58. Правила для Testing Library
Testing Library rules:
- Query by role first (getByRole)
- Use user-event over fireEvent
- Wait for async operations properly
- Test what user sees, not implementation59. Правила для Storybook
Storybook rules:
- Create story for each component variant
- Document props with argTypes
- Include responsive previews
- Add interaction tests60. Правила для Docker
Docker rules:
- Use multi-stage builds
- Don't run as root
- Use .dockerignore
- Pin base image versions61. Правила для CI/CD
CI/CD rules:
- Run tests before build
- Cache dependencies
- Fail fast on errors
- Deploy only green builds62. Правила для PostgreSQL
PostgreSQL rules:
- Use UUID for primary keys
- Add indexes for frequently queried columns
- Use constraints for data integrity
- Implement soft deletes with deleted_at63. Правила для REST API дизайна
REST API design:
- Use nouns for resources: /users, /posts
- Use HTTP methods for actions
- Filter via query params: /users?role=admin
- Paginate lists: ?page=1&limit=2064. Правила для GraphQL
GraphQL rules:
- Use fragments for reusable fields
- Implement DataLoader for N+1
- Validate input with custom scalars
- Use persisted queries in production65. Правила для WebSocket с Socket.io
Socket.io rules:
- Namespace for different features
- Rooms for group communication
- Acknowledgments for critical messages
- Middleware for authentication66. Правила для аутентификации
Authentication rules:
- Use HttpOnly cookies for tokens
- Implement refresh token rotation
- Hash passwords with bcrypt
- Rate limit login attempts67. Правила для авторизации
Authorization rules:
- Check permissions server-side
- Use RBAC or ABAC consistently
- Hide UI for unauthorized actions
- Return 403 for permission denied68. Правила для файлового хранилища
File storage rules:
- Use presigned URLs for uploads
- Store files in cloud (S3, GCS)
- Generate thumbnails async
- Clean up orphaned files69. Правила для email
Email rules:
- Use templates for consistency
- Include plain text version
- Validate addresses before sending
- Implement unsubscribe properly70. Правила для поиска
Search implementation:
- Debounce search input (300ms)
- Show search suggestions
- Highlight matches in results
- Support keyboard navigation71. Правила для пагинации
Pagination rules:
- Use cursor-based for infinite scroll
- Use offset-based for page numbers
- Show total count when needed
- Handle empty states72. Правила для фильтрации
Filtering rules:
- Sync filters with URL params
- Reset pagination on filter change
- Show active filter count
- Allow clearing all filters73. Правила для сортировки
Sorting rules:
- Support multiple sort fields
- Show sort direction clearly
- Remember user preference
- Default to sensible order74. Правила для drag and drop
Drag and drop rules:
- Show clear drop targets
- Support keyboard alternatives
- Animate position changes
- Persist order changes immediately75. Правила для уведомлений
Notification rules:
- Stack multiple notifications
- Auto-dismiss after timeout
- Allow manual dismiss
- Support different severity levels76. Правила для dark mode
Dark mode rules:
- Use CSS variables for colors
- Respect system preference
- Allow manual toggle
- Persist preference77. Правила для responsive design
Responsive rules:
- Mobile-first breakpoints
- Test on real devices
- Use clamp() for fluid typography
- Hide non-essential on mobile78. Правила для PWA
PWA rules:
- Register service worker
- Implement offline fallback
- Show update available prompt
- Cache static assets79. Правила для analytics
Analytics rules:
- Track meaningful events only
- Respect Do Not Track
- Use data layer for GTM
- Test tracking in staging80. Правила для A/B тестов
A/B testing rules:
- Use feature flags
- Track conversion events
- Ensure statistical significance
- Clean up losing variantsПРАВИЛА ДЛЯ КОНКРЕТНЫХ СЦЕНАРИЕВ (81-100)
Решение типичных задач
81. Создание нового компонента
When creating a new component:
1. Create file in src/components/
2. Define TypeScript interface for props
3. Implement component with proper structure
4. Add to index barrel file if public82. Создание нового API endpoint
When creating API endpoint:
1. Define route in api/ directory
2. Create Zod schema for validation
3. Implement handler with error handling
4. Add to API documentation83. Добавление новой страницы
When adding a new page:
1. Create page component in pages/
2. Add route configuration
3. Implement SEO meta tags
4. Add to sitemap84. Исправление бага
When fixing a bug:
1. Reproduce the issue first
2. Write a failing test
3. Fix the minimal code
4. Verify test passes
5. Check for similar issues elsewhere85. Рефакторинг существующего кода
When refactoring:
1. Ensure tests exist and pass
2. Make small incremental changes
3. Run tests after each change
4. Never change behavior and structure together86. Оптимизация производительности
When optimizing:
1. Measure first with DevTools
2. Identify bottleneck
3. Fix one thing at a time
4. Measure again to verify87. Добавление валидации
When adding validation:
1. Create Zod schema
2. Apply on form submit
3. Show errors near inputs
4. Test edge cases88. Реализация infinite scroll
Infinite scroll implementation:
1. Use IntersectionObserver for trigger
2. Load next page when near bottom
3. Show loading indicator
4. Handle end of data gracefully89. Добавление поиска с автодополнением
Autocomplete search:
1. Debounce input changes
2. Show loading during fetch
3. Allow keyboard navigation
4. Close on outside click90. Создание модального окна
Modal implementation:
1. Use portal for rendering
2. Trap focus inside
3. Handle Escape key
4. Prevent body scroll91. Реализация таблицы с сортировкой
Sortable table:
1. Use semantic table HTML
2. Add sort buttons to headers
3. Show sort direction
4. Support multi-column sort92. Добавление drag-and-drop списка
DnD list:
1. Use @dnd-kit or react-beautiful-dnd
2. Show drag handle
3. Animate reorder
4. Persist new order93. Создание формы с несколькими шагами
Multi-step form:
1. Store state in parent
2. Validate each step
3. Allow going back
4. Show progress indicator94. Реализация real-time обновлений
Real-time updates:
1. Use WebSocket or SSE
2. Handle reconnection
3. Show connection status
4. Queue offline changes95. Добавление экспорта в CSV/PDF
Export implementation:
1. Format data on client or server
2. Show progress for large exports
3. Handle errors gracefully
4. Use proper file naming96. Создание dashboard с графиками
Dashboard charts:
1. Use Recharts or Chart.js
2. Responsive container
3. Loading skeletons
4. Proper accessibility97. Реализация системы тегов
Tagging system:
1. Allow creating new tags
2. Autocomplete existing
3. Support multiple selection
4. Visual tag display98. Добавление комментариев
Comments implementation:
1. Support threading/replies
2. Real-time updates
3. Edit and delete own
4. Proper moderation99. Создание системы уведомлений
Notification system:
1. In-app notifications
2. Mark as read
3. Batch similar notifications
4. Clear old notifications100. Реализация onboarding
Onboarding flow:
1. Highlight key features
2. Allow skip
3. Track completion
4. Don't show again after completeКак использовать эти правила
Шаг 1: Выберите релевантные правила
Не копируйте все 100 правил сразу. Выберите 10-20, которые подходят вашему проекту.
Шаг 2: Создайте .cursorrules файл
# My Project Rules
## Tech Stack
- React 18 + TypeScript
- Tailwind CSS
- Supabase
## Code Style
- 2 spaces indentation
- No comments unless asked
- Named exports only
## [Добавьте выбранные правила]Шаг 3: Итерируйте
Добавляйте правила по мере необходимости. Если AI часто делает что-то не так — добавьте правило.
Заключение
100 правил — это не догма, а отправная точка. Ваш идеальный набор будет уникальным.
Главные принципы:
- Будьте конкретны
- Запрещайте то, что не хотите видеть
- Требуйте то, что важно
- Обновляйте правила по мере развития проекта
Cursor AI с правильными Rules — это как опытный разработчик, который знает все ваши стандарты и никогда их не нарушает.
Понравилась статья? Поделитесь с коллегами и сохраните в закладки — это ваш справочник на каждый день!

