nextjs-architecture
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js Architecture Enforcement
Next.js架构规则强制执行
Overview
概述
Enforces official Next.js architecture rules before code changes. Validate that the target is actually a Next.js project, determine whether App Router is in use, then apply strict rules for routing, Server and Client Component boundaries, server-first data fetching, Server Actions, Route Handlers, Proxy, and environment setup.
This skill is official-first. Treat the Next.js documentation as the source of truth. If a repo-local convention is stricter than the framework, label it clearly instead of silently presenting it as a framework rule.
OPERATING MODE: This skill is self-contained. Do not block on external orchestration just to apply architecture rules. If the user wants exhaustive verification, keep verifying. Otherwise proceed with this skill's own validation flow.
IMPORTANT: App Router is the default path for this skill. If the repo is Pages Router only, apply only the shared platform and boundary checks and do not force App Router-only file conventions unless the user is migrating or explicitly adding .
app/IMPORTANT: Prefer Server Actions for internal UI writes, especially forms and app-originated mutations. Use Route Handlers when the surface is genuinely HTTP-native, such as webhooks, feeds, CORS-sensitive endpoints, or machine-readable/public endpoints.
IMPORTANT: Treat every Server Action as a reachable POST entry point. Validation, authentication, authorization, and return-value filtering must happen inside the action or the delegated server-only data layer, not only in the page that renders the form.
在代码变更前强制执行Next.js官方架构规则。首先验证目标项目确实是Next.js项目,判断是否使用App Router,然后对路由、Server与Client Component边界、服务端优先的数据获取、Server Actions、Route Handlers、Proxy以及环境配置应用严格规则。
本技能遵循官方优先原则。 将Next.js文档视为权威来源。如果仓库本地约定比框架规则更严格,需明确标注,而非默认为框架规则。
运行模式: 本技能可独立运行。无需依赖外部编排即可应用架构规则。如果用户要求全面验证,则持续执行验证;否则按本技能自身的验证流程推进。
重要提示: App Router是本技能的默认适配路径。如果仓库仅使用Pages Router,仅应用通用平台和边界检查,除非用户正在迁移或明确添加目录,否则不强制App Router专属的文件约定。
app/重要提示: 内部UI写入操作优先使用Server Actions,尤其是表单和应用发起的变更操作。仅当场景真正属于HTTP原生场景(如webhook、订阅源、CENS敏感端点、机器可读/公开端点)时,才使用Route Handlers。
重要提示: 将每个Server Action视为可访问的POST入口点。验证、认证、授权和返回值过滤必须在Action内部或委托的服务端专属数据层中完成,不能仅在渲染表单的页面中处理。
Quick Surface Chooser
快速方案选择表
Use this table before reading the full gates:
| If the task sounds like... | Default surface | Do not default to... |
|---|---|---|
| Server Action | |
| Route Handler | Server Action |
| Server Component | Client-first fetching without a real need |
| | Server Action |
| move the code behind a server-only boundary | leaving secrets in client-reachable code |
| shared Next.js safety checks only | forcing App Router file conventions |
If the task matches one of these rows, start there, then read the linked rule file in Step 2 for detail.
在阅读完整规则前可参考此表:
| 如果任务描述类似... | 默认选用方案 | 不建议默认选用... |
|---|---|---|
| Server Action | |
| Route Handler | Server Action |
| Server Component | 无实际需求却优先使用客户端获取 |
| | Server Action |
| 将代码迁移至服务端专属边界后 | 将敏感信息留在客户端可访问代码中 |
| 仅执行Next.js通用安全检查 | 强制应用App Router文件约定 |
如果任务符合上述某一行,可从对应方案开始,然后阅读步骤2中链接的规则文件获取详细信息。
Trigger Examples
触发示例
Positive
适用场景
Audit this Next.js app before I add more App Router routes.Refactor a Next.js feature so Server Components, client boundaries, caching, and server actions follow the official docs.Add a Next.js Route Handler or Server Action and keep the architecture compliant.
在我添加更多App Router路由之前,审核这个Next.js应用。重构Next.js功能,确保Server Components、客户端边界、缓存和Server Actions符合官方文档要求。添加Next.js Route Handler或Server Action,并保持架构合规。
Negative
不适用场景
Create a generic React architecture guide.Review a Remix or TanStack Start app.
创建通用React架构指南。审核Remix或TanStack Start应用。
Boundary
边界场景
-
Direct editing can be enough if no architectural boundary is affected, but touched files still need a quick boundary check.
Make a tiny copy-only text change in a Next.js page. -
This skill still applies for shared Next.js platform, env, and boundary checks, but App Router-specific file rules must be relaxed.
This repo is Pages Router only and I am not migrating to App Router.
-
如果未涉及架构边界,直接编辑即可,但仍需对改动文件进行快速边界检查。
在Next.js页面中进行微小的纯文本修改。 -
本技能仍会应用Next.js通用平台、环境和边界检查,但会放宽App Router专属的文件规则。
这个仓库仅使用Pages Router,且我不打算迁移到App Router。
Step 1: Project Validation
步骤1:项目验证
Before any work, confirm a Next.js project and detect router mode:
bash
rg -n '"next"' package.json
find . -maxdepth 3 \( -path './app' -o -path './src/app' -o -path './pages' -o -path './src/pages' \)
test -f next.config.ts -o -f next.config.mjs -o -f next.config.jsInterpretation:
- No dependency found: stop, this skill does not apply.
next - or
app/present: full App Router mode.src/app/ - or
pages/present without App Router: shared Next.js mode only.src/pages/ - Mixed and
app/: prefer App Router rules for touchedpages/code and avoid breaking legacyapp/code without explicit migration intent.pages/
在开始任何工作前,确认项目为Next.js项目并检测路由模式:
bash
rg -n '"next"' package.json
find . -maxdepth 3 \( -path './app' -o -path './src/app' -o -path './pages' -o -path './src/pages' \)
test -f next.config.ts -o -f next.config.mjs -o -f next.config.js结果解读:
- 未找到依赖:停止操作,本技能不适用。
next - 存在或
app/:启用完整App Router模式。src/app/ - 存在或
pages/但无App Router:仅启用Next.js通用模式。src/pages/ - 同时存在和
app/:对改动的pages/代码优先应用App Router规则,若无明确迁移意图,避免破坏遗留app/代码。pages/
Step 2: Read Architecture Rules
步骤2:阅读架构规则
Load the detailed rules reference:
REQUIRED: Read in this skill directory before writing code.
architecture-rules.mdThen read the relevant rule files for the change:
- - App Router structure, special files, route groups, private folders, and segment boundaries
rules/routes.md - - Server vs Client Components,
rules/execution-model.md, providers, serializable props, anduse clientserver-only - - server data fetching, streaming, cache intent, dynamic rendering triggers, and revalidation
rules/data-fetching.md - -
rules/server-actions.md, validation, auth, authz, DAL delegation, revalidation, redirect ordering, and side-effect rulesuse server - - when
rules/route-handlers.mdis justified, method handling, caching defaults, and HTTP-only surfacesroute.ts - - environment variables,
rules/platform.md,next.config.*, Proxy, and deployment-sensitive setuptypedRoutes
If framework behavior may have drifted, also read:
- - official doc map for the rules this skill depends on
references/official/nextjs-docs.md
加载详细规则参考:
必填: 在编写代码前,阅读本技能目录下的。
architecture-rules.md然后阅读与变更相关的规则文件:
- - App Router结构、特殊文件、路由组、私有文件夹和分段边界
rules/routes.md - - Server与Client Components、
rules/execution-model.md、提供者、可序列化props和use clientserver-only - - 服务端数据获取、流式传输、缓存意图、动态渲染触发和重新验证
rules/data-fetching.md - -
rules/server-actions.md、验证、认证、授权、DAL委托、重新验证、重定向顺序和副作用规则use server - -
rules/route-handlers.md的适用场景、方法处理、缓存默认值和HTTP专属场景route.ts - - 环境变量、
rules/platform.md、next.config.*、Proxy和部署敏感配置typedRoutes
如果框架行为可能发生变化,还需阅读:
- - 本技能依赖规则对应的官方文档映射
references/official/nextjs-docs.md
Step 3: Pre-Change Validation Checklist
步骤3:变更前验证清单
Before writing any code, verify the planned change against these gates:
在编写代码前,验证计划变更是否符合以下规则:
Brownfield Adoption Rule
遗留项目适配规则
- Do not treat every untouched legacy deviation as an immediate project-wide failure.
- Safety and boundary issues still block immediately, especially in touched files.
- Legacy code can remain in place when the task is local and non-migratory.
pages/ - Any file you touch should be brought into compliance unless that would require a materially risky migration.
- 不要将所有未改动的遗留偏差视为立即需要修复的项目级问题。
- 安全和边界问题仍需立即阻止,尤其是改动文件中的问题。
- 当任务为局部且不涉及迁移时,遗留代码可保留原样。
pages/ - 任何你改动的文件都应符合规范,除非这需要进行高风险迁移。
Gate 1: Routing and File Conventions
规则1:路由与文件约定
| Check | Rule |
|---|---|
| BLOCKED |
| BLOCKED |
App Router feature work done in | BLOCKED unless explicitly requested |
| Route groups or private folders used without understanding URL impact? | WARNING. |
| Segment needs loading/error/not-found UX but no boundary exists? | WARNING. Add |
| 检查项 | 规则 |
|---|---|
| 阻止操作 |
在同一路由分段下同时创建 | 阻止操作 |
已存在对应 | 阻止操作(除非明确要求) |
| 使用路由组或私有文件夹但未理解其对URL的影响? | 警告。 |
| 分段需要加载/错误/未找到页面的UX,但未设置对应边界? | 警告。需主动添加 |
Gate 2: Server and Client Boundaries
规则2:Server与Client边界
| Check | Rule |
|---|---|
Interactive component missing | BLOCKED |
| BLOCKED. Keep client boundaries as narrow as possible |
Client Component imports server-only code, secrets, DB clients, or | BLOCKED |
Server-only helper missing | WARNING. Add a clear server-only boundary |
| Client Component props include broad DB records or non-serializable values? | BLOCKED |
| Context provider placed at the document root when a deeper boundary works? | WARNING. Render providers as deep as possible |
| 检查项 | 规则 |
|---|---|
交互式组件缺少 | 阻止操作 |
无需求却在组件树高层添加 | 阻止操作。尽量缩小客户端边界范围 |
Client Component导入服务端专属代码、敏感信息、数据库客户端或 | 阻止操作 |
服务端专属助手未添加 | 警告。添加明确的服务端专属边界 |
| Client Component的props包含完整数据库记录或不可序列化值? | 阻止操作 |
| 上下文提供者放置在文档根节点,但可在更深处设置边界? | 警告。尽量在较深层级渲染提供者 |
Gate 3: Data Fetching and Caching
规则3:数据获取与缓存
| Check | Rule |
|---|---|
| Initial page data fetched in a Client Component when a Server Component can do it? | BLOCKED unless there is a real client-only need |
Layout reads uncached runtime data and blocks same-segment | BLOCKED |
| Cache behavior is accidental or unclear? | BLOCKED. Choose and explain the cache strategy |
| Sensitive or privileged reads happen outside a DAL/server-only module without justification? | WARNING for prototypes, BLOCKED for production-oriented code |
Mutation completes without | BLOCKED |
| 检查项 | 规则 |
|---|---|
| 可通过Server Component获取初始页面数据,却在Client Component中获取? | 阻止操作(除非确实有客户端专属需求) |
布局读取未缓存的运行时数据,且未设置更接近的 | 阻止操作 |
| 缓存行为意外或不明确? | 阻止操作。需选择并说明缓存策略 |
| 敏感或特权读取操作未在DAL/服务端专属模块中执行且无合理理由? | 原型项目警告,面向生产的代码阻止操作 |
变更完成后,UI依赖新数据但未执行 | 阻止操作 |
Gate 4: Server Actions
规则4:Server Actions
| Check | Rule |
|---|---|
Internal UI mutation or form submit implemented with | BLOCKED unless real HTTP semantics are required |
| Action trusts form data, params, headers, or search params without validation or re-verification? | BLOCKED |
| Action relies only on page-level auth checks? | BLOCKED. Re-authorize inside the action |
| Action returns raw database rows or broad internal objects? | BLOCKED |
| Action performs DB or secret-heavy work directly when a server-only DAL exists or should exist? | WARNING for small code, BLOCKED for repeated domain logic |
Action mutates during rendering instead of from an explicit action path ( | BLOCKED |
| BLOCKED. Revalidate first, then redirect |
| 检查项 | 规则 |
|---|---|
内部UI变更或表单提交使用 | 阻止操作(除非确实需要HTTP语义) |
| Action信任表单数据、参数、请求头或查询参数,未进行验证或重新验证? | 阻止操作 |
| Action仅依赖页面级认证检查? | 阻止操作。需在Action内部重新授权 |
| Action返回原始数据库行或完整内部对象? | 阻止操作 |
| 已有或应存在服务端专属DAL的情况下,Action仍直接执行数据库或敏感操作? | 小型代码警告,重复领域逻辑阻止操作 |
Action在渲染期间而非通过明确的Action路径( | 阻止操作 |
在必要的重新验证前调用 | 阻止操作。先重新验证,再重定向 |
Gate 5: Route Handlers and Proxy
规则5:Route Handlers与Proxy
| Check | Rule |
|---|---|
Internal UI mutation implemented as | BLOCKED unless real HTTP semantics are required |
| Route Handler used for webhooks, feeds, CORS, or public machine endpoints? | ALLOWED |
Route Handler uses | BLOCKED |
Proxy added when | BLOCKED. Proxy is last resort |
| BLOCKED |
| Proxy matcher is missing or too broad for the actual need? | BLOCKED |
| 检查项 | 规则 |
|---|---|
内部UI变更使用 | 阻止操作(除非确实需要HTTP语义) |
| Route Handlers用于webhook、订阅源、CORS或公开机器端点? | 允许操作 |
Route Handlers使用 | 阻止操作 |
可通过 | 阻止操作。Proxy为最后选择 |
| 阻止操作 |
| Proxy匹配器缺失或范围远超实际需求? | 阻止操作 |
Gate 6: Platform and Environment
规则6:平台与环境
| Check | Rule |
|---|---|
| BLOCKED. They belong at project root |
Client code reads non- | BLOCKED |
| Runtime client env needed but treated as build-time inlined config? | BLOCKED. Expose via server path/API instead |
Multi-proxy or reverse-proxy deployment uses Server Actions without checking | WARNING |
| Next config toggles caching, routing, or server action behavior without clear intent? | BLOCKED |
Typed route safety would materially reduce routing mistakes but | WARNING. Consider enabling it intentionally |
| 检查项 | 规则 |
|---|---|
假设 | 阻止操作。此类文件应放置在项目根目录 |
客户端代码读取非 | 阻止操作 |
| 需要运行时客户端环境变量,但将其视为构建时内联配置? | 阻止操作。应通过服务端路径/API暴露 |
多代理或反向代理部署中使用Server Actions,但未检查 | 警告 |
| Next配置切换缓存、路由或Server Action行为,但未明确说明意图? | 阻止操作 |
TypeScript代码库中启用 | 警告。建议主动启用 |
Step 3.5: Auto-Remediation Policy
步骤3.5:自动修复策略
Auto-fix directly when the issue is local, reversible, and low-risk.
- narrow an overly broad boundary
'use client' - add ,
loading.tsx, orerror.tsxfor a touched segmentnot-found.tsx - move privileged reads into a server-only helper or DAL
- add markers and tighten client props
server-only - add missing revalidation after a Server Action mutation
- move a misused internal mutation to a Server Action when the change is small and local
route.ts - tighten Proxy matcher scope or move simple redirects into
next.config.* - correct /
.envusage and explicit config wiringNEXT_PUBLIC_
Do not auto-apply broad or potentially breaking migrations without explicit justification.
- mass route tree rewrites
- Pages Router to App Router migrations across large surfaces
- sweeping cache model changes
- turning many Route Handlers into Server Actions in one pass
- deployment-sensitive Server Action origin or encryption-key changes
当问题为局部、可逆且低风险时,可直接自动修复:
- 缩小过于宽泛的边界
'use client' - 为改动的分段添加、
loading.tsx或error.tsxnot-found.tsx - 将特权读取操作迁移至服务端专属助手或DAL
- 添加标记并收紧客户端props
server-only - 在Server Action变更后添加缺失的重新验证
- 当变更范围较小时,将误用的内部变更迁移至Server Action
route.ts - 收紧Proxy匹配器范围,或将简单重定向迁移至
next.config.* - 修正/
.env使用方式并明确配置关联NEXT_PUBLIC_
无明确理由时,不要自动应用宽泛或可能导致破坏的迁移:
- 大规模路由树重写
- 跨大范围的Pages Router到App Router迁移
- 全面缓存模型变更
- 一次性将多个Route Handlers转换为Server Actions
- 部署敏感的Server Action源或加密密钥变更
Step 4: Implementation
步骤4:实现
Carry these acceptance criteria into the active task:
text
- [ ] Next.js project mode validated before editing
- [ ] App Router rules applied only where they actually fit
- [ ] Routing files live in the correct route segment structure
- [ ] Server and Client Component boundaries are explicit and minimal
- [ ] Client code cannot reach server-only data, env, or modules
- [ ] Data fetching and caching strategy is intentional
- [ ] Server Actions are the default surface for internal UI writes
- [ ] Server Actions validate input, re-authorize, and return minimal data
- [ ] Route Handlers exist only for real HTTP-native needs
- [ ] Proxy is used only when simpler surfaces are insufficient
- [ ] Environment handling and next.config setup are boundary-safe将以下验收标准带入实际任务:
text
- [ ] 编辑前已验证Next.js项目模式
- [ ] App Router规则仅在适用场景下应用
- [ ] 路由文件放置在正确的路由分段结构中
- [ ] Server与Client Component边界明确且范围最小
- [ ] 客户端代码无法访问服务端专属数据、环境变量或模块
- [ ] 数据获取与缓存策略明确
- [ ] 内部UI写入操作默认使用Server Actions
- [ ] Server Actions验证输入、重新授权并返回最小化数据
- [ ] Route Handlers仅用于真正的HTTP原生场景
- [ ] 仅在更简单方案无法满足需求时才使用Proxy
- [ ] 环境处理与next.config配置符合边界安全要求Step 5: Post-Change Verification
步骤5:变更后验证
After writing code, verify:
- project mode still matches the edited surface (,
app/, or mixed)pages/ - route segment file placement is valid
- boundaries are as small as possible
'use client' - client code does not import server-only modules or private env
- data freshness after mutations is explicit (,
revalidatePath, redirect flow, or documented alternative)revalidateTag - Route Handlers and Proxy usage are still justified
- , env loading, and deployment-sensitive settings remain coherent
next.config.*
编写代码后,验证以下内容:
- 项目模式仍与改动的代码区域匹配(、
app/或混合模式)pages/ - 路由分段文件放置位置有效
- 边界范围尽可能小
'use client' - 客户端代码未导入服务端专属模块或私有环境变量
- 变更后的数据新鲜度明确(、
revalidatePath、重定向流程或文档化的替代方案)revalidateTag - Route Handlers与Proxy的使用仍合理
- 、环境变量加载和部署敏感配置保持一致
next.config.*
Quick Reference: App Router Shape
快速参考:App Router结构
text
app/
├── layout.tsx
├── page.tsx
├── dashboard/
│ ├── page.tsx
│ ├── loading.tsx
│ ├── error.tsx
│ ├── not-found.tsx
│ ├── _components/
│ └── _lib/
├── api/
│ └── webhooks/
│ └── route.ts
└── (marketing)/
└── about/
└── page.tsxKey meaning:
- organizes routes without affecting the URL
(group) - is a private implementation folder and does not become a route segment
_folder - is for HTTP handling, not page UI
route.ts - ,
loading.tsx, anderror.tsxare route-segment boundaries, not general-purpose componentsnot-found.tsx
text
app/
├── layout.tsx
├── page.tsx
├── dashboard/
│ ├── page.tsx
│ ├── loading.tsx
│ ├── error.tsx
│ ├── not-found.tsx
│ ├── _components/
│ └── _lib/
├── api/
│ └── webhooks/
│ └── route.ts
└── (marketing)/
└── about/
└── page.tsx关键含义:
- 用于组织路由,不影响URL
(group) - 为私有实现文件夹,不会成为路由分段
_folder - 用于HTTP处理,而非页面UI
route.ts - 、
loading.tsx和error.tsx是路由分段边界,而非通用组件not-found.tsx