modern-web-app-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Modern Web App Architecture (SPA/SSR/SSG/RSC)

现代Web应用架构(SPA/SSR/SSG/RSC)

Overview

概述

Comprehensive guidance for designing and building modern web applications (including SPAs and hybrid rendering apps). This skill emphasizes trade-offs, explicit boundaries, and production-ready practices (performance, accessibility, security, testing, delivery).
Core principle: Everything in architecture is a trade-off. There are no "right" answers, only least-worst combinations for your specific context.
为设计和构建现代Web应用(包括SPA和混合渲染应用)提供全面指导。本技能重点关注权衡取舍、明确边界以及生产就绪实践(性能、可访问性、安全性、测试、交付)。
核心原则: 架构中的所有选择都是权衡的结果。没有“正确答案”,只有针对特定场景的最优组合。

Operating Mode (How to Use This Skill)

操作模式(如何使用本技能)

When activated, work in this order:
  1. Clarify context (5–10 questions max) → users, routes, SEO, interactivity, data, auth, team, constraints.
  2. Choose a rendering strategy per route (not “one strategy for the whole app”).
  3. Define boundaries → feature/domain modules, shared libraries, ownership, and stable interfaces.
  4. Plan state + data → local/shared/global/server/URL state, cache strategy, invalidation, optimistic updates.
  5. Plan non-functionals → performance budgets + measurement, accessibility plan, security posture, observability.
  6. Produce artifacts → short recommendations with explicit trade-offs, plus concrete next steps (folder structure, ADRs, checklists).
If the user can’t answer a question, state reasonable assumptions and continue (don’t block).
激活本技能后,请按以下步骤操作:
  1. 明确上下文(最多5-10个问题) → 用户、路由、SEO、交互性、数据、认证、团队、约束条件。
  2. 为每个路由选择渲染策略(不要“为整个应用使用单一策略”)。
  3. 定义边界 → 功能/领域模块、共享库、所有权和稳定接口。
  4. 规划状态与数据 → 本地/共享/全局/服务器/URL状态、缓存策略、失效机制、乐观更新。
  5. 规划非功能性需求 → 性能预算与度量、可访问性计划、安全态势、可观测性。
  6. 产出成果 → 包含明确权衡的简短建议,加上具体的后续步骤(文件夹结构、架构决策记录(ADR)、检查清单)。
如果用户无法回答某个问题,请给出合理假设并继续(不要停滞)。

When to Use

适用场景

  • Starting a new SPA or web application
  • Choosing rendering strategies (CSR, SSR, SSG, ISR, RSC)
  • Implementing state management
  • Optimizing Core Web Vitals (LCP/INP/CLS)
  • Scaling for multiple frontend teams
  • Making architecture trade-off decisions
  • Migrating from legacy to modern frontend
  • 启动新的SPA或Web应用
  • 选择渲染策略(CSR、SSR、SSG、ISR、RSC)
  • 实现状态管理
  • 优化核心Web指标(LCP/INP/CLS)
  • 支持多前端团队规模扩展
  • 进行架构权衡决策
  • 从遗留前端迁移到现代前端

Quick Discovery Questions (Ask First)

快速探索问题(首先询问)

  • What are the top 3 user journeys and their target latency (e.g., “search → product → checkout”)?
  • Is SEO required for any routes? Which are public vs behind auth?
  • What’s the data shape: mostly CRUD, real-time, offline-first, heavy forms, large tables/charts?
  • What are the constraints: browser support, bundle limits, time-to-market, compliance (SOC2/HIPAA/PCI)?
  • What’s the team topology: how many devs/teams, release cadence, ownership boundaries?
  • What’s your preferred stack (React/Vue/Angular/vanilla), and are you open to TypeScript?
  • 前3个核心用户旅程及其目标延迟是多少?(例如:“搜索→产品→结账”)
  • 是否有路由需要SEO支持?哪些是公开路由,哪些在认证后方可访问?
  • 数据形态是什么:主要是CRUD、实时数据、离线优先、复杂表单、大型表格/图表?
  • 约束条件有哪些:浏览器支持范围、包体积限制、上市时间、合规要求(SOC2/HIPAA/PCI)?
  • 团队拓扑是怎样的:有多少开发人员/团队、发布节奏、所有权边界?
  • 你偏好的技术栈是什么(React/Vue/Angular/原生JS),是否愿意使用TypeScript?

Reference Files

参考文件

TopicWhen to Load
@references/design-patterns.mdImplementing JS patterns (Module, Observer, Factory, etc.)
@references/react-patterns.mdReact components, hooks, state, composition
@references/spa-fundamentals.mdSPA architecture, routing, module organization
@references/micro-frontends.mdScaling teams, independent deployments
@references/performance.mdBundle size, loading, Core Web Vitals
@references/architecture-decisions.mdTrade-offs, coupling, fitness functions
@references/rendering-strategies.mdCSR vs SSR vs SSG vs ISR vs RSC
@references/state-management.mdLocal, global, server state patterns
@references/security-and-auth.mdAuth choices, token storage, XSS/CSRF, CSP, API boundaries
@references/accessibility-and-i18n.mdWCAG basics, SPA focus mgmt, inclusive components, i18n pitfalls
@references/testing-and-quality.mdTesting strategy, CI quality gates, a11y checks, contract tests
@references/tooling-and-delivery.mdBundling, environments, deployment, observability, feature flags
主题加载时机
@references/design-patterns.md实现JS模式(模块、观察者、工厂等)时
@references/react-patterns.mdReact组件、Hooks、状态、组合时
@references/spa-fundamentals.mdSPA架构、路由、模块组织时
@references/micro-frontends.md团队规模扩展、独立部署时
@references/performance.md包体积、加载、核心Web指标优化时
@references/architecture-decisions.md权衡取舍、耦合度、适配性评估时
@references/rendering-strategies.mdCSR与SSR、SSG、ISR、RSC对比时
@references/state-management.md本地、全局、服务器端状态模式设计时
@references/security-and-auth.md认证方案选择、令牌存储、XSS/CSRF防护、CSP、API边界设计时
@references/accessibility-and-i18n.mdWCAG基础、SPA焦点管理、包容性组件、国际化陷阱规避时
@references/testing-and-quality.md测试策略、CI质量门禁、可访问性检查、契约测试设计时
@references/tooling-and-delivery.md打包、环境管理、部署、可观测性、功能标志配置时

Quick Architecture Decision Tree

快速架构决策树

Project Requirements?
├─ SEO critical + dynamic content → SSR (or SSR+streaming)
├─ SEO critical + mostly static → SSG/ISR (or hybrid)
├─ Mostly behind auth + app-like UX → CSR SPA (or hybrid with pre-rendered shell)
├─ Mixed (marketing + app) → Hybrid/Islands (route-level strategy)
Team Size?
├─ <5 developers → Modular monolith SPA
├─ 5-15 developers → Well-structured SPA or Service-based
├─ >15 developers, multiple teams → Consider micro-frontends
Domain Complexity?
├─ Simple CRUD → Layered architecture
├─ Complex workflows → Domain-partitioned (DDD)
├─ Multiple bounded contexts → Micro-frontends
Project Requirements?
├─ SEO critical + dynamic content → SSR (or SSR+streaming)
├─ SEO critical + mostly static → SSG/ISR (or hybrid)
├─ Mostly behind auth + app-like UX → CSR SPA (or hybrid with pre-rendered shell)
├─ Mixed (marketing + app) → Hybrid/Islands (route-level strategy)
Team Size?
├─ <5 developers → Modular monolith SPA
├─ 5-15 developers → Well-structured SPA or Service-based
├─ >15 developers, multiple teams → Consider micro-frontends
Domain Complexity?
├─ Simple CRUD → Layered architecture
├─ Complex workflows → Domain-partitioned (DDD)
├─ Multiple bounded contexts → Micro-frontends

Default Outputs (What You Should Produce)

默认输出内容(应产出的成果)

Depending on the user request, aim to output:
  • Route strategy map: a small table of routes → CSR/SSR/SSG/ISR/RSC + why
  • Module boundary sketch: feature folders, shared libs, interface contracts
  • State map: local/shared/global/server/URL, plus the chosen tooling pattern
  • Data plan: caching/invalidation, error states, optimistic updates, pagination
  • Quality plan: testing layers + CI gates + accessibility checks
  • Performance plan: budgets + measurement + concrete loading strategy (split points)
  • Risk register: top 5 risks + mitigations (e.g., hydration cost, auth posture, team coupling)
根据用户需求,目标输出包括:
  • 路由策略映射表:小型表格,列出路由→CSR/SSR/SSG/ISR/RSC + 选择原因
  • 模块边界草图:功能文件夹、共享库、接口契约
  • 状态映射表:本地/共享/全局/服务器/URL状态,以及所选工具模式
  • 数据规划:缓存/失效机制、错误状态处理、乐观更新、分页策略
  • 质量规划:测试分层 + CI门禁 + 可访问性检查
  • 性能规划:性能预算 + 度量方式 + 具体加载策略(拆分点)
  • 风险登记册:前5大风险 + 缓解措施(例如:水化成本、认证态势、团队耦合)

Essential Patterns Quick Reference

核心模式快速参考

Component Patterns

组件模式

PatternUse When
Container/PresentationalSeparating data from UI
Compound ComponentsBuilding composable APIs (Select, Menu)
HooksSharing stateful logic without HOCs
ProviderAvoiding prop drilling for global data
模式适用场景
容器/展示组件分离数据逻辑与UI呈现
复合组件构建可组合API(如Select、Menu)
Hooks共享有状态逻辑,无需高阶组件(HOC)
Provider避免全局数据的属性透传

State Management

状态管理

ApproachUse When
useState/useReducerLocal component state
ContextTheme, auth, low-frequency global state
Zustand/JotaiSimple global state, minimal boilerplate
Redux ToolkitComplex state, time-travel debugging
React Query/SWRServer state, caching, background refresh
XStateComplex flows with explicit state machines
方案适用场景
useState/useReducer组件本地状态
Context主题、认证、低频率全局状态
Zustand/Jotai简单全局状态,最小化样板代码
Redux Toolkit复杂状态、时间旅行调试
React Query/SWR服务器端状态、缓存、后台刷新
XState带有显式状态机的复杂流程

Performance Essentials

性能优化要点

TechniqueImpact
Code splittingReduce initial bundle
Lazy loadingDefer non-critical
React.memoPrevent unnecessary re-renders
useMemo/useCallbackStable references
Virtual listsHandle large datasets
技术影响
代码拆分减小初始包体积
懒加载延迟加载非关键资源
React.memo避免不必要的重渲染
useMemo/useCallback保持引用稳定性
虚拟列表处理大型数据集

Architecture Characteristics (Pick 3-7)

架构特性(选择3-7个)

CharacteristicQuestions to Ask
ScalabilityHow many concurrent users? Growth rate?
PerformanceWhat's acceptable TTI? LCP target?
DeployabilityHow often do you ship? Independent deploys?
TestabilityHow easy to verify changes?
MaintainabilityWhat's the expected lifespan?
ModularityHow often do requirements change?
特性需询问的问题
可扩展性并发用户数有多少?增长率如何?
性能可接受的交互时间(TTI)是多少?最大内容绘制(LCP)目标是多少?
可部署性发布频率是多少?是否支持独立部署?
可测试性验证变更的难易程度如何?
可维护性预期生命周期是多久?
模块化需求变更频率如何?

Anti-patterns to Avoid

需避免的反模式

Anti-patternProblemFix
Prop drillingTight couplingContext or state management
God componentsToo many responsibilitiesSplit by concern
Premature optimizationComplexity without evidenceProfile first
Shared mutable stateRace conditions, bugsImmutable patterns
Monolithic bundleSlow initial loadCode splitting
Over-fetchingWasted bandwidthGraphQL or BFF
LocalStorage tokens by defaultXSS turns into account takeoverPrefer httpOnly cookies + CSP (see security refs)
Global store for server dataCache invalidation painUse React Query/SWR for server state
反模式问题修复方案
属性透传紧耦合使用Context或状态管理方案
上帝组件职责过多按关注点拆分组件
过早优化无依据地增加复杂度先进行性能分析
共享可变状态竞态条件、Bug使用不可变模式
单体包初始加载缓慢代码拆分
过度获取带宽浪费使用GraphQL或BFF(后端前置)
默认使用LocalStorage存储令牌XSS攻击可能导致账户被盗优先使用httpOnly Cookie + CSP(内容安全策略)(详见安全参考文档)
全局存储服务器端数据缓存失效难题使用React Query/SWR管理服务器端状态

Performance Budgets

性能预算

Budgets must be calibrated to your users/devices, but these are good starting points for a “fast by default” app:
MetricTargetNeeds Work
LCP<2.5s2.5–4s
INP<200ms200–500ms
CLS<0.10.1–0.25
TTFB<800ms800ms–1.8s
Route JS (initial)<170KB gzip<300KB gzip
预算必须根据用户/设备情况校准,但以下是“默认快速”应用的良好起点:
指标目标值需优化区间
LCP<2.5秒2.5–4秒
INP<200毫秒200–500毫秒
CLS<0.10.1–0.25
TTFB<800毫秒800毫秒–1.8秒
初始路由JS体积(gzip压缩后)<170KB<300KB

Sources

资料来源

Synthesized from:
  • Learning JavaScript Design Patterns (Osmani, 2023)
  • React in Depth (Barklund, 2024)
  • SPA Design and Architecture (Scott)
  • Single Page Web Applications (Mikowski & Powell)
  • Building Micro-Frontends (Mezzalira)
  • Micro Frontends in Action (Geers)
  • Responsible JavaScript (Wagner)
  • High Performance Browser Networking (Grigorik)
  • Web Performance in Action (Wagner)
  • Frontend Architecture for Design Systems (Godbolt)
  • Fundamentals of Software Architecture (Richards & Ford)
  • Software Architecture: The Hard Parts (Ford et al.)
  • Patterns.dev
综合整理自:
  • 《Learning JavaScript Design Patterns》(Osmani, 2023)
  • 《React in Depth》(Barklund, 2024)
  • 《SPA Design and Architecture》(Scott)
  • 《Single Page Web Applications》(Mikowski & Powell)
  • 《Building Micro-Frontends》(Mezzalira)
  • 《Micro Frontends in Action》(Geers)
  • 《Responsible JavaScript》(Wagner)
  • 《High Performance Browser Networking》(Grigorik)
  • 《Web Performance in Action》(Wagner)
  • 《Frontend Architecture for Design Systems》(Godbolt)
  • 《Fundamentals of Software Architecture》(Richards & Ford)
  • 《Software Architecture: The Hard Parts》(Ford et al.)
  • Patterns.dev