nextjs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js App Router - Production Patterns
Next.js App Router - 生产环境实践模式
Version: Next.js 16.0.3
React Version: 19.2.0
Node.js: 20.9+
Last Verified: 2025-11-21
版本: Next.js 16.0.3
React版本: 19.2.0
Node.js: 20.9+
最后验证时间: 2025-11-21
Table of Contents
目录
When to Use This Skill
何时使用该技能
Use this skill when you need:
- Next.js 16 App Router patterns (layouts, loading, error boundaries, routing)
- Server Components best practices (data fetching, composition, streaming)
- Server Actions patterns (forms, mutations, revalidation, error handling)
- Cache Components with directive (NEW in Next.js 16)
"use cache" - New caching APIs: ,
revalidateTag(),updateTag()(Updated in Next.js 16)refresh() - Migration from Next.js 15 to 16 (async params, proxy.ts, parallel routes)
- Route Handlers (API endpoints, webhooks, streaming responses)
- Proxy patterns (replaces
proxy.tsin Next.js 16)middleware.ts - Async route params (,
params,searchParams,cookies()now async)headers() - Parallel routes with default.js (breaking change in Next.js 16)
- React 19.2 features (View Transitions, , React Compiler)
useEffectEvent() - Metadata API (SEO, Open Graph, Twitter Cards, sitemaps)
- Image optimization (with updated defaults in Next.js 16)
next/image - Performance optimization (lazy loading, code splitting, PPR, ISR)
在以下场景中使用本技能:
- Next.js 16 App Router 实践模式(布局、加载状态、错误边界、路由)
- Server Components 最佳实践(数据获取、组件组合、流式渲染)
- Server Actions 实践模式(表单处理、数据变更、重新验证、错误处理)
- 带有指令的Cache Components(Next.js 16 新增特性)
"use cache" - 新缓存API:、
revalidateTag()、updateTag()(Next.js 16 更新)refresh() - 从Next.js 15迁移到16(异步参数、proxy.ts、并行路由)
- Route Handlers(API端点、Webhooks、流式响应)
- 代理模式(Next.js 16中替代
proxy.ts)middleware.ts - 异步路由参数(、
params、searchParams、cookies()现在为异步方法)headers() - 带有default.js的并行路由(Next.js 16中的破坏性变更)
- React 19.2 特性(View Transitions、、React Compiler)
useEffectEvent() - Metadata API(SEO、Open Graph、Twitter Cards、站点地图)
- 图片优化(Next.js 16中默认配置更新的)
next/image - 性能优化(懒加载、代码分割、PPR、ISR)
When NOT to Use This Skill
何时不使用该技能
Do NOT use this skill for:
- Cloudflare Workers deployment → Use skill instead
cloudflare-nextjs - Pages Router patterns → This skill covers App Router ONLY (Pages Router is legacy)
- Authentication libraries → Use ,
clerk-auth, or other auth-specific skillsauth-js - Database integration → Use ,
cloudflare-d1, or database-specific skillsdrizzle-orm-d1 - UI component libraries → Use skill for Tailwind + shadcn/ui
tailwind-v4-shadcn - State management → Use ,
zustand-state-managementskillstanstack-query - Form libraries → Use skill
react-hook-form-zod
请勿在以下场景使用本技能:
- Cloudflare Workers部署 → 请使用技能
cloudflare-nextjs - Pages Router实践模式 → 本技能仅覆盖App Router(Pages Router已属 legacy)
- 认证库 → 请使用、
clerk-auth或其他认证专属技能auth-js - 数据库集成 → 请使用、
cloudflare-d1或数据库专属技能drizzle-orm-d1 - UI组件库 → 请使用技能处理Tailwind + shadcn/ui
tailwind-v4-shadcn - 状态管理 → 请使用、
zustand-state-management技能tanstack-query - 表单库 → 请使用技能
react-hook-form-zod
Next.js 16 Breaking Changes
Next.js 16 破坏性变更
CRITICAL: Next.js 16 has multiple breaking changes. For detailed migration steps, see .
references/next-16-migration-guide.md| Breaking Change | Before | After |
|---|---|---|
| Async params | | |
| Async headers | | |
| Middleware | | |
| Parallel routes | | |
| Caching | Auto-cached fetch | Opt-in with |
| revalidateTag() | 1 argument | 2 arguments (tag + cacheLife) |
| Node.js | 18.x+ | 20.9+ required |
| React | 18.x | 19.2+ required |
Quick Fix for Async Params:
typescript
// ✅ Next.js 16 pattern
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return <div>{id}</div>
}Codemod:
bunx @next/codemod@canary upgrade latestSee: for complete migration guide with examples.
references/next-16-migration-guide.md重要提示:Next.js 16存在多项破坏性变更。详细迁移步骤请查看。
references/next-16-migration-guide.md| 破坏性变更 | 之前的写法 | 之后的写法 |
|---|---|---|
| 异步参数 | | |
| 异步headers | | |
| 中间件 | | |
| 并行路由 | | |
| 缓存机制 | 自动缓存fetch请求 | 通过 |
| revalidateTag() | 1个参数 | 2个参数(tag + cacheLife) |
| Node.js版本 | 18.x+ | 20.9+ 必填 |
| React版本 | 18.x | 19.2+ 必填 |
异步参数快速修复:
typescript
// ✅ Next.js 16 写法
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return <div>{id}</div>
}代码转换工具:
bunx @next/codemod@canary upgrade latest参考: 获取包含示例的完整迁移指南。
references/next-16-migration-guide.mdCache Components & Caching APIs
Cache Components 与缓存API
"use cache" Directive (NEW in Next.js 16)
"use cache" 指令(Next.js 16 新增)
typescript
'use cache'
export async function BlogPosts() {
const posts = await db.posts.findMany()
return posts.map(post => <article key={post.id}>{post.title}</article>)
}typescript
'use cache'
export async function BlogPosts() {
const posts = await db.posts.findMany()
return posts.map(post => <article key={post.id}>{post.title}</article>)
}Caching APIs Summary
缓存API汇总
| API | Purpose | Example |
|---|---|---|
| Opt-in component/function caching | |
| Invalidate by tag | |
| Update cache without revalidation | |
| Refresh current page | |
| Invalidate by path | |
| API | 用途 | 示例 |
|---|---|---|
| 手动开启组件/函数缓存 | 在顶部添加 |
| 按标签失效缓存 | |
| 更新缓存无需重新验证 | |
| 刷新当前页面 | |
| 按路径失效缓存 | |
PPR (Partial Prerendering)
PPR(部分预渲染)
typescript
// next.config.ts
const config = { experimental: { ppr: true } }
// page.tsx
export const experimental_ppr = true
export default function Page() {
return (
<>
<StaticHeader />
<Suspense fallback={<Skeleton />}>
<DynamicContent />
</Suspense>
</>
)
}See: for complete caching API reference with ISR, tag-based revalidation, and advanced patterns.
references/caching-apis.mdtypescript
// next.config.ts
const config = { experimental: { ppr: true } }
// page.tsx
export const experimental_ppr = true
export default function Page() {
return (
<>
<StaticHeader />
<Suspense fallback={<Skeleton />}>
<DynamicContent />
</Suspense>
</>
)
}参考: 获取包含ISR、基于标签的重新验证和进阶模式的完整缓存API参考。
references/caching-apis.mdServer Components
Server Components
Server Components are the default in App Router. They run on the server and can fetch data, access databases, and keep logic server-side.
typescript
// app/posts/page.tsx (Server Component by default)
export default async function PostsPage() {
const posts = await db.posts.findMany()
return <div>{posts.map(p => <article key={p.id}>{p.title}</article>)}</div>
}Server Components是App Router中的默认组件类型。它们在服务器端运行,可进行数据获取、访问数据库,并将逻辑保留在服务端。
typescript
// app/posts/page.tsx(默认是Server Component)
export default async function PostsPage() {
const posts = await db.posts.findMany()
return <div>{posts.map(p => <article key={p.id}>{p.title}</article>)}</div>
}Streaming with Suspense
结合Suspense实现流式渲染
typescript
import { Suspense } from 'react'
export default function Page() {
return (
<div>
<Header />
<Suspense fallback={<Skeleton />}>
<Posts />
</Suspense>
</div>
)
}typescript
import { Suspense } from 'react'
export default function Page() {
return (
<div>
<Header />
<Suspense fallback={<Skeleton />}>
<Posts />
</Suspense>
</div>
)
}Server vs Client Components
Server Components vs Client Components
| Server Components | Client Components |
|---|---|
| Data fetching, DB access | Interactivity (onClick) |
| Sensitive logic | React hooks (useState) |
| Large dependencies | Browser APIs |
| Static content | Real-time updates |
Client Component (requires ):
'use client'typescript
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}| Server Components | Client Components |
|---|---|
| 数据获取、数据库访问 | 交互逻辑(如onClick) |
| 敏感逻辑处理 | React钩子(如useState) |
| 可引入大体积依赖 | 浏览器API调用 |
| 静态内容渲染 | 实时更新 |
Client Component(需添加):
'use client'typescript
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}Server Actions
Server Actions
Server Actions are async functions that run on the server, callable from Client or Server Components.
Server Actions是运行在服务器端的异步函数,可从Client或Server Components中调用。
Basic Server Action
基础Server Action
typescript
// app/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
await db.posts.create({ data: { title } })
revalidatePath('/posts')
}typescript
// app/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
await db.posts.create({ data: { title } })
revalidatePath('/posts')
}Form Handling
表单处理
typescript
// Server Component Form (simplest)
import { createPost } from './actions'
export default function NewPostPage() {
return (
<form action={createPost}>
<input name="title" required />
<button type="submit">Create</button>
</form>
)
}typescript
// Server Component表单(最简写法)
import { createPost } from './actions'
export default function NewPostPage() {
return (
<form action={createPost}>
<input name="title" required />
<button type="submit">创建文章</button>
</form>
)
}Available Patterns
可用实践模式
| Pattern | Use Case | Reference |
|---|---|---|
| Client Form with Loading | useFormState + useFormStatus | |
| Error Handling | Return { error } or { success } | |
| Optimistic Updates | useOptimistic hook | |
| File Upload | FormData + blob storage | |
| Redirect After Action | redirect() function | |
See: for error handling, optimistic updates, file uploads, and advanced patterns.
references/server-actions-patterns.md| 模式 | 使用场景 | 参考 |
|---|---|---|
| 带加载状态的客户端表单 | useFormState + useFormStatus | |
| 错误处理 | 返回{ error }或{ success } | |
| 乐观更新 | useOptimistic钩子 | |
| 文件上传 | FormData + blob存储 | |
| 操作后重定向 | redirect()函数 | |
参考: 获取错误处理、乐观更新、文件上传和进阶模式的内容。
references/server-actions-patterns.mdRoute Handlers
Route Handlers
Route Handlers are the App Router equivalent of API Routes.
typescript
// app/api/posts/route.ts
export async function GET(request: Request) {
const posts = await db.posts.findMany()
return Response.json({ posts })
}
export async function POST(request: Request) {
const body = await request.json()
const post = await db.posts.create({ data: body })
return Response.json({ post }, { status: 201 })
}Dynamic Routes (with async params):
typescript
// app/api/posts/[id]/route.ts
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params // Await in Next.js 16
const post = await db.posts.findUnique({ where: { id } })
return post ? Response.json({ post }) : Response.json({ error: 'Not found' }, { status: 404 })
}See: for search params, webhooks, and streaming patterns.
templates/route-handler-api.tsRoute Handlers是App Router版本的API Routes。
typescript
// app/api/posts/route.ts
export async function GET(request: Request) {
const posts = await db.posts.findMany()
return Response.json({ posts })
}
export async function POST(request: Request) {
const body = await request.json()
const post = await db.posts.create({ data: body })
return Response.json({ post }, { status: 201 })
}动态路由(带异步参数):
typescript
// app/api/posts/[id]/route.ts
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params // Next.js 16中需await
const post = await db.posts.findUnique({ where: { id } })
return post ? Response.json({ post }) : Response.json({ error: '未找到' }, { status: 404 })
}参考: 获取搜索参数、Webhooks和流式响应模式。
templates/route-handler-api.tsReact 19.2 Features
React 19.2 特性
| Feature | Usage |
|---|---|
| React Compiler | |
| View Transitions | |
| useEffectEvent | Stable event handlers without deps |
| 特性 | 使用方式 |
|---|---|
| React Compiler | |
| View Transitions | |
| useEffectEvent | 无需依赖项的稳定事件处理器 |
Metadata API
Metadata API
typescript
// Static metadata
export const metadata: Metadata = {
title: 'My Blog',
description: 'A blog about Next.js',
openGraph: { title: 'My Blog', images: ['/og-image.jpg'] },
}
// Dynamic metadata (await params in Next.js 16)
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const post = await db.posts.findUnique({ where: { id } })
return { title: post.title, description: post.excerpt }
}typescript
// 静态metadata
export const metadata: Metadata = {
title: '我的博客',
description: '关于Next.js的博客',
openGraph: { title: '我的博客', images: ['/og-image.jpg'] },
}
// 动态metadata(Next.js 16中需await params)
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const post = await db.posts.findUnique({ where: { id } })
return { title: post.title, description: post.excerpt }
}Image & Font Optimization
图片与字体优化
typescript
// next/image
import Image from 'next/image'
<Image src="/profile.jpg" alt="Profile" width={500} height={500} priority />
// next/font
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
<html className={inter.variable}>Remote images: Configure in .
images.remotePatternsnext.config.tstypescript
// next/image
import Image from 'next/image'
<Image src="/profile.jpg" alt="头像" width={500} height={500} priority />
// next/font
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
<html className={inter.variable}>远程图片: 在中配置。
next.config.tsimages.remotePatternsTop 5 Critical Errors
Top 5 关键错误
Error 1: params
is a Promise
params错误1: params
是Promise
paramsError:
Type 'Promise<{ id: string }>' is not assignable to type '{ id: string }'Solution: Await params in Next.js 16:
typescript
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
}错误信息:
Type 'Promise<{ id: string }>' is not assignable to type '{ id: string }'解决方案: 在Next.js 16中await params:
typescript
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
}Error 2: middleware.ts
is deprecated
middleware.ts错误2: middleware.ts
已废弃
middleware.tsWarning:
middleware.ts is deprecated. Use proxy.ts instead.Solution: Rename file and function:
typescript
// Rename: middleware.ts → proxy.ts
// Rename function: middleware → proxy
export function proxy(request: NextRequest) {
// Same logic
}警告信息:
middleware.ts is deprecated. Use proxy.ts instead.解决方案: 重命名文件和函数:
typescript
// 重命名: middleware.ts → proxy.ts
// 重命名函数: middleware → proxy
export function proxy(request: NextRequest) {
// 逻辑保持不变
}Error 3: Parallel route missing default.js
default.js错误3: 并行路由缺少default.js
default.jsError:
Parallel route @modal was matched but no default.js was foundSolution: Add default.tsx:
typescript
// app/@modal/default.tsx
export default function ModalDefault() {
return null
}错误信息:
Parallel route @modal was matched but no default.js was found解决方案: 添加default.tsx:
typescript
// app/@modal/default.tsx
export default function ModalDefault() {
return null
}Error 4: Cannot use React hooks in Server Component
错误4: 无法在Server Component中使用React钩子
Error:
You're importing a component that needs useState. It only works in a Client ComponentSolution: Add :
'use client'typescript
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}错误信息:
You're importing a component that needs useState. It only works in a Client Component解决方案: 添加:
'use client'typescript
'use client'
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}Error 5: fetch()
not caching
fetch()错误5: fetch()
未缓存
fetch()Cause: Next.js 16 uses opt-in caching with .
"use cache"Solution: Add directive:
"use cache"typescript
'use cache'
export async function getPosts() {
const response = await fetch('/api/posts')
return response.json()
}See All 18 Errors:
references/error-catalog.md原因: Next.js 16使用手动开启缓存。
"use cache"解决方案: 添加指令:
"use cache"typescript
'use cache'
export async function getPosts() {
const response = await fetch('/api/posts')
return response.json()
}查看全部18个错误:
references/error-catalog.mdPerformance Patterns
性能优化实践
| Pattern | Usage |
|---|---|
| Lazy Loading | |
| Code Splitting | Automatic per route - each |
| Turbopack | Default in Next.js 16, opt out with |
| PPR | |
| 模式 | 使用方式 |
|---|---|
| 懒加载 | |
| 代码分割 | 按路由自动分割 - 每个 |
| Turbopack | Next.js 16默认使用,通过 |
| PPR | |
TypeScript Configuration
TypeScript 配置
json
{
"compilerOptions": {
"strict": true,
"baseUrl": ".",
"paths": { "@/*": ["./*"] }
}
}json
{
"compilerOptions": {
"strict": true,
"baseUrl": ".",
"paths": { "@/*": ["./*"] }
}
}When to Load References
何时加载参考文档
| Reference | Load When... |
|---|---|
| Migrating from Next.js 15, async params errors, proxy.ts setup |
| Error handling, optimistic updates, file uploads, advanced forms |
| ISR, tag-based revalidation, updateTag(), refresh(), PPR details |
| Debugging any Next.js error, comprehensive error solutions |
| Quick fixes for the 5 most common Next.js errors |
| 参考文档 | 加载时机... |
|---|---|
| 从Next.js 15迁移、遇到异步参数错误、配置proxy.ts时 |
| 处理错误、乐观更新、文件上传、进阶表单时 |
| 处理ISR、基于标签的重新验证、updateTag()、refresh()、PPR细节时 |
| 调试任何Next.js错误、获取全面错误解决方案时 |
| 获取5个最常见Next.js错误的快速修复时 |
Bundled Resources
内置资源
| Type | Files |
|---|---|
| References | |
| Templates | |
| 类型 | 文件 |
|---|---|
| 参考文档 | |
| 模板 | |
Related Skills
相关技能
| Skill | Purpose |
|---|---|
| Deploy to Cloudflare Workers |
| Styling |
| Authentication |
| Database |
| Forms |
| Client state |
Official Docs: https://nextjs.org/docs | App Router: https://nextjs.org/docs/app
Version: Next.js 16.0.0 | React 19.2.0 | Node.js 20.9+ | TypeScript 5.3+
Production Tested: E-commerce, SaaS, content sites | Token Savings: 65-70%
| 技能 | 用途 |
|---|---|
| 部署到Cloudflare Workers |
| 样式处理 |
| 认证功能 |
| 数据库集成 |
| 表单处理 |
| 客户端状态管理 |
官方文档: https://nextjs.org/docs | App Router: https://nextjs.org/docs/app
版本: Next.js 16.0.0 | React 19.2.0 | Node.js 20.9+ | TypeScript 5.3+
生产环境验证: 电商、SaaS、内容站点 | Token节省: 65-70%