nextjs-react-typescript-cursorrules-prompt-file — правило для Cursor
Правило для Cursor, которое задаёт агенту стиль кода в проектах на Next.js 14 App Router, React и TypeScript.
.cursor/rules/nextjs-react-typescript-cursorrules-prompt-file.mdcЧто делает nextjs-react-typescript-cursorrules-prompt-file
Файл описывает, как агент должен писать код: функциональные компоненты, декларативный JSX, интерфейсы вместо типов, именованные экспорты и паттерн RORO. Отдельный блок про обработку ошибок — ранние возвраты, guard clauses, happy path в конце функции. Ещё один — про React и Next.js: минимум use client и useEffect, ставка на серверные компоненты, Zod для валидации форм, next-safe-action для серверных действий с типом ActionResponse.
Внутри также перечислены соглашения по проекту: опираться на App Router для смены состояния, следить за Web Vitals, использовать Shadcn UI, Radix и Tailwind Aria для компонентов и стилей, а изображения отдавать в WebP с ленивой загрузкой. Директории именуются строчными буквами через дефис, статический контент и интерфейсы лежат в конце файла.
Правило объявлено с alwaysApply: false и globs **/*, то есть по умолчанию оно не подключается ко всем файлам — это повод проверить, как именно ваш Cursor подхватывает .mdc-файлы, иначе агент просто не увидит инструкции. В шапке правила заявлен и Solidity с Viem и Wagmi, так что для чистого фронтенда часть контекста лишняя.
Какие задачи решает
- задать агенту единый стиль кода в проекте на Next.js
- перевести компоненты на серверные и убрать лишний
use client - сделать серверные действия типобезопасными через
next-safe-action - выстроить обработку ошибок с ранними возвратами вместо вложенных условий
- описать структуру файлов и папок так, чтобы агент её не ломал
Примеры запросов агенту
- Сгенерируй компонент формы по правилам проекта, с валидацией через Zod и
useActionState - Перепиши этот компонент на серверный,
use clientоставь только там, где нужен доступ к Web API - Добавь серверное действие через
next-safe-action, чтобы возвращался типActionResponse
Как установить nextjs-react-typescript-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/nextjs-react-typescript-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/nextjs-react-typescript-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/nextjs-react-typescript-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/nextjs-react-typescript-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/nextjs-react-typescript-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Из того же набора68
Похожие
Рядом в теме «Фронтенд и UI»
Все правила IDE по теме «Фронтенд и UI» →Вопросы о nextjs-react-typescript-cursorrules-prompt-file
Как установить nextjs-react-typescript-cursorrules-prompt-file в Cursor?
Создайте файл .cursor/rules/nextjs-react-typescript-cursorrules-prompt-file.mdc и вставьте в него содержимое правила.
Что делает это правило?
Задаёт агенту Cursor стиль кода для Next.js 14 App Router, React и TypeScript: функциональные компоненты, интерфейсы вместо типов, ранние возвраты при обработке ошибок, минимум use client.
Правило применяется ко всем файлам автоматически?
В шапке стоит alwaysApply: false при globs **/*, поэтому подключение зависит от того, как Cursor обрабатывает .mdc-файлы в вашем проекте.
Исходный текст
nextjs-react-typescript-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Next.js development with React and TypeScript integration."
globs: **/*
alwaysApply: false
---
You are an expert in Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, and Tailwind Aria.
Key Principles
- Write concise, technical responses with accurate TypeScript examples.
- Use functional, declarative programming. Avoid classes.
- Prefer iteration and modularization over duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading).
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.
- Use the Receive an Object, Return an Object (RORO) pattern.
JavaScript/TypeScript
- Use "function" keyword for pure functions. Omit semicolons.
- Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use maps.
- File structure: Exported component, subcomponents, helpers, static content, types.
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).
Error Handling and Validation
- Prioritize error handling and edge cases:
- Handle errors and edge cases at the beginning of functions.
- Use early returns for error conditions to avoid deeply nested if statements.
- Place the happy path last in the function for improved readability.
- Avoid unnecessary else statements; use if-return pattern instead.
- Use guard clauses to handle preconditions and invalid states early.
- Implement proper error logging and user-friendly error messages.
- Consider using custom error types or error factories for consistent error handling.
React/Next.js
- Use functional components and TypeScript interfaces.
- Use declarative JSX.
- Use function, not const, for components.
- Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
- Implement responsive design with Tailwind CSS.
- Use mobile-first approach for responsive design.
- Place static content and interfaces at file end.
- Use content variables for static content outside render functions.
- Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
- Use Zod for form validation.
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: WebP format, size data, lazy loading.
- Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
- Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
- Use useActionState with react-hook-form for form validation.
- Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
- Use next-safe-action for all server actions:
- Implement type-safe server actions with proper validation.
- Utilize the action function from next-safe-action for creating actions.
- Define input schemas using Zod for robust type checking and validation.
- Handle errors gracefully and return appropriate responses.
- Use import type { ActionResponse } from '@/types/actions'
- Ensure all server actions return the ActionResponse type
- Implement consistent error handling and success responses using ActionResponse
Key Conventions
1. Rely on Next.js App Router for state changes.
2. Prioritize Web Vitals (LCP, CLS, FID).
3. Minimize 'use client' usage:
- Prefer server components and Next.js SSR features.
- Use 'use client' only for Web API access in small components.
- Avoid using 'use client' for data fetching or state management.
Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
- https://nextjs.org/docs
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules