nextjs-fastapi-conventions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js + FastAPI Conventions
Next.js + FastAPI 开发规范
Single source of truth for architecture, code quality, and testing in
Next.js + FastAPI full-stack projects.
是Next.js + FastAPI全栈项目中架构设计、代码质量、测试相关规则的唯一权威参考。
Project Stack
技术栈
- Frontend: Next.js 16 (App Router) + React 19 + shadcn/ui + Tailwind CSS
v4 (TypeScript, in )
frontend/ - Backend: FastAPI + Uvicorn + Pydantic (Python 3.11+, in )
backend/
- 前端: Next.js 16 (App Router) + React 19 + shadcn/ui + Tailwind CSS v4 (TypeScript,存放于目录)
frontend/ - 后端: FastAPI + Uvicorn + Pydantic (Python 3.11+,存放于目录)
backend/
Architecture
架构设计
BFF Pattern
BFF模式
The browser NEVER calls FastAPI directly. All backend communication flows
through the Next.js server layer:
- Server Actions () handle mutations. Client components call these; they run on the Next.js server and proxy to FastAPI.
app/actions.ts - API Routes () exist ONLY for external consumers (health checks, webhooks), NOT for frontend use.
app/api/*/route.ts
浏览器永远不会直接调用FastAPI接口,所有后端通信都需要经过Next.js服务层流转:
- Server Actions()处理变更操作,客户端组件调用这些方法,它们在Next.js服务端运行并代理请求到FastAPI。
app/actions.ts - API Routes()仅提供给外部调用方使用(健康检查、webhook),不供前端内部调用。
app/api/*/route.ts
Type Safety (Zod Contracts)
类型安全(Zod契约)
Every FastAPI response is validated on the frontend with Zod:
- : Zod schemas mirroring Pydantic models.
lib/contracts.ts - :
lib/backend-client.tsfetches + validates against Zod.backendJson() - Contract breaks fail fast with .
BackendRequestError
New endpoint checklist:
- Pydantic response model in .
backend/api/schemas.py - Matching Zod schema in .
frontend/lib/contracts.ts - Contract test in .
frontend/tests/contracts.test.ts - with schema in Server Action.
backendJson()
所有FastAPI返回的响应都会在前端通过Zod进行校验:
- :定义与Pydantic模型一一对应的Zod schema。
lib/contracts.ts - :
lib/backend-client.ts方法负责发起请求并按照Zod schema校验返回结果。backendJson() - 契约不匹配时会快速抛出错误。
BackendRequestError
新增接口检查清单:
- 在中定义Pydantic响应模型。
backend/api/schemas.py - 在中定义匹配的Zod schema。
frontend/lib/contracts.ts - 在中添加契约测试。
frontend/tests/contracts.test.ts - 在Server Action中使用带schema校验的方法。
backendJson()
Components
组件
- Server Components (default): fetch data, pass as props.
- Client Components (): interactivity, browser APIs, hooks.
'use client'
- Server Components(默认):负责拉取数据,通过props传递给子组件。
- Client Components(标注):负责交互逻辑、调用浏览器API、使用hooks。
'use client'
React 19
React 19
- (NOT deprecated
useActionState).useFormState - Explicit state types (e.g. in
GreetingState).lib/greeting-state.ts
- 使用(不要使用已废弃的
useActionState)。useFormState - 显式定义状态类型(例如中的
lib/greeting-state.ts)。GreetingState
Backend Structure
后端结构
- Lifespan via (NOT
@asynccontextmanager).@app.on_event - for typed config from env vars.
pydantic-settings - Versioned routers under .
api/v1/ - Every endpoint declares and returns a Pydantic model.
response_model
- 使用定义生命周期(不要使用
@asynccontextmanager)。@app.on_event - 使用从环境变量中读取带类型的配置。
pydantic-settings - 版本化路由统一存放于目录下。
api/v1/ - 每个接口都要声明并返回Pydantic模型实例。
response_model
Code Quality
代码质量
Python
Python
- Async endpoints, (not
httpx.AsyncClient).requests - Type hints everywhere. for FastAPI params.
Annotated - Docstrings on modules, classes, public functions.
- for API errors. No swallowed exceptions.
HTTPException - Import grouping: stdlib | third-party | local.
- 异步接口使用(不要使用
httpx.AsyncClient)。requests - 所有位置都要添加类型注解,FastAPI参数使用声明。
Annotated - 模块、类、公共函数都需要添加文档字符串。
- API错误使用抛出,不要吞掉异常。
HTTPException - 导入分组顺序:标准库 | 第三方依赖 | 本地模块。
TypeScript
TypeScript
- . Never
strict: true(preferany+ narrowing).unknown - Zod for all external data; derive types with .
z.infer<> - Server Actions: , return typed state objects.
'use server' - shadcn/ui components from .
components/ui/ - Import grouping: React/Next.js | third-party | local (components > lib > types).
@/ - Tailwind v4 semantic tokens (,
text-foreground), not raw colours.bg-muted
- 开启,禁止使用
strict: true(优先使用any+类型收窄)。unknown - 所有外部数据都用Zod校验,通过推导类型。
z.infer<> - Server Action标注,返回带类型的状态对象。
'use server' - shadcn/ui组件从导入。
components/ui/ - 导入分组顺序:React/Next.js | 第三方依赖 | 本地模块(组件 > 工具库 > 类型定义)。
@/ - 使用Tailwind v4语义化token(、
text-foreground),不要直接写原始色值。bg-muted
Styling
样式规范
- Tailwind utility classes in JSX. from
cn()for conditional classes.lib/utils.ts - Semantic tokens from , not raw colour values.
@theme - Mobile-first responsive (,
sm:,md:).lg: - CVA for component variants. Sonner for toasts. next-themes for theme switching.
- JSX中使用Tailwind工具类,条件类使用导出的
lib/utils.ts方法处理。cn() - 使用提供的语义化token,不要直接写原始色值。
@theme - 采用移动端优先的响应式设计(、
sm:、md:)。lg: - 组件变体使用CVA定义,toast使用Sonner实现,主题切换使用next-themes。
File Organisation
文件组织
- Pages in (App Router). Reusable components in
app/.components/ - shadcn/ui in (don't edit directly).
components/ui/ - Shared utils/types in . Import via
lib/.@/
- 页面存放于目录(App Router模式),可复用组件存放于
app/目录。components/ - shadcn/ui组件存放于目录,不要直接修改。
components/ui/ - 共享工具/类型存放于目录,通过
lib/别名导入。@/
Testing
测试
Backend (pytest)
后端(pytest)
- +
pytest(auto mode).pytest-asyncio - +
httpx.AsyncClientagainst FastAPIASGITransport.app - Assert status codes AND JSON payloads.
- for async tests.
@pytest.mark.anyio
- 使用+
pytest(自动模式)。pytest-asyncio - 使用+
httpx.AsyncClient对接FastAPIASGITransport实例测试。app - 同时断言状态码和JSON返回值。
- 异步测试添加装饰器。
@pytest.mark.anyio
Frontend (Vitest)
前端(Vitest)
- . Tests in
environment: 'node'.frontend/tests/*.test.ts - Contract tests: and
.parse()against schemas..safeParse() - /
describeblocks,itmatchers.expect()
- 测试环境设置为,测试用例存放于
environment: 'node'。frontend/tests/*.test.ts - 契约测试调用schema的和
.parse()方法进行校验。.safeParse() - 使用/
describe块组织测试用例,使用it匹配器断言。expect()
Commands
常用命令
Backend
后端
bash
cd backend && python -m pytest tests/ -v # all tests
cd backend && python -m pytest tests/ -v -k <name> # specific test
cd backend && ruff check --fix . && ruff format . # lint+fix
cd backend && ruff check . && ruff format --check . # lint check onlybash
cd backend && python -m pytest tests/ -v # 运行所有测试
cd backend && python -m pytest tests/ -v -k <name> # 运行指定测试
cd backend && ruff check --fix . && ruff format . # 执行lint并自动修复+格式化
cd backend && ruff check . && ruff format --check . # 仅执行lint和格式检查Frontend
前端
bash
cd frontend && pnpm test # all tests
cd frontend && pnpm test:watch # watch mode
cd frontend && pnpm lint # lint
cd frontend && pnpm format # formatbash
cd frontend && pnpm test # 运行所有测试
cd frontend && pnpm test:watch # 启动监听模式运行测试
cd frontend && pnpm lint # 执行lint检查
cd frontend && pnpm format # 执行代码格式化