import os from 'os' import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes' import { imageConfigDefault } from '../shared/lib/image-config' import type { ImageConfig, ImageConfigComplete, } from '../shared/lib/image-config' import type { SubresourceIntegrityAlgorithm } from '../build/webpack/plugins/subresource-integrity-plugin' import type { WEB_VITALS } from '../shared/lib/utils' import type { NextParsedUrlQuery } from './request-meta' import type { SizeLimit } from '../types' import type { SupportedTestRunners } from '../cli/next-test' import type { ExperimentalPPRConfig } from './lib/experimental/ppr' import { INFINITE_CACHE } from '../lib/constants' import { isStableBuild } from '../shared/lib/errors/canary-only-config-error' import type { FallbackRouteParam } from '../build/static-paths/types' export type NextConfigComplete = Required> & { images: Required typescript: TypeScriptConfig configFile: string | undefined configFileName: string // override NextConfigComplete.experimental.htmlLimitedBots to string // because it's not defined in NextConfigComplete.experimental htmlLimitedBots: string | undefined experimental: ExperimentalConfig // The root directory of the distDir. Generally the same as `distDir` but when `isolatedDevBuild` // is true it is the parent directory of `distDir`. This is used to ensure that the bundler doesn't // traverse into the output directory. distDirRoot: string } export type I18NDomains = readonly DomainLocale[] export interface I18NConfig { defaultLocale: string domains?: I18NDomains localeDetection?: false locales: readonly string[] } export interface DomainLocale { defaultLocale: string domain: string http?: true locales?: readonly string[] } export interface TypeScriptConfig { /** Do not run TypeScript during production builds (`next build`). */ ignoreBuildErrors?: boolean /** Relative path to a custom tsconfig file */ tsconfigPath?: string } export interface EmotionConfig { sourceMap?: boolean autoLabel?: 'dev-only' | 'always' | 'never' labelFormat?: string importMap?: { [importName: string]: { [exportName: string]: { canonicalImport?: [string, string] styledBaseImport?: [string, string] } } } } export interface StyledComponentsConfig { /** * Enabled by default in development, disabled in production to reduce file size, * setting this will override the default for all environments. */ displayName?: boolean topLevelImportPaths?: string[] ssr?: boolean fileName?: boolean meaninglessFileNames?: string[] minify?: boolean transpileTemplateLiterals?: boolean namespace?: string pure?: boolean cssProp?: boolean } export type JSONValue = | string | number | boolean | JSONValue[] | { [k: string]: JSONValue } // At the moment, Turbopack options must be JSON-serializable, so restrict values. export type TurbopackLoaderOptions = Record export type TurbopackLoaderItem = | string | { loader: string options?: TurbopackLoaderOptions } export type TurbopackLoaderBuiltinCondition = | 'browser' | 'foreign' | 'development' | 'production' | 'node' | 'edge-light' export type TurbopackRuleCondition = | { all: TurbopackRuleCondition[] } | { any: TurbopackRuleCondition[] } | { not: TurbopackRuleCondition } | TurbopackLoaderBuiltinCondition | { path?: string | RegExp content?: RegExp } export type TurbopackRuleConfigItem = { loaders: TurbopackLoaderItem[] as?: string condition?: TurbopackRuleCondition } /** * This can be an object representing a single configuration, or a list of * loaders and/or rule configuration objects. * * - A list of loader path strings or objects is the "shorthand" syntax. * - A list of rule configuration objects can be useful when each configuration * object has different `condition` fields, but still match the same top-level * path glob. */ export type TurbopackRuleConfigCollection = | TurbopackRuleConfigItem | (TurbopackLoaderItem | TurbopackRuleConfigItem)[] export interface TurbopackOptions { /** * (`next --turbopack` only) A mapping of aliased imports to modules to load in their place. * * @see [Resolve Alias](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#resolving-aliases) */ resolveAlias?: Record< string, string | string[] | Record > /** * (`next --turbopack` only) A list of extensions to resolve when importing files. * * @see [Resolve Extensions](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#resolving-custom-extensions) */ resolveExtensions?: string[] /** * (`next --turbopack` only) A list of webpack loaders to apply when running with Turbopack. * * @see [Turbopack Loaders](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders) */ rules?: Record /** * This is the repo root usually and only files above this * directory can be resolved by turbopack. */ root?: string /** * Enables generation of debug IDs in JavaScript bundles and source maps. * These debug IDs help with debugging and error tracking by providing stable identifiers. * * @see https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md TC39 Debug ID Proposal */ debugIds?: boolean } export interface WebpackConfigContext { /** Next.js root directory */ dir: string /** Indicates if the compilation will be done in development */ dev: boolean /** It's `true` for server-side compilation, and `false` for client-side compilation */ isServer: boolean /** The build id, used as a unique identifier between builds */ buildId: string /** The next.config.js merged with default values */ config: NextConfigComplete /** Default loaders used internally by Next.js */ defaultLoaders: { /** Default babel-loader configuration */ babel: any } /** Number of total Next.js pages */ totalPages: number /** The webpack configuration */ webpack: any /** The current server runtime */ nextRuntime?: 'nodejs' | 'edge' } export interface NextJsWebpackConfig { ( /** Existing Webpack config */ config: any, context: WebpackConfigContext ): any } /** * Set of options for React Compiler that Next.js currently supports. * * These options may be changed in breaking ways at any time without notice * while support for React Compiler is experimental. * * @see https://react.dev/reference/react-compiler/configuration */ export interface ReactCompilerOptions { /** * Controls the strategy for determining which functions the React Compiler * will optimize. * * The default is `'infer'`, which uses intelligent heuristics to identify * React components and hooks. * * When using `infer`, Next.js applies its own heuristics before calling * `react-compiler`. This improves compilation performance by avoiding extra * invocations of Babel and reducing redundant parsing of code. * * @see https://react.dev/reference/react-compiler/compilationMode */ compilationMode?: 'infer' | 'annotation' | 'all' /** * Controls how the React Compiler handles errors during compilation. * * The default is `'none'`, which skips components which cannot be compiled. * * @see https://react.dev/reference/react-compiler/panicThreshold */ panicThreshold?: 'none' | 'critical_errors' | 'all_errors' } export interface IncomingRequestLoggingConfig { /** * A regular expression array to match incoming requests that should not be logged. * You can specify multiple patterns to match incoming requests that should not be logged. */ ignore?: RegExp[] } export interface LoggingConfig { fetches?: { fullUrl?: boolean /** * If true, fetch requests that are restored from the HMR cache are logged * during an HMR refresh request, i.e. when editing a server component. */ hmrRefreshes?: boolean } /** * If set to false, incoming request logging is disabled. * You can specify a pattern to match incoming requests that should not be logged. */ incomingRequests?: boolean | IncomingRequestLoggingConfig } export interface ExperimentalConfig { adapterPath?: string useSkewCookie?: boolean /** @deprecated use top-level `cacheHandlers` instead */ cacheHandlers?: NextConfig['cacheHandlers'] multiZoneDraftMode?: boolean appNavFailHandling?: boolean prerenderEarlyExit?: boolean linkNoTouchStart?: boolean caseSensitiveRoutes?: boolean /** * Custom header name to use for CDN cache control instead of the default * 'CDN-Cache-Control'. This can be used to target specific CDN providers * that do not support `CDN-Cache-Control` and have their own custom header. */ cdnCacheControlHeader?: string /** * The origins that are allowed to write the rewritten headers when * performing a non-relative rewrite. When undefined, no non-relative * rewrites will get the rewrite headers. */ clientParamParsingOrigins?: string[] dynamicOnHover?: boolean preloadEntriesOnStart?: boolean clientRouterFilter?: boolean clientRouterFilterRedirects?: boolean /** * This config can be used to override the cache behavior for the client router. * These values indicate the time, in seconds, that the cache should be considered * reusable. When the `prefetch` Link prop is left unspecified, this will use the `dynamic` value. * When the `prefetch` Link prop is set to `true`, this will use the `static` value. */ staleTimes?: { dynamic?: number /** Must be greater than or equal to 30 seconds, to ensure prefetching is not completely wasteful */ static?: number } /** * @deprecated use top-level `cacheLife` instead */ cacheLife?: NextConfig['cacheLife'] // decimal for percent for possible false positives // e.g. 0.01 for 10% potential false matches lower // percent increases size of the filter clientRouterFilterAllowedRate?: number /** * @deprecated Use `externalProxyRewritesResolve` instead. */ externalMiddlewareRewritesResolve?: boolean externalProxyRewritesResolve?: boolean extensionAlias?: Record allowedRevalidateHeaderKeys?: string[] fetchCacheKeyPrefix?: string imgOptConcurrency?: number | null imgOptTimeoutInSeconds?: number imgOptMaxInputPixels?: number imgOptSequentialRead?: boolean | null imgOptSkipMetadata?: boolean | null optimisticClientCache?: boolean /** * @deprecated use config.expireTime instead */ expireTime?: number /** * @deprecated Use `proxyPrefetch` instead. */ middlewarePrefetch?: 'strict' | 'flexible' proxyPrefetch?: 'strict' | 'flexible' manualClientBasePath?: boolean /** * CSS Chunking strategy. Defaults to `true` ("loose" mode), which guesses dependencies * between CSS files to keep ordering of them. * An alternative is 'strict', which will try to keep correct ordering as * much as possible, even when this leads to many requests. */ cssChunking?: boolean | 'strict' disablePostcssPresetEnv?: boolean cpus?: number memoryBasedWorkersCount?: boolean proxyTimeout?: number isrFlushToDisk?: boolean workerThreads?: boolean // optimizeCss can be boolean or critters' option object // Use Record as critters doesn't export its Option type // https://github.com/GoogleChromeLabs/critters/blob/a590c05f9197b656d2aeaae9369df2483c26b072/packages/critters/src/index.d.ts optimizeCss?: boolean | Record nextScriptWorkers?: boolean scrollRestoration?: boolean externalDir?: boolean disableOptimizedLoading?: boolean /** @deprecated A no-op as of Next 16, size metrics were removed from the build output. */ gzipSize?: boolean craCompat?: boolean esmExternals?: boolean | 'loose' fullySpecified?: boolean urlImports?: NonNullable['buildHttp'] swcTraceProfiling?: boolean forceSwcTransforms?: boolean swcPlugins?: Array<[string, Record]> largePageDataBytes?: number /** * If set to `false`, webpack won't fall back to polyfill Node.js modules in the browser * Full list of old polyfills is accessible here: * [webpack/webpack#ModuleNotoundError.js#L13-L42](https://github.com/webpack/webpack/blob/2a0536cf510768111a3a6dceeb14cb79b9f59273/lib/ModuleNotFoundError.js#L13-L42) */ fallbackNodePolyfills?: false sri?: { algorithm?: SubresourceIntegrityAlgorithm } webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]> /** * Automatically apply the "modularizeImports" optimization to imports of the specified packages. */ optimizePackageImports?: string[] /** * Optimize React APIs for server builds. */ optimizeServerReact?: boolean /** * Type-checks props and return values of pages. * Requires literal values for segment config (e.g. `export const dynamic = 'force-static' as const`). */ strictRouteTypes?: boolean /** * Displays an indicator when a React Transition has no other indicator rendered. * This includes displaying an indicator on client-side navigations. */ transitionIndicator?: boolean /** * A target memory limit for turbo, in bytes. */ turbopackMemoryLimit?: number /** * Enable minification. Defaults to true in build mode and false in dev mode. */ turbopackMinify?: boolean /** * Enable support for `with {type: "module"}` for ESM imports. */ turbopackImportTypeBytes?: boolean /** * Enable scope hoisting. Defaults to true in build mode. Always disabled in development mode. */ turbopackScopeHoisting?: boolean /** * Enable nested async chunking for client side assets. Defaults to true in build mode and false in dev mode. * This optimization computes all possible paths through dynamic imports in the applications to figure out the modules needed at dynamic imports for every path. */ turbopackClientSideNestedAsyncChunking?: boolean /** * Enable nested async chunking for server side assets. Defaults to false in dev and build mode. * This optimization computes all possible paths through dynamic imports in the applications to figure out the modules needed at dynamic imports for every path. */ turbopackServerSideNestedAsyncChunking?: boolean /** * Enable filesystem cache for the turbopack dev server. * * Defaults to `true`. */ turbopackFileSystemCacheForDev?: boolean /** * Enable filesystem cache for the turbopack build. * * Defaults to `false`. */ turbopackFileSystemCacheForBuild?: boolean /** * Enable source maps. Defaults to true. */ turbopackSourceMaps?: boolean /** * Enable extraction of source maps from input files. Defaults to true. */ turbopackInputSourceMaps?: boolean /** * Enable tree shaking for the turbopack dev server and build. */ turbopackTreeShaking?: boolean /** * Enable removing unused imports for turbopack dev server and build. */ turbopackRemoveUnusedImports?: boolean /** * Enable removing unused exports for turbopack dev server and build. */ turbopackRemoveUnusedExports?: boolean /** * Enable local analysis to infer side effect free modules. When enabled, Turbopack will * analyze module code to determine if it has side effects. This can improve tree shaking * and bundle size at the cost of some additional analysis. * * Defaults to `true` in canary builds only */ turbopackInferModuleSideEffects?: boolean /** * Use the system-provided CA roots instead of bundled CA roots for external HTTPS requests * made by Turbopack. Currently this is only used for fetching data from Google Fonts. * * This may be useful in cases where you or an employer are MITMing traffic. * * This option is experimental because: * - This may cause small performance problems, as it uses [`rustls-native-certs`]( * https://github.com/rustls/rustls-native-certs). * - In the future, this may become the default, and this option may be eliminated, once * is resolved. * * Users who need to configure this behavior system-wide can override the project * configuration using the `NEXT_TURBOPACK_EXPERIMENTAL_USE_SYSTEM_TLS_CERTS=1` environment * variable. * * This option is ignored on Windows on ARM, where the native TLS implementation is always * used. * * If you need to set a proxy, Turbopack [respects the common `HTTP_PROXY` and `HTTPS_PROXY` * environment variable convention](https://docs.rs/reqwest/latest/reqwest/#proxies). HTTP * proxies are supported, SOCKS proxies are not currently supported. */ turbopackUseSystemTlsCerts?: boolean /** * Set this to `false` to disable the automatic configuration of the babel loader when a Babel * configuration file is present. This option is enabled by default. * * If this is set to `false`, but `reactCompiler` is `true`, the built-in Babel will * still be configured, but any Babel configuration files on disk will be ignored. If you wish to * use React Compiler with a different manually-configured `babel-loader`, you should disable both * this and `reactCompiler`. */ turbopackUseBuiltinBabel?: boolean /** * Set this to `false` to disable the automatic configuration of the sass loader. The sass loader * configuration is enabled by default. */ turbopackUseBuiltinSass?: boolean /** * The module ID strategy to use for Turbopack. * If not set, the default is `'named'` for development and `'deterministic'` * for production. */ turbopackModuleIds?: 'named' | 'deterministic' /** * For use with `@next/mdx`. Compile MDX files using the new Rust compiler. * @see https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs */ mdxRs?: | boolean | { development?: boolean jsx?: boolean jsxRuntime?: string jsxImportSource?: string providerImportSource?: string mdxType?: 'gfm' | 'commonmark' } /** * Enable type checking for Link and Router.push, etc. * @deprecated Use `typedRoutes` instead — this feature is now stable. * @see https://nextjs.org/docs/app/api-reference/config/typescript#statically-typed-links */ typedRoutes?: boolean /** * Enable type-checking and autocompletion for environment variables. * * @default false */ typedEnv?: boolean /** * Runs the compilations for server and edge in parallel instead of in serial. * This will make builds faster if there is enough server and edge functions * in the application at the cost of more memory. * * NOTE: This option is only valid when the build process can use workers. See * the documentation for `webpackBuildWorker` for more details. */ parallelServerCompiles?: boolean /** * Runs the logic to collect build traces for the server routes in parallel * with other work during the compilation. This will increase the speed of * the build at the cost of more memory. This option may incur some additional * work compared to if the option was disabled since the work is started * before data from the client compilation is available to potentially reduce * the amount of code that needs to be traced. Despite that, this may still * result in faster builds for some applications. * * Valid values are: * - `true`: Collect the server build traces in parallel. * - `false`: Do not collect the server build traces in parallel. * - `undefined`: Collect server build traces in parallel only in the `experimental-compile` mode. * * NOTE: This option is only valid when the build process can use workers. See * the documentation for `webpackBuildWorker` for more details. */ parallelServerBuildTraces?: boolean /** * Run the Webpack build in a separate process to optimize memory usage during build. * Valid values are: * - `false`: Disable the Webpack build worker * - `true`: Enable the Webpack build worker * - `undefined`: Enable the Webpack build worker only if the webpack config is not customized */ webpackBuildWorker?: boolean /** * Enables optimizations to reduce memory usage in Webpack. This reduces the max size of the heap * but may increase compile times slightly. * Valid values are: * - `false`: Disable Webpack memory optimizations (default). * - `true`: Enables Webpack memory optimizations. */ webpackMemoryOptimizations?: boolean /** * The array of the meta tags to the client injected by tracing propagation data. */ clientTraceMetadata?: string[] /** * @deprecated This configuration option has been merged into `cacheComponents`. * The Partial Prerendering feature is still available via `cacheComponents`. */ ppr?: ExperimentalPPRConfig /** * Enables experimental taint APIs in React. * Using this feature will enable the `react@experimental` for the `app` directory. */ taint?: boolean /** * Uninstalls all "unhandledRejection" and "uncaughtException" listeners from * the global process so that we can override the behavior, which in some * runtimes is to exit the process. * * This is experimental until we've considered the impact in various * deployment environments. */ removeUncaughtErrorAndRejectionListeners?: boolean /** * During an RSC request, validates that the request headers match the * cache-busting search parameter sent by the client. */ validateRSCRequestHeaders?: boolean serverActions?: { /** * Allows adjusting body parser size limit for server actions. */ bodySizeLimit?: SizeLimit /** * Allowed origins that can bypass Server Action's CSRF check. This is helpful * when you have reverse proxy in front of your app. * @example * ["my-app.com", "*.my-app.com"] */ allowedOrigins?: string[] } /** * Allows adjusting the maximum size of the postponed state body for PPR * resume requests. This includes the Resume Data Cache (RDC) which may grow * large for some applications. * @default '100 MB' */ maxPostponedStateSize?: SizeLimit /** * enables the minification of server code. */ serverMinification?: boolean /** * Enables source maps generation for the server production bundle. */ serverSourceMaps?: boolean /** * @internal Used by the Next.js internals only. */ trustHostHeader?: boolean /** * @internal Used by the Next.js internals only. */ isExperimentalCompile?: boolean useWasmBinary?: boolean /** * Use lightningcss instead of postcss-loader */ useLightningcss?: boolean /** * Enables view transitions by using the {@link https://react.dev/reference/react/ViewTransition ViewTransition} Component. */ viewTransition?: boolean /** * Enables `fetch` requests to be proxied to the experimental test proxy server */ testProxy?: boolean /** * Set a default test runner to be used by `next experimental-test`. */ defaultTestRunner?: SupportedTestRunners /** * Allow NODE_ENV=development even for `next build`. */ allowDevelopmentBuild?: true /** * @deprecated use `config.bundlePagesRouterDependencies` instead * */ bundlePagesExternals?: boolean /** * @deprecated use `config.serverExternalPackages` instead * */ serverComponentsExternalPackages?: string[] /** * When enabled, in dev mode, Next.js will send React's debug info through the * WebSocket connection, instead of including it in the main RSC payload. */ reactDebugChannel?: boolean /** * @deprecated use top-level `cacheComponents` instead */ cacheComponents?: boolean /** * The number of times to retry static generation (per page) before giving up. */ staticGenerationRetryCount?: number /** * The amount of pages to export per worker during static generation. */ staticGenerationMaxConcurrency?: number /** * The minimum number of pages to be chunked into each export worker. */ staticGenerationMinPagesPerWorker?: number /** * Allows previously fetched data to be re-used when editing server components. */ serverComponentsHmrCache?: boolean /** * Render