如何升级到 16 版本
将你的 Next.js 应用从 15 版本升级到 16 版本。
使用编码代理(推荐)
在应用目录下运行最新的升级 CLI:
npx next@canary upgrade --agent=latest
该 CLI 会为代理准备好 Next.js 16 迁移指南和 codemod 命令,然后要求它应用更改并验证应用。详情请参阅使用编码代理升级。
或者手动升级
手动升级需要按顺序执行以下几个步骤:
- 如果你现在使用编码代理,或希望未来的代理工作基于版本匹配的文档,请设置 AI 代理文档。
- 运行升级 codemod。
- 如果你不想运行 codemod,可以手动安装依赖包。
- 继续处理下面的破坏性变更,运行相关检查,并修复任何遗留问题。
设置 AI 代理文档
在升级之前,将 AGENTS.md 指向版本匹配的 Next.js 文档,以便编码代理协助完成后续步骤:
npx @next/codemod@canary agents-md
升级后,检查 AGENTS.md 是否指向 node_modules/next/dist/docs/ 中随已安装版本一起提供的文档。在 Next.js 16.2 及更高版本中,next dev 在检测到编码代理时会保持该区块为最新状态。如果该设置将文档下载到了 .next-docs/,请在没有内容引用它之后删除该目录。有关受管理区块和设置详情,请参阅版本匹配的文档。
使用 codemod
要更新到 Next.js 16 版本,你可以使用 upgrade codemod:
pnpm
pnpm dlx @next/codemod@canary upgrade latest
npm
npx @next/codemod@canary upgrade latest
yarn
yarn dlx @next/codemod@canary upgrade latest
bun
bunx @next/codemod@canary upgrade latest
该 codemod 能够:
- 更新
next.config.js以使用新的turbopack配置 - 从
next lint迁移到 ESLint CLI - 从已弃用的
middleware约定迁移到proxy - 从已稳定的 API 中移除
unstable_前缀 - 从页面和布局中移除
experimental_ppr路由段配置
upgrade codemod 并不会运行所有迁移 codemod。如果你的应用仍在从 Next.js 15 兼容期使用同步的 params、searchParams、cookies()、headers() 或 draftMode() 访问,请同时运行异步 Request API codemod:
npx @next/codemod@canary next-async-request-api .
手动安装包
如果你希望手动操作,请安装最新版本的 Next.js 和 React:
pnpm
pnpm add next@latest react@latest react-dom@latest
npm
npm install next@latest react@latest react-dom@latest
yarn
yarn add next@latest react@latest react-dom@latest
bun
bun add next@latest react@latest react-dom@latest
如果你使用 TypeScript,请确保同时将 @types/react 和 @types/react-dom 升级到最新版本。
Node.js 运行时与浏览器支持
| 要求 | 变更 / 详情 |
|---|---|
| Node.js 20.9+ | 最低版本现为 20.9.0(LTS);不再支持 Node.js 18 |
| TypeScript 5+ | 最低版本现为 5.1.0 |
| 浏览器 | Chrome 111+、Edge 111+、Firefox 111+、Safari 16.4+ |
默认使用 Turbopack
从 Next.js 16 开始,Turbopack 已稳定,并在 next dev 和 next build 中默认使用
此前你需要使用 --turbopack 或 --turbo 来启用 Turbopack。
{
"scripts": {
"dev": "next dev --turbopack",
"build": "next build --turbopack",
"start": "next start"
}
}
现在不再需要这样做了。你可以更新你的 package.json 脚本:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
}
}
如果你的项目有自定义 webpack 配置,并且你运行 next build(它现在默认使用 Turbopack),构建将失败,以防止出现配置错误问题。
你有几种不同的方式来处理这个问题:
- 仍然使用 Turbopack:使用
next build --turbopack运行,以 Turbopack 进行构建并忽略你的webpack配置。 - 完全切换到 Turbopack:将你的
webpack配置迁移为 Turbopack 兼容的选项。 - 继续使用 Webpack:使用
--webpack标志退出 Turbopack,并使用 Webpack 进行构建。
须知:
如果你因为检测到
webpack配置而出现构建失败,但你自己并没有定义该配置,那么很可能是某个插件添加了webpack选项
退出 Turbopack
如果你需要继续使用 Webpack,可以使用 --webpack 标志退出。例如,在开发中使用 Turbopack,而在生产构建中使用 Webpack:
{
"scripts": {
"dev": "next dev",
"build": "next build --webpack",
"start": "next start"
}
}
我们建议在开发和生产中都使用 Turbopack。如果你无法切换到 Turbopack,请在这个讨论帖中提交评论。
Turbopack 配置的位置
experimental.turbopack 配置已不再是实验性的。
import type { NextConfig } from 'next'
// Next.js 15 - experimental.turbopack
const nextConfig: NextConfig = {
experimental: {
turbopack: {
// options
},
},
}
export default nextConfig
你可以将其作为顶层的 turbopack 选项使用:
import type { NextConfig } from 'next'
// Next.js 16 - turbopack at the top level of nextConfig
const nextConfig: NextConfig = {
turbopack: {
// options
},
}
export default nextConfig
请务必查看 Turbopack 配置的选项。Next.js 16 引入了各种改进和新选项,例如:
解析别名回退
在某些项目中,客户端代码可能会导入包含 Node.js 原生模块的文件。这会导致 Module not found: Can't resolve 'fs' 类型的错误。
出现这种情况时,你应该重构代码,使客户端 bundle 不再引用这些 Node.js 原生模块。
然而,在某些情况下这可能无法做到。在 Webpack 中,通常会使用 resolve.fallback 选项来消除该错误。Turbopack 提供了类似的选项,使用 turbopack.resolveAlias。在这种情况下,让 Turbopack 在浏览器请求 fs 时加载一个空模块。
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
resolveAlias: {
fs: {
browser: './empty.ts', // We recommend to fix code imports before using this method
},
},
},
}
export default nextConfig
最好重构你的模块,使客户端代码永远不会从使用 Node.js 原生模块的模块中导入。
Sass 的 node_modules 导入
Turbopack 完全支持从 node_modules 导入 Sass 文件。请注意,虽然 Webpack 允许使用旧式的波浪号(~)前缀,但 Turbopack 不支持这种语法。
在 Webpack 中:
@import '~bootstrap/dist/css/bootstrap.min.css';
在 Turbopack 中:
@import 'bootstrap/dist/css/bootstrap.min.css';
如果无法更改导入,你可以使用 turbopack.resolveAlias。例如:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
resolveAlias: {
'~*': '*',
},
},
}
export default nextConfig
Turbopack 文件系统缓存
Turbopack 会在多次运行之间将编译器产物存储到磁盘,从而在重启后显著加快编译速度。对于 next dev 和 next build,通过 experimental.turbopackFileSystemCacheForDev 和 experimental.turbopackFileSystemCacheForBuild,文件系统缓存默认启用。请参阅 Turbopack 文件系统缓存 来配置或禁用其中任一缓存。
异步请求 API(破坏性变更)
版本 15 引入了 异步请求 API 作为破坏性变更,并提供了临时的同步兼容性。
从 Next.js 16 开始,同步访问已被完全移除。这些 API 只能以异步方式访问。
cookiesheadersdraftModeparams在layout.js、page.js、route.js、default.js、opengraph-image、twitter-image、icon和apple-icon中。searchParams在page.js中
使用 codemod 迁移到异步的请求时 API。
迁移异步请求时 API 的类型
为了帮助迁移到异步的 params 和 searchParams,你可以运行 npx next typegen 来自动生成这些全局可用的类型辅助工具:
须知:
typegen在 Next.js 15.5 中引入
这简化了向新的异步 API 模式的类型安全迁移,并让你能在完全类型安全的情况下更新组件,例如:
export default async function Page(props: PageProps<'/blog/[slug]'>) {
const { slug } = await props.params
const query = await props.searchParams
return <h1>Blog Post: {slug}</h1>
}
这种方法让你可以直接在页面中完全类型安全地访问 props.params(包括 slug)以及 searchParams。
icon 和 open-graph Image 的异步参数(破坏性变更)
在
opengraph-image、twitter-image、icon和apple-icon中传递给图像生成函数的 props 现在都是 Promise。
在之前的版本中,Image(图像生成函数)和 generateImageMetadata 都会接收一个 params 对象。由 generateImageMetadata 返回的 id 会以字符串形式传递给图像生成函数。
// Next.js 15 - synchronous params access
export function generateImageMetadata({ params }) {
const { slug } = params
return [{ id: '1' }, { id: '2' }]
}
// Next.js 15 - synchronous params and id access
export default function Image({ params, id }) {
const slug = params.slug
const imageId = id // string
// ...
}
从 Next.js 16 开始,为了与 异步请求 API 变更保持一致,图像生成函数现在以 Promise 形式接收 params 和 id。generateImageMetadata 函数仍接收同步的 params。
export async function generateImageMetadata({ params }) {
const { slug } = params
return [{ id: '1' }, { id: '2' }]
}
// Next.js 16 - asynchronous params and id access
export default async function Image({ params, id }) {
const { slug } = await params // params now async
const imageId = await id // id is now Promise<string> when using generateImageMetadata
// ...
}
sitemap 的异步 id 参数(破坏性变更)
此前,从 generateSitemaps 返回的 id 值会直接传递给 sitemap 生成函数。
export async function generateSitemaps() {
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
// Next.js 15 - synchronous id access
export default async function sitemap({ id }) {
const start = id * 50000 // id is a number
// ...
}
从 Next.js 16 开始,sitemap 生成函数现在以 Promise 形式接收 id。
export async function generateSitemaps() {
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
// Next.js 16 - asynchronous id access
export default async function sitemap({ id }) {
const resolvedId = await id // id is now Promise<string>
const start = Number(resolvedId) * 50000
// ...
}
React 19.2
Next.js 16 中的 App Router 使用最新的 React Canary 版本,其中包含最新发布的 React 19.2 功能以及其他正在逐步稳定的功能。亮点包括:
- View Transitions:为在 Transition 或导航过程中更新的元素添加动画
useEffectEvent:将非响应式逻辑从 Effect 中提取为可复用的 Effect Event 函数- Activity:通过使用
display: none隐藏 UI 来渲染“后台活动”,同时保持状态并清理 Effect
在 React 19.2 公告中了解更多。
React Compiler 支持
随着 React Compiler 发布 1.0 版本,Next.js 16 中对 React Compiler 的内置支持现已稳定。React Compiler 会自动对组件进行记忆化,无需任何手动代码更改即可减少不必要的重新渲染。
reactCompiler 配置项已从 experimental 提升为稳定状态。由于我们仍在收集不同应用类型的构建性能数据,该选项默认未启用。
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: true,
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: true,
}
module.exports = nextConfig
安装最新版本的 React Compiler 插件:
pnpm
pnpm add -D babel-plugin-react-compiler
npm
npm install -D babel-plugin-react-compiler
yarn
yarn add -D babel-plugin-react-compiler
bun
bun add -D babel-plugin-react-compiler
须知:
启用此选项后,开发和构建期间的编译时间预计会更长,因为 React Compiler 依赖于 Babel。
缓存 API
revalidateTag
revalidateTag 现在需要第二个参数来指定 cacheLife 配置文件。单参数形式已弃用,并将产生 TypeScript 错误。
// Before
revalidateTag('posts')
// After
revalidateTag('posts', 'max')
如果你需要立即过期而不是 stale-while-revalidate,请改用服务器操作中的 updateTag。这还能保留客户端刷新。
TypeScript
'use server'
import { revalidateTag } from 'next/cache'
export async function updateArticle(articleId: string) {
// Mark article data as stale - article readers see stale data while it revalidates
revalidateTag(`article-${articleId}`, 'max')
}
JavaScript
'use server'
import { revalidateTag } from 'next/cache'
export async function updateArticle(articleId) {
// Mark article data as stale - article readers see stale data while it revalidates
revalidateTag(`article-${articleId}`, 'max')
}
对于更新稍有延迟也可接受的内容(例如博客文章、产品目录或文档),请使用 revalidateTag。用户在后台加载新数据期间会收到陈旧内容。
updateTag
updateTag 是一个仅用于 Server Actions 的新 API,提供 read-your-writes 语义,即用户做出更改后,UI 会立即显示该更改,而不是过时的数据。
它通过在同一请求内使数据过期并立即刷新来实现这一点。
TypeScript
'use server'
import { updateTag } from 'next/cache'
export async function updateUserProfile(userId: string, profile: Profile) {
await db.users.update(userId, profile)
// Expire cache and refresh immediately - user sees their changes right away
updateTag(`user-${userId}`)
}
JavaScript
'use server'
import { updateTag } from 'next/cache'
export async function updateUserProfile(userId, profile) {
await db.users.update(userId, profile)
// Expire cache and refresh immediately - user sees their changes right away
updateTag(`user-${userId}`)
}
这确保交互式功能立即反映更改。非常适合表单、用户设置以及任何用户期望立即看到更新的工作流。
在此处了解有关何时使用 updateTag 或 revalidateTag 的更多信息。
refresh
refresh 允许你在服务器操作中刷新客户端路由器。
TypeScript
'use server'
import { refresh } from 'next/cache'
export async function markNotificationAsRead(notificationId: string) {
// Update the notification in the database
await db.notifications.markAsRead(notificationId)
// Refresh the notification count displayed in the header
refresh()
}
JavaScript
'use server'
import { refresh } from 'next/cache'
export async function markNotificationAsRead(notificationId) {
// Update the notification in the database
await db.notifications.markAsRead(notificationId)
// Refresh the notification count displayed in the header
refresh()
}
当你需要在执行操作后刷新客户端路由器时使用它。
cacheLife 和 cacheTag
cacheLife 和 cacheTag 现已稳定。不再需要 unstable_ 前缀。
无论你在何处使用了如下别名导入:
import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
} from 'next/cache'
你可以将导入更新为:
import { cacheLife, cacheTag } from 'next/cache'
增强的路由与导航
Next.js 16 对路由和导航系统进行了全面改造,使页面过渡更精简、更快速。这优化了 Next.js 预取和缓存导航数据的方式:
- 布局去重:当预取多个共享布局的 URL 时,布局只会下载一次。
- 增量预取:Next.js 只预取尚未缓存的部分,而不是整个页面。
这些更改无需修改代码,旨在提升所有应用的性能。
不过,你可能会看到更多单独的预取请求,但总传输大小要低得多。我们认为对于几乎所有应用来说,这都是正确的取舍。
如果请求数量增加导致了问题,请通过创建 issue 或 discussion 条目来告知我们。
部分预渲染(PPR)
Next.js 16 移除了实验性的 部分预渲染(PPR) 标志和配置选项,包括路由级段 experimental_ppr。
从 Next.js 16 开始,你可以使用 cacheComponents 配置选择启用 PPR。
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
Next.js 16 中的 PPR 与 Next.js 15 canary 版本中的工作方式不同。如果你目前正在使用 PPR,请继续使用你当前使用的 Next.js 15 canary 版本。迁移模式请参阅迁移到缓存组件。
/** @type {import('next').NextConfig} */
const nextConfig = {
// If you are using PPR today
// stay in the current Next.js 15 canary
experimental: {
ppr: true,
},
}
module.exports = nextConfig
从 middleware 到 proxy
middleware 文件名已弃用,并已重命名为 proxy,以明确网络边界和路由的关注点。
proxy 中不支持 edge 运行时。proxy 运行时是 nodejs,且无法配置。如果你想继续使用 edge 运行时,请继续使用 middleware。我们将在后续的小版本中提供更多关于 edge 运行时的说明。
# Rename your middleware file
mv middleware.ts proxy.ts
# or
mv middleware.js proxy.js
具名导出 middleware 也已弃用。请将你的函数重命名为 proxy。
TypeScript
export function proxy(request: Request) {}
JavaScript
export function proxy(request) {}
即使你使用的是默认导出,我们也建议将函数名改为 proxy。
包含 middleware 名称的配置标志也已重命名。例如,skipMiddlewareUrlNormalize 现在为 skipProxyUrlNormalize
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
skipProxyUrlNormalize: true,
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
skipProxyUrlNormalize: true,
}
module.exports = nextConfig
版本 16 的 codemod 也能更新这些标志。
next/image 的变更
带查询字符串的本地图片(破坏性变更)
现在,带查询字符串的本地图片来源需要配置 images.localPatterns.search,以防止枚举攻击。
import Image from 'next/image'
export default function Page() {
return <Image src="/assets/photo?v=1" alt="Photo" width="100" height="100" />
}
如果你需要在本地图片中使用查询字符串,请将该模式添加到你的配置中:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '?v=1',
},
],
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '?v=1',
},
],
},
}
module.exports = nextConfig
minimumCacheTTL 默认值(破坏性变更)
images.minimumCacheTTL 的默认值已从 60 seconds 改为 4 hours(14400 秒)。这降低了没有 cache-control 头的图片的重新验证成本。
对于部分 Next.js 用户来说,图片会频繁重新验证,通常是因为上游源图片缺少 cache-control 头。这导致每隔 60 秒就会重新验证,从而增加了 CPU 使用率和成本。
由于大多数图片并不经常变化,如此短的间隔并不理想。将默认值设为 4 小时可默认提供更持久的缓存,同时在需要时仍允许图片每天更新几次。
如果你需要之前的行为,请将 minimumCacheTTL 改为更低的值,例如改回 60 秒:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
minimumCacheTTL: 60,
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
minimumCacheTTL: 60,
},
}
module.exports = nextConfig
imageSizes 默认值(破坏性变更)
16 值已从默认的 images.imageSizes 数组中移除。
我们查阅了请求分析数据,发现很少有项目会提供 16 像素宽度的图片。移除该设置可减小由 next/image 发送到浏览器的 srcset 属性大小。
如果你需要支持 16px 图片:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
module.exports = nextConfig
我们认为 16 像素宽度图片变得不常见,原因并不是开发者不再使用,而是 devicePixelRatio: 2 实际上会获取 32px 的图片,以避免在视网膜显示屏上出现模糊。
qualities 默认值(破坏性变更)
images.qualities 的默认值已从允许所有质量值改为仅允许 [75]。
如果你需要支持多个质量级别:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
qualities: [50, 75, 100],
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
qualities: [50, 75, 100],
},
}
module.exports = nextConfig
如果你指定的 quality 属性不在 images.qualities 数组中,质量值将被强制转换为 images.qualities 中最接近的值。例如,在上述配置下,值为 80 的 quality 属性会被强制转换为 75。
检查自定义图片质量。将所需的值添加到 images.qualities,并测试直接发起的 /_next/image 请求,因为不受支持的 q 值会返回 400。
本地 IP 限制(破坏性变更)
一项新的安全限制默认会阻止本地 IP 优化。仅在私有网络中才将 images.dangerouslyAllowLocalIP 设置为 true。
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
dangerouslyAllowLocalIP: true, // Only for private networks
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
dangerouslyAllowLocalIP: true, // Only for private networks
},
}
module.exports = nextConfig
当你在使用分离式 DNS(split-horizon DNS)的 VPC 中托管 Next.js 并收到 400 Bad Request 状态时,可能需要这样做。只有在了解 SSRF 风险后才启用。
最大重定向次数(破坏性变更)
images.maximumRedirects 的默认值已从无限制改为最多 3 次重定向。
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
maximumRedirects: 0, // Disable redirects
// or
maximumRedirects: 5, // Increase for edge cases
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
maximumRedirects: 0, // Disable redirects
// or
maximumRedirects: 5, // Increase for edge cases
},
}
module.exports = nextConfig
next/legacy/image 组件(已弃用)
next/legacy/image 组件已弃用。请改用 next/image:
// Before
import Image from 'next/legacy/image'
// After
import Image from 'next/image'
images.domains 配置(已弃用)
images.domains 配置已弃用。
// image.domains is deprecated
module.exports = {
images: {
domains: ['example.com'],
},
}
请改用 images.remotePatterns 以提升安全性:
// Use image.remotePatterns instead
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
},
],
},
}
并发运行 dev 与 build
next dev 与 next build 现在使用各自独立的输出目录,因此可以并发执行。next dev 命令会输出到 .next/dev。
此外,锁文件机制可防止在同一项目上同时运行多个 next dev 或 next build 实例。
pnpm
pnpm next internal trace .next-profiles/trace-turbopack.bin
npm
npx next internal trace .next-profiles/trace-turbopack.bin
yarn
yarn next internal trace .next-profiles/trace-turbopack.bin
bun
bunx next internal trace .next-profiles/trace-turbopack.bin
并行路由的 default.js 要求
所有并行路由插槽现在都要求显式的 default.js 文件。缺少这些文件会导致构建失败。
如需保持原有行为,请创建一个default.js 文件,在其中调用 notFound() 或返回 null。
import { notFound } from 'next/navigation'
export default function Default() {
notFound()
}
或返回 null:
export default function Default() {
return null
}
ESLint 扁平配置
@next/eslint-plugin-next 现在默认使用 ESLint 扁平配置格式,与将放弃旧版配置支持的 ESLint v10 保持一致。
请务必查看我们关于 @next/eslint-plugin-next 插件的 API 参考文档。
如果你使用的是旧版 .eslintrc 格式,建议迁移到扁平配置格式。详情请参阅 ESLint 迁移指南。
滚动行为覆盖
在 Next.js 的早期版本中,如果你通过 CSS 在 <html> 元素上全局设置了 scroll-behavior: smooth,Next.js 会在 SPA 路由切换期间覆盖该设置,具体如下:
- 临时将
scroll-behavior设置为auto - 执行导航(导致瞬间滚动到顶部)
- 恢复你原来的
scroll-behavior值
这确保了页面导航始终感觉迅速、即时,即使你为页面内导航启用了平滑滚动也是如此。然而,这种操作可能开销很大,尤其是在每次导航开始时。
在 Next.js 16 中,这一行为已经改变。默认情况下,Next.js 在导航期间不再覆盖你的 scroll-behavior 设置。
如果你希望 Next.js 执行此覆盖(之前的默认行为),请将 data-scroll-behavior="smooth" 属性添加到你的 <html> 元素:
export default function RootLayout({ children }) {
return (
<html lang="en" data-scroll-behavior="smooth">
<body>{children}</body>
</html>
)
}
性能改进
对 next dev 和 next start 命令进行了显著的性能优化,同时改进了终端输出,格式更清晰、错误消息更好,性能指标也有所提升。
Next.js 16 从 next build 输出中移除了 size 和 First Load JS 指标。我们发现,在使用 React 服务器组件的服务器驱动架构中,这些指标并不准确。我们的 Turbopack 和 Webpack 实现都存在问题,并且在如何统计客户端组件负载方面存在分歧。
衡量实际路由性能最有效的方法是通过 Chrome Lighthouse 或 Vercel Analytics 等工具,它们专注于 Core Web Vitals 和下载资源大小。
next dev 配置加载
在之前的版本中,Next 配置文件在开发期间会被加载两次:
- 在运行
next dev命令时 - 当
next dev命令启动 Next.js 服务器时
这很低效,因为 next dev 命令不需要配置文件来启动 Next.js 服务器。
这一变更的一个后果是:在运行 next dev 时,如果在 Next.js 配置文件中检查 process.argv 是否包含 'dev',将返回 false。
须知:
typegen和build命令在process.argv中仍然可见。
这对于在 next dev 上触发副作用的插件尤其重要。如果是这种情况,只需检查 NODE_ENV 是否设置为 development 可能就足够了。
import { startServer } from 'docs-lib/dev-server'
const isDev = process.env.NODE_ENV === 'development'
if (isDev) {
startServer()
}
const nextConfig = {
/* Your config options */
}
module.exports = nextConfig
或者,使用会加载配置的 phase。
构建适配器 API(alpha)
继 Build Adapters RFC 之后,Build Adapters API 的首个 alpha 版本现已可用。
Build Adapters 允许你创建接入构建过程的自定义适配器,使部署平台和自定义构建集成能够修改 Next.js 配置或处理构建输出。
const nextConfig = {
experimental: {
adapterPath: require.resolve('./my-adapter.js'),
},
}
module.exports = nextConfig
adapterPath 在 16.2.0 中已提升为稳定的顶级选项。当前 API 参考请见 adapterPath。
现代 Sass API
sass-loader 已升级至 v16,支持现代 Sass 语法和新特性。
移除项
以下特性此前已弃用,现已移除:
AMP 支持
AMP 的采用率已显著下降,而维护该特性会增加框架的复杂度。所有 AMP API 和配置均已移除:
- Next 配置文件中的
amp配置 next/amphook 的导入与使用(useAmp)
// Removed
import { useAmp } from 'next/amp'
// Removed
export const config = { amp: true }
- 页面中的
export const config = { amp: true }
const nextConfig = {
// Removed
amp: {
canonicalBase: 'https://example.com',
},
}
module.exports = nextConfig
请评估你的使用场景是否仍需要 AMP。如今大部分性能收益都可以通过 Next.js 内置的优化和现代 Web 标准实现。
next lint 命令
next lint 命令已被移除。请直接使用 Biome 或 ESLint。next build 不再运行 lint 检查。
可使用 codemod 自动完成迁移:
pnpm
pnpm dlx @next/codemod@canary next-lint-to-eslint-cli .
npm
npx @next/codemod@canary next-lint-to-eslint-cli .
yarn
yarn dlx @next/codemod@canary next-lint-to-eslint-cli .
bun
bunx @next/codemod@canary next-lint-to-eslint-cli .
Next.js 配置文件中的 eslint 选项也已被移除。
/** @type {import('next').NextConfig} */
const nextConfig = {
// No longer supported
// eslint: {},
}
export default nextConfig
运行时配置
serverRuntimeConfig 和 publicRuntimeConfig 已被移除。请改用环境变量。
之前(Next.js 15):
module.exports = {
serverRuntimeConfig: {
dbUrl: process.env.DATABASE_URL,
},
publicRuntimeConfig: {
apiUrl: '/api',
},
}
import getConfig from 'next/config'
export default function Page() {
const { publicRuntimeConfig } = getConfig()
return <p>API URL: {publicRuntimeConfig.apiUrl}</p>
}
之后(Next.js 16):
对于仅限服务端的值,可直接在服务器组件中访问环境变量:
async function fetchData() {
const dbUrl = process.env.DATABASE_URL
// Use for server-side operations only
return await db.query(dbUrl, 'SELECT * FROM users')
}
export default async function Page() {
const data = await fetchData()
return <div>{/* render data */}</div>
}
须知:
使用 taint API 来防止意外将敏感的服务器端值传递给客户端组件。
对于客户端可访问的值,请使用 NEXT_PUBLIC_ 前缀:
NEXT_PUBLIC_API_URL="/api"
'use client'
export default function ClientComponent() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL
return <p>API URL: {apiUrl}</p>
}
为确保环境变量在运行时读取(而不是在构建时打包),请在从 process.env 读取之前使用 connection() 函数:
import { connection } from 'next/server'
export default async function Page() {
await connection()
const config = process.env.RUNTIME_CONFIG
return <p>{config}</p>
}
了解更多关于环境变量的信息。
devIndicators 选项
以下选项已从 devIndicators 中移除:
appIsrStatusbuildActivitybuildActivityPosition
指示器本身仍然可用。
experimental.dynamicIO 和 experimental.useCache
experimental.dynamicIO 和 experimental.useCache 标志已被移除。
// Before: experimental.useCache
module.exports = {
experimental: {
useCache: true,
},
}
// Before: experimental.dynamicIO
module.exports = {
experimental: {
dynamicIO: true,
},
}
如果你一直在主动使用这些标志,请迁移到顶层的 cacheComponents:
TypeScript
import type { NextConfig } from 'next'
// After
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
JavaScript
// After
module.exports = {
cacheComponents: true,
}
如果你并未主动采用 Cache Components,请改为移除这些标志。启用 cacheComponents 并非只是重命名:它可能会在 <Suspense> 之外暴露出未缓存数据的构建错误,并且需要采用 Cache Components 模型。
完整的迁移路径请参阅迁移到 Cache Components。
unstable_rootParams
unstable_rootParams 函数已被移除。请改用 next/root-params。
Next.js 16 中移除的其他实验性标志
以下实验性标志在后续的 Next.js 16 次要版本中被移除。升级到相应版本时,请从 Next 配置中移除它们。
| 标志 | 版本历史 | 迁移 |
|---|---|---|
experimental.viewTransition |
在 15.2.0 中引入,在 16.3.0 中移除。 | 移除该标志。视图过渡在 App Router 中无需配置即可使用。 |
experimental.appNewScrollHandler |
在 16.2.0 中引入,在 16.3.0 中默认启用,在 16.4.0 中移除。 | 移除该标志。true 值已与默认值一致。false 退出选项已不再可用,并且新的处理程序会保持焦点不变。 |
故障排除
升级到 React 19 后安装失败
- 按照 React 恢复检查清单 操作。
升级 ESLint 后安装失败
Next.js 16 移除了 next lint,但迁移到 ESLint CLI 不要求升级 ESLint。eslint-config-next@16 需要 ESLint 9 或更高版本,而 eslint-config-next@16.4.0 或更高版本支持 ESLint 10。如果你现有的 lint 配置不使用 eslint-config-next@16,可以保留其兼容的 ESLint 版本。
- 如果升级 ESLint 导致 peer 依赖冲突,请恢复
eslint、eslint-config-next和@next/eslint-plugin-next之前兼容的版本(如果存在),以及之前的 lint 配置。 - 如果安装中断了升级,请使用
--skip-eslint-upgrade重试完全相同的目标,以保留已修复的 lint 工具链并跳过 lint codemod。如果 Next.js 已与目标匹配,请安装依赖并逐一完成中断的迁移。请将next lint脚本替换为与保留配置兼容的 ESLint CLI 命令。确认安装和 lint 均通过。
查看迁移检查清单
在应用与你的应用相关的更改后,在认为迁移完成之前,请检查以下行动项:
应用满足本指南中的 Node.js、TypeScript 和 React 要求。
开发和构建脚本与生效的打包器配置一致,包括插件、加载器、别名以及受影响的 Sass 导入。
中间件和 proxy 更改保留了所需的运行时和路由行为。Edge 中间件不会被盲目重命名为 proxy。
受影响的图片请求在文档所述的限制和默认值下成功,同时保持预期质量。
现有缓存 API 调用遵循文档记录的签名和语义。不会仅仅为了完成升级而启用 React Compiler 和 Cache Components。
已移除的 API 和配置不再有使用方。运行时配置替代方案保留了服务器和客户端可见性以及所需的求值时机。
脚本和 CI 不再调用
next lint;在应用需要时单独运行 lint。应用支持的检查以及受影响的运行时行为均通过。仅凭构建通过并不能消除运行时发现的问题。
异步 Request API 访问及受影响的调用方已完成迁移。处理 codemod 错误注释和
UnsafeUnwrapped类型断言;在适当情况下,对同步客户端组件使用 Reactuse。动态元数据图片函数和 sitemap 函数处理其异步参数,并且受影响的生成 URL 正常工作。
并行路由槽具有适当的默认值,直接导航和重新加载会保留预期的回退行为。