nextjs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Next.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
    "use cache"
    directive (NEW in Next.js 16)
  • New caching APIs:
    revalidateTag()
    ,
    updateTag()
    ,
    refresh()
    (Updated in Next.js 16)
  • Migration from Next.js 15 to 16 (async params, proxy.ts, parallel routes)
  • Route Handlers (API endpoints, webhooks, streaming responses)
  • Proxy patterns (
    proxy.ts
    replaces
    middleware.ts
    in Next.js 16)
  • Async route params (
    params
    ,
    searchParams
    ,
    cookies()
    ,
    headers()
    now async)
  • Parallel routes with default.js (breaking change in Next.js 16)
  • React 19.2 features (View Transitions,
    useEffectEvent()
    , React Compiler)
  • Metadata API (SEO, Open Graph, Twitter Cards, sitemaps)
  • Image optimization (
    next/image
    with updated defaults in Next.js 16)
  • Performance optimization (lazy loading, code splitting, PPR, ISR)
在以下场景中使用本技能:
  • Next.js 16 App Router 实践模式(布局、加载状态、错误边界、路由)
  • Server Components 最佳实践(数据获取、组件组合、流式渲染)
  • Server Actions 实践模式(表单处理、数据变更、重新验证、错误处理)
  • 带有
    "use cache"
    指令的Cache Components(Next.js 16 新增特性)
  • 新缓存API
    revalidateTag()
    updateTag()
    refresh()
    (Next.js 16 更新)
  • 从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、
    useEffectEvent()
    、React Compiler)
  • 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
    cloudflare-nextjs
    skill instead
  • Pages Router patterns → This skill covers App Router ONLY (Pages Router is legacy)
  • Authentication libraries → Use
    clerk-auth
    ,
    auth-js
    , or other auth-specific skills
  • Database integration → Use
    cloudflare-d1
    ,
    drizzle-orm-d1
    , or database-specific skills
  • UI component libraries → Use
    tailwind-v4-shadcn
    skill for Tailwind + shadcn/ui
  • State management → Use
    zustand-state-management
    ,
    tanstack-query
    skills
  • Form libraries → Use
    react-hook-form-zod
    skill

请勿在以下场景使用本技能:
  • Cloudflare Workers部署 → 请使用
    cloudflare-nextjs
    技能
  • Pages Router实践模式 → 本技能仅覆盖App Router(Pages Router已属 legacy)
  • 认证库 → 请使用
    clerk-auth
    auth-js
    或其他认证专属技能
  • 数据库集成 → 请使用
    cloudflare-d1
    drizzle-orm-d1
    或数据库专属技能
  • UI组件库 → 请使用
    tailwind-v4-shadcn
    技能处理Tailwind + shadcn/ui
  • 状态管理 → 请使用
    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 ChangeBeforeAfter
Async params
params.slug
const { slug } = await params
Async headers
cookies()
sync
await cookies()
Middleware
middleware.ts
proxy.ts
(renamed)
Parallel routes
default.js
optional
default.js
required
CachingAuto-cached fetchOpt-in with
"use cache"
revalidateTag()1 argument2 arguments (tag + cacheLife)
Node.js18.x+20.9+ required
React18.x19.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 latest
See:
references/next-16-migration-guide.md
for complete migration guide with examples.

重要提示:Next.js 16存在多项破坏性变更。详细迁移步骤请查看
references/next-16-migration-guide.md
破坏性变更之前的写法之后的写法
异步参数
params.slug
const { slug } = await params
异步headers
cookies()
同步调用
await cookies()
中间件
middleware.ts
proxy.ts
(重命名)
并行路由
default.js
可选
default.js
必填
缓存机制自动缓存fetch请求通过
"use cache"
手动开启
revalidateTag()1个参数2个参数(tag + cacheLife)
Node.js版本18.x+20.9+ 必填
React版本18.x19.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.md
获取包含示例的完整迁移指南。

Cache 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汇总

APIPurposeExample
"use cache"
Opt-in component/function caching
'use cache'
at top
revalidateTag()
Invalidate by tag
revalidateTag('posts', 'max')
updateTag()
Update cache without revalidation
updateTag('posts', newData)
refresh()
Refresh current page
refresh()
revalidatePath()
Invalidate by path
revalidatePath('/posts')
API用途示例
"use cache"
手动开启组件/函数缓存在顶部添加
'use cache'
revalidateTag()
按标签失效缓存
revalidateTag('posts', 'max')
updateTag()
更新缓存无需重新验证
updateTag('posts', newData)
refresh()
刷新当前页面
refresh()
revalidatePath()
按路径失效缓存
revalidatePath('/posts')

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:
references/caching-apis.md
for complete caching API reference with ISR, tag-based revalidation, and advanced patterns.

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>
    </>
  )
}
参考:
references/caching-apis.md
获取包含ISR、基于标签的重新验证和进阶模式的完整缓存API参考。

Server 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 ComponentsClient Components
Data fetching, DB accessInteractivity (onClick)
Sensitive logicReact hooks (useState)
Large dependenciesBrowser APIs
Static contentReal-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 ComponentsClient 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

可用实践模式

PatternUse CaseReference
Client Form with LoadinguseFormState + useFormStatus
templates/server-action-form.tsx
Error HandlingReturn { error } or { success }
references/server-actions-patterns.md
Optimistic UpdatesuseOptimistic hook
references/server-actions-patterns.md
File UploadFormData + blob storage
references/server-actions-patterns.md
Redirect After Actionredirect() function
references/server-actions-patterns.md
See:
references/server-actions-patterns.md
for error handling, optimistic updates, file uploads, and advanced patterns.

模式使用场景参考
带加载状态的客户端表单useFormState + useFormStatus
templates/server-action-form.tsx
错误处理返回{ error }或{ success }
references/server-actions-patterns.md
乐观更新useOptimistic钩子
references/server-actions-patterns.md
文件上传FormData + blob存储
references/server-actions-patterns.md
操作后重定向redirect()函数
references/server-actions-patterns.md
参考:
references/server-actions-patterns.md
获取错误处理、乐观更新、文件上传和进阶模式的内容。

Route 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:
templates/route-handler-api.ts
for search params, webhooks, and streaming patterns.

Route 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 })
}
参考:
templates/route-handler-api.ts
获取搜索参数、Webhooks和流式响应模式。

React 19.2 Features

React 19.2 特性

FeatureUsage
React Compiler
experimental: { reactCompiler: true }
- Auto-memoization
View Transitions
useTransition()
+
router.push()
useEffectEventStable event handlers without deps

特性使用方式
React Compiler
experimental: { reactCompiler: true }
- 自动记忆化
View Transitions
useTransition()
+
router.push()
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
images.remotePatterns
in
next.config.ts
.

typescript
// 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.ts
中配置
images.remotePatterns

Top 5 Critical Errors

Top 5 关键错误

Error 1:
params
is a Promise

错误1:
params
是Promise

Error:
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

错误2:
middleware.ts
已废弃

Warning:
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

错误3: 并行路由缺少
default.js

Error:
Parallel route @modal was matched but no default.js was found
Solution: 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 Component
Solution: 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

错误5:
fetch()
未缓存

Cause: Next.js 16 uses opt-in caching with
"use cache"
.
Solution: Add
"use cache"
directive:
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.md

Performance Patterns

性能优化实践

PatternUsage
Lazy Loading
const HeavyComp = dynamic(() => import('./Heavy'), { ssr: false })
Code SplittingAutomatic per route - each
page.tsx
gets own bundle
TurbopackDefault in Next.js 16, opt out with
--webpack
flag
PPR
experimental: { ppr: true }
+
<Suspense>
boundaries

模式使用方式
懒加载
const HeavyComp = dynamic(() => import('./Heavy'), { ssr: false })
代码分割按路由自动分割 - 每个
page.tsx
拥有独立打包文件
TurbopackNext.js 16默认使用,通过
--webpack
标志可切换回Webpack
PPR
experimental: { ppr: true }
+
<Suspense>
边界

TypeScript Configuration

TypeScript 配置

json
{
  "compilerOptions": {
    "strict": true,
    "baseUrl": ".",
    "paths": { "@/*": ["./*"] }
  }
}

json
{
  "compilerOptions": {
    "strict": true,
    "baseUrl": ".",
    "paths": { "@/*": ["./*"] }
  }
}

When to Load References

何时加载参考文档

ReferenceLoad When...
next-16-migration-guide.md
Migrating from Next.js 15, async params errors, proxy.ts setup
server-actions-patterns.md
Error handling, optimistic updates, file uploads, advanced forms
caching-apis.md
ISR, tag-based revalidation, updateTag(), refresh(), PPR details
error-catalog.md
Debugging any Next.js error, comprehensive error solutions
top-errors.md
Quick fixes for the 5 most common Next.js errors

参考文档加载时机...
next-16-migration-guide.md
从Next.js 15迁移、遇到异步参数错误、配置proxy.ts时
server-actions-patterns.md
处理错误、乐观更新、文件上传、进阶表单时
caching-apis.md
处理ISR、基于标签的重新验证、updateTag()、refresh()、PPR细节时
error-catalog.md
调试任何Next.js错误、获取全面错误解决方案时
top-errors.md
获取5个最常见Next.js错误的快速修复时

Bundled Resources

内置资源

TypeFiles
References
error-catalog.md
,
top-errors.md
,
next-16-migration-guide.md
,
server-actions-patterns.md
,
caching-apis.md
Templates
async-params-page.tsx
,
server-action-form.tsx
,
route-handler-api.ts
,
cache-component-use-cache.tsx
,
parallel-routes-with-default.tsx
,
proxy-migration.ts

类型文件
参考文档
error-catalog.md
,
top-errors.md
,
next-16-migration-guide.md
,
server-actions-patterns.md
,
caching-apis.md
模板
async-params-page.tsx
,
server-action-form.tsx
,
route-handler-api.ts
,
cache-component-use-cache.tsx
,
parallel-routes-with-default.tsx
,
proxy-migration.ts

Related Skills

相关技能

SkillPurpose
cloudflare-nextjs
Deploy to Cloudflare Workers
tailwind-v4-shadcn
Styling
clerk-auth
Authentication
drizzle-orm-d1
Database
react-hook-form-zod
Forms
zustand-state-management
Client state

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-nextjs
部署到Cloudflare Workers
tailwind-v4-shadcn
样式处理
clerk-auth
认证功能
drizzle-orm-d1
数据库集成
react-hook-form-zod
表单处理
zustand-state-management
客户端状态管理

版本: Next.js 16.0.0 | React 19.2.0 | Node.js 20.9+ | TypeScript 5.3+ 生产环境验证: 电商、SaaS、内容站点 | Token节省: 65-70%