Next.js 16 啟動盤
Next.js 16:Turbopack 為預設(建置速度提升 2-5 倍)、快取元件('use cache')以及用於明確控制的 proxy.ts。
使用時機
✅ Next.js 16、Turbopack、快取元件、proxy 遷移、App Router、React 19.2
❌ Pages Router、Next.js ≤15、一般 React 問題
需求
| 工具 | 版本 |
|---|---|
| Node.js | 20.9.0+ |
| TypeScript | 5.1.0+ |
| React | 19.2+ |
快速開始
# 新專案
npx create-next-app@latest my-app
# 升級現有專案
npx @next/codemod@canary upgrade latest
npm install next@latest react@latest react-dom@latest
建議使用:TypeScript、ESLint、Tailwind、App Router、Turbopack、@/* 別名。
最小設定
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
// app/page.tsx
export default function Page() {
return <h1>Hello, Next.js 16!</h1>
}
配置
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
reactCompiler: true,
}
export default nextConfig
v15 → v16 變更
| v15 | v16 |
|---|---|
experimental.turbopack | 預設 |
experimental.ppr | cacheComponents |
middleware.ts (Edge) | proxy.ts (Node) |
同步 params | await params |
核心模式
1. 伺服器元件(預設)
export default async function BlogPage() {
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
return <PostList posts={posts} />
}
2. 快取元件
import { cacheLife } from 'next/cache'
export default async function BlogPage() {
'use cache'
cacheLife('hours')
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
return <PostList posts={posts} />
}
3. 客戶端元件
'use client'
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
)
}
4. Proxy 邊界
// app/proxy.ts
export function proxy(request: NextRequest) {
if (!request.cookies.get('auth') && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
5. 快取標籤 + 伺服器動作
// app/blog/page.tsx
'use cache'
cacheLife('hours')
cacheTag('blog-posts')
export default async function BlogList() {
const posts = await db.posts.findMany()
return <PostList posts={posts} />
}
// app/actions.ts
'use server'
import { updateTag } from 'next/cache'
export async function createPost(data: PostData) {
await db.posts.create(data)
updateTag('blog-posts')
}
6. 使用 Suspense 進行串流
export default function Dashboard() {
return (
<div>
<Suspense fallback={<Skeleton />}>
<RevenueCard />
</Suspense>
<Suspense fallback={<Skeleton />}>
<UsersCard />
</Suspense>
</div>
)
}
async function RevenueCard() {
const data = await db.analytics.revenue()
return <div>{data}</div>
}
關鍵概念
- Turbopack - Rust 打包工具、增量編譯、快速重新整理
- 伺服器元件 - 在
app/目錄下為預設、零客戶端 JavaScript - 客戶端元件 -
'use client'、Hooks、瀏覽器 API - 快取元件 -
'use cache'+cacheLife()實現 PPR - Proxy 邊界 - 用於驗證/重寫/重新導向的
proxy.ts - 部分預渲染 - 靜態 Shell + 動態串流
遷移檢查清單
-
非同步請求 API
npx @next/codemod@canary async-request-api更新:
const { slug } = await params -
middleware.ts → proxy.ts
- 重新命名檔案,匯出
proxy - 僅限 Node 執行時期(非 Edge)
- 重新命名檔案,匯出
-
配置更新
- 移除
experimental.*標誌 - 啟用
cacheComponents、reactCompiler - 移除
serverRuntimeConfig/publicRuntimeConfig
- 移除
-
快取元件
- 將
experimental.ppr替換為cacheComponents: true - 使用
<Suspense>包裝動態區段
- 將
-
圖片
- 為查詢字串配置
images.localPatterns
- 為查詢字串配置
完整指南請參閱 references/nextjs16-migration-playbook.md。
常見陷阱
❌ 在快取元件中混用執行時期 API(cookies()、headers())
❌ 啟用快取元件時缺少 <Suspense>
❌ 在 Turbopack 中使用 Tilde Sass 匯入
❌ 在 Edge 執行時期執行 proxy.ts
✅ 先讀取 cookies/headers,並將其作為 props 傳遞給快取元件
✅ 使用 <Suspense> 包裝動態子元件
✅ 使用標準的 Sass 匯入
✅ 為 proxy 使用 Node 執行時期
決策指南
啟用快取元件? → 靜態或半靜態內容:是 → 完全動態的儀表板:否
驗證邏輯放在哪裡?
→ 跨路由檢查:proxy.ts
→ API 特定邏輯:路由處理器
何時使用 'use client'?
→ 僅當你需要 Hooks、狀態或瀏覽器 API 時
→ 保持展示性元件在伺服器端
生產模式
電子商務
// 產品頁面搭配串流
export default async function Product({ params }) {
const { id } = await params
const product = await db.products.findById(id)
return (
<>
<ProductInfo product={product} />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={id} />
</Suspense>
</>
)
}
已驗證的儀表板
// proxy.ts
export function proxy(request: NextRequest) {
const session = request.cookies.get('session')
if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
}
更多藍圖請參閱 references/nextjs16-advanced-patterns.md。
效能
- 保持 Turbopack 啟用(僅在必要時使用
--webpack退出) - 使用
Promise.all並行化 fetch - 使用
<Suspense>作為串流邊界 - 為大型儲存庫啟用檔案系統快取
安全性
- 使用
server-only套件 + React Taint API - 將驗證邏輯保留在
proxy.ts中 - 在伺服器動作中驗證輸入
- 使用
NEXT_PUBLIC_前綴區分環境變數 - 在快取範圍之前提取 cookies/headers
部署
- Vercel:零配置
- Docker/Node:
output: 'standalone' - 監控建置時間(預期速度提升 2-5 倍)
- 配置快取生命週期以匹配 CDN
參考檔案
- references/nextjs16-reference.md - 安裝/配置/檢查清單
- references/nextjs16-migration-playbook.md - 使用 codemod 的遷移指南
- references/nextjs16-advanced-patterns.md - 串流、快取、驗證模式
- references/NEXTJS_16_COMPLETE_GUIDE.md - 完整文件
- scripts/bootstrap-nextjs16.ps1 - 自動化設定腳本
- assets/app-router-starter/ - 參考實作
資源
版本: 1.1.0 | 更新日期: 2025-12-27