nextjs-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Next.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/
目录,否则不强制App Router专属的文件约定。
重要提示: 内部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 surfaceDo not default to...
Add a form or internal app mutation in App Router
Server Action
route.ts
Add a webhook, feed, CORS endpoint, or public machine-readable endpoint
Route HandlerServer Action
Fetch initial page data for UI
Server ComponentClient-first fetching without a real need
Need redirect logic before render across many requests
next.config.*
or Proxy, with Proxy last
Server Action
Client Component imports DB code or private env
move the code behind a server-only boundaryleaving secrets in client-reachable code
Pages Router only repo and no migration requested
shared Next.js safety checks onlyforcing 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.
在阅读完整规则前可参考此表:
如果任务描述类似...默认选用方案不建议默认选用...
在App Router中添加表单或内部应用变更
Server Action
route.ts
添加webhook、订阅源、CORS端点或公开机器可读端点
Route HandlerServer Action
为UI获取初始页面数据
Server Component无实际需求却优先使用客户端获取
需要在多请求渲染前执行重定向逻辑
next.config.*
或Proxy(Proxy为最后选择)
Server Action
Client Component导入数据库代码或私有环境变量
将代码迁移至服务端专属边界后将敏感信息留在客户端可访问代码中
仅使用Pages Router的仓库,且不计划迁移至App Router
仅执行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

边界场景

  • Make a tiny copy-only text change in a Next.js page.
    Direct editing can be enough if no architectural boundary is affected, but touched files still need a quick boundary check.
  • This repo is Pages Router only and I am not migrating to App Router.
    This skill still applies for shared Next.js platform, env, and boundary checks, but App Router-specific file rules must be relaxed.
  • 在Next.js页面中进行微小的纯文本修改。
    如果未涉及架构边界,直接编辑即可,但仍需对改动文件进行快速边界检查。
  • 这个仓库仅使用Pages Router,且我不打算迁移到App Router。
    本技能仍会应用Next.js通用平台、环境和边界检查,但会放宽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.js
Interpretation:
  • No
    next
    dependency found: stop, this skill does not apply.
  • app/
    or
    src/app/
    present: full App Router mode.
  • pages/
    or
    src/pages/
    present without App Router: shared Next.js mode only.
  • Mixed
    app/
    and
    pages/
    : prefer App Router rules for touched
    app/
    code and avoid breaking legacy
    pages/
    code without explicit migration intent.
在开始任何工作前,确认项目为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/
    src/app/
    :启用完整App Router模式。
  • 存在
    pages/
    src/pages/
    但无App Router:仅启用Next.js通用模式。
  • 同时存在
    app/
    pages/
    :对改动的
    app/
    代码优先应用App Router规则,若无明确迁移意图,避免破坏遗留
    pages/
    代码。

Step 2: Read Architecture Rules

步骤2:阅读架构规则

Load the detailed rules reference:
REQUIRED: Read
architecture-rules.md
in this skill directory before writing code.
Then read the relevant rule files for the change:
  • rules/routes.md
    - App Router structure, special files, route groups, private folders, and segment boundaries
  • rules/execution-model.md
    - Server vs Client Components,
    use client
    , providers, serializable props, and
    server-only
  • rules/data-fetching.md
    - server data fetching, streaming, cache intent, dynamic rendering triggers, and revalidation
  • rules/server-actions.md
    -
    use server
    , validation, auth, authz, DAL delegation, revalidation, redirect ordering, and side-effect rules
  • rules/route-handlers.md
    - when
    route.ts
    is justified, method handling, caching defaults, and HTTP-only surfaces
  • rules/platform.md
    - environment variables,
    next.config.*
    ,
    typedRoutes
    , Proxy, and deployment-sensitive setup
If framework behavior may have drifted, also read:
  • references/official/nextjs-docs.md
    - official doc map for the rules this skill depends on
加载详细规则参考:
必填: 在编写代码前,阅读本技能目录下的
architecture-rules.md
然后阅读与变更相关的规则文件:
  • rules/routes.md
    - App Router结构、特殊文件、路由组、私有文件夹和分段边界
  • rules/execution-model.md
    - Server与Client Components、
    use client
    、提供者、可序列化props和
    server-only
  • rules/data-fetching.md
    - 服务端数据获取、流式传输、缓存意图、动态渲染触发和重新验证
  • rules/server-actions.md
    -
    use server
    、验证、认证、授权、DAL委托、重新验证、重定向顺序和副作用规则
  • rules/route-handlers.md
    -
    route.ts
    的适用场景、方法处理、缓存默认值和HTTP专属场景
  • rules/platform.md
    - 环境变量、
    next.config.*
    typedRoutes
    、Proxy和部署敏感配置
如果框架行为可能发生变化,还需阅读:
  • 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
    pages/
    code can remain in place when the task is local and non-migratory.
  • 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:路由与文件约定

CheckRule
page.tsx
,
layout.tsx
,
loading.tsx
,
error.tsx
,
not-found.tsx
, or
route.ts
placed outside the expected segment structure?
BLOCKED
route.ts
and
page.tsx
created at the same route segment?
BLOCKED
App Router feature work done in
pages/
even though
app/
already exists for that surface?
BLOCKED unless explicitly requested
Route groups or private folders used without understanding URL impact?WARNING.
(group)
does not affect URL,
_folder
stays private
Segment needs loading/error/not-found UX but no boundary exists?WARNING. Add
loading.tsx
,
error.tsx
, or
not-found.tsx
intentionally
检查项规则
page.tsx
layout.tsx
loading.tsx
error.tsx
not-found.tsx
route.ts
放置在预期分段结构之外?
阻止操作
在同一路由分段下同时创建
route.ts
page.tsx
阻止操作
已存在对应
app/
代码的情况下,仍在
pages/
中开发App Router功能?
阻止操作(除非明确要求)
使用路由组或私有文件夹但未理解其对URL的影响?警告。
(group)
不影响URL,
_folder
为私有目录
分段需要加载/错误/未找到页面的UX,但未设置对应边界?警告。需主动添加
loading.tsx
error.tsx
not-found.tsx

Gate 2: Server and Client Boundaries

规则2:Server与Client边界

CheckRule
Interactive component missing
'use client'
?
BLOCKED
'use client'
added high in the tree without need?
BLOCKED. Keep client boundaries as narrow as possible
Client Component imports server-only code, secrets, DB clients, or
process.env
private values?
BLOCKED
Server-only helper missing
import 'server-only'
or equivalent protected placement?
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
检查项规则
交互式组件缺少
'use client'
阻止操作
无需求却在组件树高层添加
'use client'
阻止操作。尽量缩小客户端边界范围
Client Component导入服务端专属代码、敏感信息、数据库客户端或
process.env
私有值?
阻止操作
服务端专属助手未添加
import 'server-only'
或未放置在受保护位置?
警告。添加明确的服务端专属边界
Client Component的props包含完整数据库记录或不可序列化值?阻止操作
上下文提供者放置在文档根节点,但可在更深处设置边界?警告。尽量在较深层级渲染提供者

Gate 3: Data Fetching and Caching

规则3:数据获取与缓存

CheckRule
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
loading.tsx
without a closer
<Suspense>
boundary?
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
revalidatePath
,
revalidateTag
, redirect, or another freshness strategy where the UI depends on new data?
BLOCKED
检查项规则
可通过Server Component获取初始页面数据,却在Client Component中获取?阻止操作(除非确实有客户端专属需求)
布局读取未缓存的运行时数据,且未设置更接近的
<Suspense>
边界,导致阻塞同分段的
loading.tsx
阻止操作
缓存行为意外或不明确?阻止操作。需选择并说明缓存策略
敏感或特权读取操作未在DAL/服务端专属模块中执行且无合理理由?原型项目警告,面向生产的代码阻止操作
变更完成后,UI依赖新数据但未执行
revalidatePath
revalidateTag
、重定向或其他刷新策略?
阻止操作

Gate 4: Server Actions

规则4:Server Actions

CheckRule
Internal UI mutation or form submit implemented with
route.ts
even though a Server Action fits?
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 (
form
, event, transition)?
BLOCKED
redirect()
called before required revalidation?
BLOCKED. Revalidate first, then redirect
检查项规则
内部UI变更或表单提交使用
route.ts
实现,但更适合使用Server Action?
阻止操作(除非确实需要HTTP语义)
Action信任表单数据、参数、请求头或查询参数,未进行验证或重新验证?阻止操作
Action仅依赖页面级认证检查?阻止操作。需在Action内部重新授权
Action返回原始数据库行或完整内部对象?阻止操作
已有或应存在服务端专属DAL的情况下,Action仍直接执行数据库或敏感操作?小型代码警告,重复领域逻辑阻止操作
Action在渲染期间而非通过明确的Action路径(
form
、事件、过渡)执行变更?
阻止操作
在必要的重新验证前调用
redirect()
阻止操作。先重新验证,再重定向

Gate 5: Route Handlers and Proxy

规则5:Route Handlers与Proxy

CheckRule
Internal UI mutation implemented as
route.ts
even though a Server Action fits better?
BLOCKED unless real HTTP semantics are required
Route Handler used for webhooks, feeds, CORS, or public machine endpoints?ALLOWED
Route Handler uses
NextResponse.next()
to forward like Proxy?
BLOCKED
Proxy added when
redirects
,
rewrites
, headers, or render-time logic would be enough?
BLOCKED. Proxy is last resort
proxy.ts
not placed at project root or
src/
root level next to
app
or
pages
?
BLOCKED
Proxy matcher is missing or too broad for the actual need?BLOCKED
检查项规则
内部UI变更使用
route.ts
实现,但更适合使用Server Action?
阻止操作(除非确实需要HTTP语义)
Route Handlers用于webhook、订阅源、CORS或公开机器端点?允许操作
Route Handlers使用
NextResponse.next()
实现类似Proxy的转发?
阻止操作
可通过
redirects
rewrites
、请求头或渲染时逻辑实现需求,却添加了Proxy?
阻止操作。Proxy为最后选择
proxy.ts
未放置在项目根目录或
src/
根目录(与
app
pages
同级)?
阻止操作
Proxy匹配器缺失或范围远超实际需求?阻止操作

Gate 6: Platform and Environment

规则6:平台与环境

CheckRule
.env*
files assumed to load from
src/
?
BLOCKED. They belong at project root
Client code reads non-
NEXT_PUBLIC_
env vars?
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
serverActions.allowedOrigins
needs?
WARNING
Next config toggles caching, routing, or server action behavior without clear intent?BLOCKED
Typed route safety would materially reduce routing mistakes but
typedRoutes
is ignored in a TypeScript codebase?
WARNING. Consider enabling it intentionally
检查项规则
假设
.env*
文件从
src/
目录加载?
阻止操作。此类文件应放置在项目根目录
客户端代码读取非
NEXT_PUBLIC_
前缀的环境变量?
阻止操作
需要运行时客户端环境变量,但将其视为构建时内联配置?阻止操作。应通过服务端路径/API暴露
多代理或反向代理部署中使用Server Actions,但未检查
serverActions.allowedOrigins
配置需求?
警告
Next配置切换缓存、路由或Server Action行为,但未明确说明意图?阻止操作
TypeScript代码库中启用
typedRoutes
可大幅减少路由错误,但未启用?
警告。建议主动启用

Step 3.5: Auto-Remediation Policy

步骤3.5:自动修复策略

Auto-fix directly when the issue is local, reversible, and low-risk.
  • narrow an overly broad
    'use client'
    boundary
  • add
    loading.tsx
    ,
    error.tsx
    , or
    not-found.tsx
    for a touched segment
  • move privileged reads into a server-only helper or DAL
  • add
    server-only
    markers and tighten client props
  • add missing revalidation after a Server Action mutation
  • move a misused internal
    route.ts
    mutation to a Server Action when the change is small and local
  • tighten Proxy matcher scope or move simple redirects into
    next.config.*
  • correct
    .env
    /
    NEXT_PUBLIC_
    usage and explicit config wiring
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.tsx
    not-found.tsx
  • 将特权读取操作迁移至服务端专属助手或DAL
  • 添加
    server-only
    标记并收紧客户端props
  • 在Server Action变更后添加缺失的重新验证
  • 当变更范围较小时,将误用的内部
    route.ts
    变更迁移至Server Action
  • 收紧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:
  1. project mode still matches the edited surface (
    app/
    ,
    pages/
    , or mixed)
  2. route segment file placement is valid
  3. 'use client'
    boundaries are as small as possible
  4. client code does not import server-only modules or private env
  5. data freshness after mutations is explicit (
    revalidatePath
    ,
    revalidateTag
    , redirect flow, or documented alternative)
  6. Route Handlers and Proxy usage are still justified
  7. next.config.*
    , env loading, and deployment-sensitive settings remain coherent
编写代码后,验证以下内容:
  1. 项目模式仍与改动的代码区域匹配(
    app/
    pages/
    或混合模式)
  2. 路由分段文件放置位置有效
  3. 'use client'
    边界范围尽可能小
  4. 客户端代码未导入服务端专属模块或私有环境变量
  5. 变更后的数据新鲜度明确(
    revalidatePath
    revalidateTag
    、重定向流程或文档化的替代方案)
  6. Route Handlers与Proxy的使用仍合理
  7. 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.tsx
Key meaning:
  • (group)
    organizes routes without affecting the URL
  • _folder
    is a private implementation folder and does not become a route segment
  • route.ts
    is for HTTP handling, not page UI
  • loading.tsx
    ,
    error.tsx
    , and
    not-found.tsx
    are route-segment boundaries, not general-purpose components
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
关键含义:
  • (group)
    用于组织路由,不影响URL
  • _folder
    为私有实现文件夹,不会成为路由分段
  • route.ts
    用于HTTP处理,而非页面UI
  • loading.tsx
    error.tsx
    not-found.tsx
    是路由分段边界,而非通用组件