nextjs-vercel-typescript-cursorrules-prompt-file — правило
Правило для Cursor, которое задаёт стиль кода и структуру проекта на Next.js с TypeScript, Vercel middleware и KV-базой.
.cursor/rules/nextjs-vercel-typescript-cursorrules-prompt-file.mdcЧто делает nextjs-vercel-typescript-cursorrules-prompt-file
Файл описывает, как агент должен писать код в проекте: TypeScript везде, интерфейсы вместо типов, функциональные компоненты, отказ от классов и enum в пользу map. Файлы раскладываются по схеме «экспортируемый компонент, подкомпоненты, хелперы, статика, типы», директории именуются строчными буквами через дефис, компоненты — именованными экспортами.
Отдельный блок посвящён производительности и клиентскому коду. Правило просит минимизировать use client, useEffect и setState, оборачивать клиентские компоненты в Suspense с fallback и подгружать некритичные части динамически. Для состояния в URL предлагается nuqs, для картинок — WebP с указанием размеров и ленивой загрузкой.
Есть раздел про ai-sdk-rsc: установка библиотеки, middleware в middleware.ts для сессий через @vercel/kv, хуки для стриминга генеративного контента. Учтите, что для этого нужен доступ к Vercel KV и переменные окружения с ключами и учётными данными базы — их правило советует держать в настройках окружения Vercel, а не в репозитории.
Какие задачи решает
- задать единый стиль TypeScript-кода для агента в проекте на Next.js
- разложить файлы компонента по фиксированной структуре
- сократить число клиентских компонентов и перенести логику на сервер
- настроить middleware с сессиями через Vercel KV
- подключить стриминг ответов модели через
ai-sdk-rsc
Примеры запросов агенту
- Создай компонент чата в
components/chatпо правилам проекта - Отрефактори этот компонент: убери
use client, перенеси выборку данных на сервер - Настрой
middleware/ai-middleware.tsс сессией в Vercel KV
Как установить nextjs-vercel-typescript-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/nextjs-vercel-typescript-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/nextjs-vercel-typescript-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/nextjs-vercel-typescript-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/nextjs-vercel-typescript-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/nextjs-vercel-typescript-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о nextjs-vercel-typescript-cursorrules-prompt-file
Как установить nextjs-vercel-typescript-cursorrules-prompt-file в Cursor?
Скопируйте файл правил в .cursor/rules/nextjs-vercel-typescript-cursorrules-prompt-file.mdc. Cursor подхватит его из этой папки.
Что делает это правило?
Задаёт агенту набор соглашений по Next.js App Router, TypeScript, Tailwind, Shadcn UI и Radix UI, а также инструкции по ai-sdk-rsc, Vercel middleware и KV-базе.
Что нужно для работы с ai-sdk-rsc по этому правилу?
Библиотека ставится через npm install ai-sdk-rsc или yarn add ai-sdk-rsc, а ключи и учётные данные базы правило советует хранить в переменных окружения Vercel.
Исходный текст
nextjs-vercel-typescript-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Next.js development with Vercel and TypeScript integration."
globs: **/*
alwaysApply: false
---
To extend the provided rules to include usage of the `ai-sdk-rsc` library and integrate it with Vercel middleware and a KV database, here's an updated set of instructions tailored for use with Cursor IDE. These instructions are designed to help you effectively implement generative user interfaces using React Server Components (RSC) with the AI SDK.
### Extended Rules for AI SDK RSC Integration with Vercel Middleware and KV Database
**Environment and Tools**
- You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, Tailwind, and Vercel middleware.
- You are familiar with Vercel's KV database for managing stateful data.
**Code Style and Structure**
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Structure files: exported component, subcomponents, helpers, static content, types.
**Naming Conventions**
- Use lowercase with dashes for directories (e.g., `components/auth-wizard`).
- Favor named exports for components.
**TypeScript Usage**
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.
**Syntax and Formatting**
- Use the `function` keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.
**UI and Styling**
- Use Shadcn UI, Radix UI, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.
**Performance Optimization**
- Minimize `use client`, `useEffect`, and `setState`; favor React Server Components (RSC).
- Wrap client components in `Suspense` with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.
**Key Conventions**
- Use `nuqs` for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit `use client`:
- Favor server components and Next.js SSR.
- Use only for Web API access in small components.
- Avoid for data fetching or state management.
- Follow Next.js docs for Data Fetching, Rendering, and Routing.
**AI SDK RSC Integration**
- **Setup and Installation**: Integrate `ai-sdk-rsc` into your Next.js project.
- Install the library using `npm install ai-sdk-rsc` or `yarn add ai-sdk-rsc`.
- Configure middleware in `middleware.ts` to manage requests and sessions using Vercel's KV database.
- **Middleware Implementation**: Use Vercel middleware to handle incoming requests.
- Create a middleware file in the `middleware` directory (e.g., `middleware/ai-middleware.ts`).
- Use middleware to parse user input and manage sessions with the KV database.
- Example:
```typescript
import { NextRequest, NextResponse } from 'next/server';
import { kv } from '@vercel/kv';
export async function middleware(req: NextRequest) {
const sessionId = req.cookies.get('session-id');
if (!sessionId) {
const newSessionId = generateSessionId();
await kv.set(newSessionId, { state: {} }); // Initialize state in KV database
const res = NextResponse.next();
res.cookies.set('session-id', newSessionId);
return res;
}
// Fetch state from KV database
const state = await kv.get(sessionId);
req.nextUrl.searchParams.set('state', JSON.stringify(state));
return NextResponse.next();
}
function generateSessionId() {
return Math.random().toString(36).substring(2);
}
```
- **React Server Components (RSC) and AI SDK**:
- Use `ai-sdk-rsc` hooks to manage state and stream generative content.
- Example usage of AI SDK hooks in a React Server Component:
```typescript
import { useAIStream } from 'ai-sdk-rsc';
import { FC } from 'react';
interface ChatProps {
initialMessage: string;
}
const Chat: FC = ({ initialMessage }) => {
const { messages, sendMessage } = useAIStream({
initialMessage,
onMessage: (message) => console.log('New message:', message),
});
return (
{msg.content}
);
export default Chat;
```
- **KV Database Integration**:
- Use Vercel's KV database to store and retrieve session data.
- Utilize `kv.set`, `kv.get`, and `kv.delete` to manage data.
- Ensure the database operations are asynchronous to avoid blocking server-side rendering (SSR).
- **Data Fetching and State Management**:
- Use Next.js data fetching methods (`getServerSideProps`, `getStaticProps`) to manage server-side state.
- Avoid client-side data fetching methods (`useEffect`, `fetch`) except for critical, non-blocking operations.
- **Deployment Considerations**:
- Ensure all environment variables (e.g., API keys, database credentials) are securely stored in Vercel's environment settings.
- Configure Vercel's KV and other serverless functions correctly to handle scalability and performance needs.
By following these extended rules, you'll be able to create a well-optimized, scalable, and efficient Next.js application that leverages `ai-sdk-rsc`, Vercel middleware, and KV database for building sophisticated AI-driven interfaces.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules