跳到内容
API 参考配置next.config.js

next.config.js

Next.js 可以通过项目根目录(例如,与 package.json 同级)中的 next.config.js 文件进行配置,该文件具有默认导出。

next.config.js
// @ts-check
 
/** @type {import('next').NextConfig} */
const nextConfig = {
  /* config options here */
}
 
module.exports = nextConfig

ECMAScript 模块

next.config.js 是一个常规的 Node.js 模块,而不是 JSON 文件。它被 Next.js 服务器和构建阶段使用,并且不包含在浏览器构建中。

如果您需要ECMAScript 模块,您可以使用 next.config.mjs

next.config.mjs
// @ts-check
 
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  /* config options here */
}
 
export default nextConfig

须知: 当前支持扩展名为 .cjs.cts.mtsnext.config

作为函数的配置

您也可以使用函数

next.config.mjs
// @ts-check
 
export default (phase, { defaultConfig }) => {
  /**
   * @type {import('next').NextConfig}
   */
  const nextConfig = {
    /* config options here */
  }
  return nextConfig
}

异步配置

从 Next.js 12.1.0 开始,您可以使用异步函数

next.config.js
// @ts-check
 
module.exports = async (phase, { defaultConfig }) => {
  /**
   * @type {import('next').NextConfig}
   */
  const nextConfig = {
    /* config options here */
  }
  return nextConfig
}

阶段

phase 是加载配置的当前上下文。您可以查看可用阶段。阶段可以从 next/constants 导入

next.config.js
// @ts-check
 
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
 
module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return {
      /* development only config options here */
    }
  }
 
  return {
    /* config options for all phases except development here */
  }
}

TypeScript

如果您在项目中使用 TypeScript,则可以使用 next.config.ts 在配置中使用 TypeScript

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  /* config options here */
}
 
export default nextConfig

注释行是您可以放置 next.config.js 允许的配置的位置,这些配置在此文件中定义

但是,没有任何配置是必需的,也没有必要理解每个配置的作用。相反,请在本节中搜索您需要启用或修改的功能,它们将向您展示如何操作。

避免使用目标 Node.js 版本中不可用的新 JavaScript 功能。next.config.js 不会被 Webpack 或 Babel 解析。

此页面记录了所有可用的配置选项

单元测试(实验性)

从 Next.js 15.1 开始,next/experimental/testing/server 包包含用于帮助单元测试 next.config.js 文件的实用程序。

unstable_getResponseFromNextConfig 函数使用提供的请求信息运行 next.config.js 中的 headersredirectsrewrites 函数,并返回带有路由结果的 NextResponse

unstable_getResponseFromNextConfig 的响应仅考虑 next.config.js 字段,而不考虑中间件或文件系统路由,因此生产环境中的结果可能与单元测试不同。

import {
  getRedirectUrl,
  unstable_getResponseFromNextConfig,
} from 'next/experimental/testing/server'
 
const response = await unstable_getResponseFromNextConfig({
  url: 'https://nextjs.net.cn/test',
  nextConfig: {
    async redirects() {
      return [{ source: '/test', destination: '/test2', permanent: false }]
    },
  },
})
expect(response.status).toEqual(307)
expect(getRedirectUrl(response)).toEqual('https://nextjs.net.cn/test2')

allowedDevOrigins

Use `allowedDevOrigins` to configure additional origins that can request the dev server.

appDir

Enable the App Router to use layouts, streaming, and more.

assetPrefix

Learn how to use the assetPrefix config option to configure your CDN.

authInterrupts

Learn how to enable the experimental `authInterrupts` configuration option to use `forbidden` and `unauthorized`.

basePath

Use `basePath` to deploy a Next.js application under a sub-path of a domain.

cacheLife

Learn how to set up cacheLife configurations in Next.js.

compress

Next.js provides gzip compression to compress rendered content and static files, it only works with the server target. Learn more about it here.

crossOrigin

Use the `crossOrigin` option to add a crossOrigin tag on the `script` tags generated by `next/script`.

cssChunking

Use the `cssChunking` option to control how CSS files are chunked in your Next.js application.

devIndicators

Configuration options for the on-screen indicator that gives context about the current route you're viewing during development.

distDir

Set a custom build directory to use instead of the default .next directory.

dynamicIO

Learn how to enable the dynamicIO flag in Next.js.

env

Learn to add and access environment variables in your Next.js application at build time.

eslint

Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.

expireTime

Customize stale-while-revalidate expire time for ISR enabled pages.

exportPathMap

Customize the pages that will be exported as HTML files when using `next export`.

generateBuildId

Configure the build id, which is used to identify the current build in which your application is being served.

generateEtags

Next.js will generate etags for every page by default. Learn more about how to disable etag generation here.

headers

Add custom HTTP headers to your Next.js app.

htmlLimitedBots

Specify a list of user agents that should receive blocking metadata.

httpAgentOptions

Next.js will automatically use HTTP Keep-Alive by default. Learn more about how to disable HTTP Keep-Alive here.

images

Custom configuration for the next/image loader

cacheHandler

Configure the Next.js cache used for storing and revalidating data to use any external service like Redis, Memcached, or others.

inlineCss

Enable inline CSS support.

logging

Configure how data fetches are logged to the console when running Next.js in development mode.

mdxRs

Use the new Rust compiler to compile MDX files in the App Router.

onDemandEntries

Configure how Next.js will dispose and keep in memory pages created in development.

optimizePackageImports

API Reference for optimizePackageImports Next.js Config Option

output

Next.js automatically traces which files are needed by each page to allow for easy deployment of your application. Learn how it works here.

pageExtensions

Extend the default page extensions used by Next.js when resolving pages in the Pages Router.

poweredByHeader

Next.js will add the `x-powered-by` header by default. Learn to opt-out of it here.

ppr

Learn how to enable Partial Prerendering in Next.js.

productionBrowserSourceMaps

Enables browser source map generation during the production build.

reactCompiler

Enable the React Compiler to automatically optimize component rendering.

reactMaxHeadersLength

The maximum length of the headers that are emitted by React and added to the response.

reactStrictMode

The complete Next.js runtime is now Strict Mode-compliant, learn how to opt-in

redirects

Add redirects to your Next.js app.

rewrites

Add rewrites to your Next.js app.

sassOptions

Configure Sass options.

serverActions

Configure Server Actions behavior in your Next.js application.

serverComponentsHmrCache

Configure whether fetch responses in Server Components are cached across HMR refresh requests.

serverExternalPackages

Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.

staleTimes

Learn how to override the invalidation time of the Client Router Cache.

staticGeneration*

Learn how to configure static generation in your Next.js application.

trailingSlash

Configure Next.js pages to resolve with or without a trailing slash.

transpilePackages

Automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`).

turbopack

Configure Next.js with Turbopack-specific options

typedRoutes

Enable experimental support for statically typed links.

typescript

Next.js reports TypeScript errors by default. Learn to opt-out of this behavior here.

urlImports

Configure Next.js to allow importing modules from external URLs.

useCache

Learn how to enable the useCache flag in Next.js.

useLightningcss

Enable experimental support for Lightning CSS.

ViewTransition

Enable ViewTransition API from React in App Router

webpack

Learn how to customize the webpack config used by Next.js

webVitalsAttribution

Learn how to use the webVitalsAttribution option to pinpoint the source of Web Vitals issues.