React 및 Next.js 프로젝트 개발 시 AI 코딩 에이전트의 공통 개발 규칙과 컨벤션으로 활용합니다.
# Universal Instructions for React / Next.js Projects
> Purpose: General rules for developing various projects with React + TypeScript, Next.js + TypeScript, and Tailwind CSS.
> Usage: Place this file in the root of a new project as `AGENTS.md`, `CLAUDE.md`, or `PROJECT_RULES.md`, or use it as a base instruction set for an AI agent.
> Important: These instructions do not contain product-specific rules. Keep everything related to an individual project in a separate `PROJECT_RULES.md` file.
---
# 1. Core Principle
Build a production-ready application, not a collection of disconnected components.
Always follow this sequence:
1. Review the current project structure, `package.json`, routing, UI primitives, stores, hooks, schemas, and project rules.
2. Find existing actions, helpers, schemas, and components that can be reused.
3. Identify the smallest change required for the task.
4. Preserve existing behavior.
5. Implement each new feature end to end: model, validation, UI, storage/import/export, edge cases, and verification.
6. Run the relevant checks and report the results honestly.
Do not add dependencies, abstractions, a global store, or an architectural layer unless they are genuinely necessary.
Use `shadcn/ui` by default for UI work. Do not add another UI kit on top of it without a clear reason.
---
# 2. Choosing Between React and Next.js
Use Next.js when the project needs:
- routing;
- SEO;
- SSR / Server Components;
- Server Actions;
- Route Handlers / API routes;
- authentication;
- database access;
- private environment variables;
- content publishing.
Use React + Vite when:
- the application is entirely client-side;
- SEO is not required;
- it is a local tool, dashboard, editor, admin panel, or desktop-like UI;
- the server already exists as a separate service.
Do not choose Next.js simply because it is popular. Do not add Redux, Zustand, React Query, a form library, or another UI kit without a specific reason.
---
# 3. Default Stack and Checks
Use the following by default:
- React;
- TypeScript in strict mode;
- Tailwind CSS;
- `shadcn/ui` as the required UI approach for clean design and rapid interface development;
- Lucide React or the icon library used by the current shadcn configuration;
- ESLint;
- a shared `cn()` helper;
- runtime validation for external data;
- accessible HTML elements.
Use `shadcn/ui` as the primary source of UI primitives: buttons, inputs, selects, dialogs, sheets, dropdowns, tooltips, tabs, carousels, cards, badges, skeletons, scroll areas, and other required components. Create custom primitives only when shadcn does not provide a suitable component or when the project already has a stable local primitive.
For an MVP, begin with mock/JSON/localStorage data and validate local user flows first. Add the backend, database, payments, authentication, and external integrations last, once the UI, models, and flows are clear.
At a minimum, run these commands after code changes:
```bash
npm run typecheck
npm run lint
npm run build
```
Do not claim that the project works if these commands were not run or completed with errors.
---
# 4. Architecture
For Next.js projects expected to grow, keep source code inside `src/` by default: `src/app`, `src/components`, `src/lib`, `src/data`, `src/hooks`, and `src/features`. Keep root-level support folders and files (`public`, configuration files, lockfiles, and README) in the project root.
For small projects, the following structure is acceptable:
```text
src/
app/ or pages/
components/
features/
lib/
shared/
```
For medium and large projects, use an FSD-like approach:
```text
src/
app/ # bootstrap, providers, layouts, routes
views/ # page-level composition
widgets/ # large UI blocks
features/ # user workflows
entities/ # domain model
shared/ # generic helpers, config, thin wrappers around shadcn/ui
```
Import direction:
```text
app/views -> widgets -> features -> entities -> shared
```
Do not:
- import `widgets` into `features`;
- place business logic in `shared`;
- turn `shared/lib` into a dumping ground for unrelated functions;
- duplicate mutation logic across multiple UI components;
- use deep imports into another module's internals when that module exposes a public API.
---
# 5. Public API
Every feature, entity, or shared UI folder should expose a clear public API through `index.ts` when the module is used externally. For shadcn primitives, the public API usually already lives in `components/ui/*` or the project's local UI layer.
Good:
```ts
import { createTask } from "@/features/create-task";
```
Bad:
```ts
import { createTask } from "@/features/create-task/model/createTask";
```
Exception: internal code within the same feature or entity.
---
# 6. TypeScript
Required:
- enable `strict: true`;
- do not use `any` except in isolated interoperability code;
- do not hide type errors with `as` assertions;
- use discriminated unions for complex state;
- validate runtime JSON with a schema;
- do not create multiple identical types without a meaningful reason.
Example state type:
```ts
type LoadState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; message: string };
```
---
# 7. React State and Effects
Store state where it actually belongs:
| State type | Where to store it |
| ------------ | ----------------------------------------------------------- |
| Local UI | `useState`, `useReducer` |
| URL state | route/search parameters |
| Server state | server rendering or a cache/query layer |
| Form state | form hook/library |
| Global UI | a small store when necessary |
| Domain state | entity/store when the state is shared across multiple flows |
Do not put the following in a global store:
- hover state;
- the state of a single dropdown;
- the draft value of a single input;
- the state of a single modal;
- the temporary selected tab of one component.
Use `useEffect` to synchronize with external systems:
- browser APIs;
- timers;
- subscriptions;
- external stores;
- DOM integrations.
Do not use `useEffect` for derived values.
Bad:
```tsx
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);
```
Good:
```tsx
const fullName = `${firstName} ${lastName}`;
```
---
# 8. Next.js Boundaries
In the App Router, components are Server Components by default.
Add `"use client"` only where you need:
- event handlers;
- local state;
- effects;
- `window`, `document`, or `localStorage`;
- drag and drop;
- `contenteditable`;
- client-only libraries.
Do not make an entire layout a Client Component without a clear need.
Server-only code includes:
- database access;
- authentication;
- private API clients;
- secret environment variables;
- webhooks;
- access checks.
Never import a server-only module into a Client Component.
---
# 9. Runtime Validation and Migrations
Validate all external data at the boundary:
- request bodies;
- form data;
- URL/search parameters;
- uploaded files;
- imported JSON;
- localStorage/IndexedDB data;
- responses from external APIs.
When adding a new model field, update the entire lifecycle:
1. TypeScript type.
2. Runtime schema.
3. Factory/default values.
4. Parser/migration for legacy data.
5. Normalization helpers.
6. Import/export.
7. Search/filter indexing, if the field should be searchable.
8. Undo/redo snapshots, if users can edit the field.
9. UI for creating, editing, and clearing the field.
10. Edge cases and checks.
Example:
```ts
return {
...item,
status: item.status ?? "active",
tags: normalizeTags(item.tags),
dueDate: normalizeDate(item.dueDate),
};
```
Do not add a model field only in the출처 · prompts.chat · Universal Instructions for React / Next.js Projects — 원문은 출처에 게시된 그대로이며, 권리는 원작자에게 있습니다.
Gemini로 실행한 결과입니다. 입력 항목에는 국내 환경의 예시값을 적용했습니다(AI 생성 — 사실 확인 필요).
# Universal Instructions for React / Next.js Projects > Purpose: General rules for developing various projects with React + TypeScript, Next.js + TypeScript, and Tailwind CSS. > Usage: Place this file in the root of a new project as `AGENTS.md`, `CLAUDE.md`, or `PROJECT_RULES.md`, or use it as a base instruction set for an AI agent. > Important: These instructions do not contain product-specific rules. Keep everything related to an individual project in a separate `PROJECT_RULES.md` file. --- # 1. Core Principle Build a production-ready application, not a collection of disconnected components. Always follow this sequence: 1. Review the current project structure, `package.json`, routing, UI primitives, stores, hooks, schemas, and project rules. 2. Find existing actions, helpers, schemas, and components that can be reused. 3. Identify the smallest change required for the task. 4. Preserve existing behavior. 5. Implement each new feature end to end: model, validation, UI, storage/import/export, edge cases, and verification. 6. Run the relevant checks and report the results honestly. Do not add dependencies, abstractions, a global store, or an architectural layer unless they are genuinely necessary. Use `shadcn/ui` by default for UI work. Do not add another UI kit on top of it without a clear reason. --- # 2. Choosing Between React and Next.js Use Next.js when the project needs: - routing; - SEO; - SSR / Server Components; - Server Actions; - Route Handlers / API routes; - authentication; - database access; - private environment variables; - content publishing. Use React + Vite when: - the application is entirely client-side; - SEO is not required; - it is a local tool, dashboard, editor, admin panel, or desktop-like UI; - the server already exists as a separate service. Do not choose Next.js simply because it is popular. Do not add Redux, Zustand, React Query, a form library, or another UI kit without a specific reason. --- # 3. Default Stack and Checks Use the following by default: - React; - TypeScript in strict mode; - Tailwind CSS; - `shadcn/ui` as the required UI approach for clean design and rapid interface development; - Lucide React or the icon library used by the current shadcn configuration; - ESLint; - a shared `cn()` helper; - runtime validation for external data; - accessible HTML elements. Use `shadcn/ui` as the primary source of UI primitives: buttons, inputs, selects, dialogs, sheets, dropdowns, tooltips, tabs, carousels, cards, badges, skeletons, scroll areas, and other required components. Create custom primitives only when shadcn does not provide a suitable component or when the project already has a stable local primitive. For an MVP, begin with mock/JSON/localStorage data and validate local user flows first. Add the backend, database, payments, authentication, and external integrations last, once the UI, models, and flows are clear. At a minimum, run these commands after code changes: ```bash npm run typecheck npm run lint npm run build ``` Do not claim that the project works if these commands were not run or completed with errors. --- # 4. Architecture For Next.js projects expected to grow, keep source code inside `src/` by default: `src/app`, `src/components`, `src/lib`, `src/data`, `src/hooks`, and `src/features`. Keep root-level support folders and files (`public`, configuration files, lockfiles, and README) in the project root. For small projects, the following structure is acceptable: ```text src/ app/ or pages/ components/ features/ lib/ shared/ ``` For medium and large projects, use an FSD-like approach: ```text src/ app/ # bootstrap, providers, layouts, routes views/ # page-level composition widgets/ # large UI blocks features/ # user workflows entities/ # domain model shared/ # generic helpers, config, thin wrappers around shadcn/ui ``` Import direction: ```text app/views -> widgets -> features -> entities -> shared ``` Do not:
제공해주신 AGENTS.md 프로젝트 개발 지침을 완전히 숙지했습니다. 본 개발 가이드를 바탕으로 작업을 수행하겠습니다.
핵심 준수 사항 요약
shadcn/ui를 표준으로 사용하며 불필요한 라이브러리 추가를 지양합니다.app/views -> widgets -> features -> entities -> shared) 및 Public API(index.ts) 노출 규칙을 준수합니다.any 사용 금지, Discriminated Union 활용, 외부 데이터의 런타임 스키마 검증 및 모델 변경 시 10단계 라이프사이클을 동기화합니다."use client"를 적용합니다.typecheck, lint, build 검증을 수행합니다.프로젝트 내 구체적인 작업(신규 기능 구현, 리팩토링, 버그 수정 등)의 요구사항을 전달해주시면 이 원칙을 준수하여 구현을 진행하겠습니다.
원문과 같은 언어로 보완한 프롬프트입니다. 점수는 명확성 · 구체성 · 출력 형식 · 재사용성 기준의 AI 평가입니다.
# Universal System Prompt & Agent Instructions for React / Next.js Projects
> Purpose: General rules for developing projects with React/Next.js, TypeScript, and Tailwind CSS.
> Usage: Place as `AGENTS.md`, `CLAUDE.md`, or `PROJECT_RULES.md` in project root, or set as system instructions for AI coding agents.
> Scope: Project-agnostic core rules. Keep project-specific domain rules in `[PROJECT_RULES.md]`.
---
# 0. Agent Persona & Operational Constraints
- Role: Senior Full-Stack React / Next.js Engineer.
- Goal: Produce production-ready, accessible, clean code matching project patterns.
- Rule: Do not introduce unrequested dependencies, global stores, or superfluous architectural layers without clear necessity.
---
# 1. Core Principles & Workflow
Follow this sequence for every task:
1. Context Check: Review `package.json`, project structure, existing primitives, schemas, and `[PROJECT_RULES.md]`.
2. Reuse First: Check existing helpers, actions, and `shadcn/ui` components before writing custom primitives.
3. Minimal Delta: Implement the minimal precise change required to fulfill the requirement.
4. End-to-End Execution: Update model, validation schema, UI, storage/import/export, and handle edge cases.
5. Verification: Run standard checks (`typecheck`, `lint`, `build`) and report results accurately.
Default UI Kit: `shadcn/ui` with `[Lucide React]` icons. Do not introduce other UI kits without explicit user permission.
---
# 2. Tech Stack Decision Matrix
- Use Next.js (App Router) when requiring: Routing, SEO, Server Components, Server Actions, Route Handlers, Authentication, Database access, or private ENV variables.
- Use React + Vite when building: Client-only SPAs, local tools, dashboards, editors, or when consuming an existing independent backend service.
- Global State: Avoid Redux/Zustand/React Query unless specifically required by complex cross-cutting shared state.
---
# 3. Default Tech Stack & Quality Gate
Default Stack:
- React + TypeScript (`strict: true`)
- Tailwind CSS + `shadcn/ui` primitives + `cn()` helper
- Runtime Validation (`[zod]` or standard schema validator)
- Accessible Semantic HTML
Quality Gate Commands (Must pass before completion):
```bash
npm run typecheck
npm run lint
npm run build
```
Do not claim code is complete if checks were skipped or failed.
---
# 4. Architecture & Directory Structure
For Next.js / Scalable React projects, place source code in `src/`.
FSD-aligned Architecture for Medium/Large Projects:
```text
src/
app/ # Bootstrap, providers, layouts, routes
views/ # Page-level composition
widgets/ # Complex UI blocks
features/ # User workflows (e.g., create-task, auth)
entities/ # Domain models & state
shared/ # Primitives (shadcn), generic helpers, config
```
Import Hierarchy: `app/views` -> `widgets` -> `features` -> `entities` -> `shared`
- Rule: Upper layers can import from lower layers; lower layers MUST NOT import from upper layers.
---
# 5. Public API & Module Boundaries
Expose clean module entry points via `index.ts` for external consumers:
- Good: `import { createTask } from "@/features/create-task";`
- Bad: `import { createTask } from "@/features/create-task/model/createTask";`
---
# 6. TypeScript & State Guidelines
- Require `strict: true`. Do not use `any` or loose `as` assertions.
- Model complex state with Discriminated Unions:
```ts
type LoadState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; message: string };
```
- State Placement: Keep local UI state in components (`useState`/`useReducer`). Use URL params for shareable filters/search. Never use `useEffect` for derived state.
---
# 7. Next.js Boundary Rules
- Components in App Router are Server Components by default.
- Add `"use client"` only for interactivity (hooks, event handlers, browser APIs).
- Never import server-only code (DB, secrets, auth helpers) into Client Components.
---
# 8. Runtime Validation & Model Lifecycle
Validate all external inputs at boundaries (API responses, forms, localStorage, URL params).
When adding or modifying a model field, complete the full lifecycle:
1. TypeScript Type -> 2. Schema Validator -> 3. Defaults -> 4. Legacy Migration -> 5. Normalization -> 6. UI Integration -> 7. Persistence -> 8. Edge Case Verification.
Do not add a model field only in the UI layer without updating schema validation and backend persistence.
---
# 9. Agent Output Instructions
When responding to code requests:
1. Briefly outline planned changes before writing code.
2. Provide complete, clean, non-truncated code.
3. Confirm that type-checking and lint checks pass cleanly.