react-typescript-nextjs-nodejs-cursorrules-prompt- — правило
Правило для Cursor задаёт стиль кода на React, TypeScript, Next.js 14 и Node.js: функциональные компоненты, RORO, минимум use client.
.cursor/rules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdcЧто делает react-typescript-nextjs-nodejs-cursorrules-prompt-
Это файл правил, который Cursor подхватывает и применяет к генерации кода. Внутри — набор соглашений: писать на TypeScript, использовать function вместо const для компонентов, обходиться без классов и enum, применять именованные экспорты и паттерн RORO (принимаем объект, возвращаем объект). Директории именуются строчными буквами через дефис, например components/auth-wizard.
Отдельный блок посвящён обработке ошибок: проверки и граничные случаи — в начале функции, дальше ранние возвраты, счастливый путь идёт последним. Ожидаемые ошибки в Server Actions предлагается моделировать как возвращаемые значения через useActionState, а не через try/catch, неожиданные — ловить error boundaries в error.tsx и global-error.tsx. Для серверных экшенов правило советует next-safe-action со схемами Zod и общим типом ActionResponse.
По фронтенду: компоненты и стили из Shadcn UI, Radix и Tailwind Aria, адаптив по mobile-first, изображения в WebP с ленивой загрузкой. Правило прямо просит минимизировать use client, useEffect и setState в пользу серверных компонентов. Учтите: в тексте правила заявлен стек с Solidity, Viem v2 и Wagmi v2 — если вы делаете обычное веб-приложение без блокчейна, эти установки будут лишними, и правило лучше подрезать под себя. Применяется не всегда: в метаданных стоит alwaysApply: false, а globs задан как **/*.
Какие задачи решает
- задать единый стиль кода на React и TypeScript для всей команды
- убрать лишние
use clientи перевести логику на серверные компоненты - выстроить обработку ошибок в Server Actions без вложенных try/catch
- подключить типизированные экшены через
next-safe-actionи Zod - договориться об именовании файлов и структуре компонентов
Примеры запросов агенту
- Создай компонент формы логина по правилам проекта: серверный компонент, Zod для валидации, именованный экспорт
- Перепиши этот Server Action на
next-safe-actionс типомActionResponseи ранними возвратами - Проверь компонент на лишние
use clientиuseEffectи предложи, что вынести в RSC
Как установить react-typescript-nextjs-nodejs-cursorrules-prompt-
Вручную: положить файлы
.cursor/rules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/react-typescript-nextjs-nodejs-cursorrules-prompt-.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdВручную: положить файлы
.clinerules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о react-typescript-nextjs-nodejs-cursorrules-prompt-
Как установить react-typescript-nextjs-nodejs-cursorrules-prompt- в Cursor?
Положите файл по пути .cursor/rules/react-typescript-nextjs-nodejs-cursorrules-prompt-.mdc в корне проекта. Cursor подхватит его как правило.
Что делает это правило?
Описывает соглашения для кода на React, TypeScript, Next.js 14 App Router и Node.js: функциональный стиль, RORO, ранние возвраты при ошибках, минимум клиентских компонентов, Shadcn UI и Tailwind Aria для вёрстки.
Правило применяется ко всем файлам автоматически?
Нет. В метаданных указано alwaysApply: false, а globs стоит **/* — то есть область широкая, но автоприменение выключено.
Исходный текст
react-typescript-nextjs-nodejs-cursorrules-prompt-.mdc · CC0-1.0
---
description: "Cursor rules for React development with TypeScript, Next.js, and Node.js 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()).
- 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.
Dependencies:
- Next.js 14 App Router
- Wagmi v2
- Viem v2
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
- Example:
```typescript
'use server'
import { createSafeActionClient } from 'next-safe-action'
import { z } from 'zod'
import type { ActionResponse } from '@/app/actions/actions'
const schema = z.object({
value: z.string()
})
export const someAction = createSafeActionClient()
.schema(schema)
.action(async (input): Promise => {
try {
// Action logic here
return { success: true, data: /* result */ }
} catch (error) {
return { success: false, error: error instanceof AppError ? error : appErrors.UNEXPECTED_ERROR, }
}
})
```
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.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules