MENU
Configurations
You can modify the Next.js configuration file to control different aspects of Next.js.
With a filename suffix .js, .mjs, or .ts, this file will not be parsed by Webpack or Babel.
The .cjs, .cts, or .mts extensions are currently not supported.
In the file, you should export a default configuration object or a function (sync or async) returning a configuration object.
You can configure Next.js by creating a next.config.js file in the root of your project directory (not inside the /app folder), using a default export.
A list of available phases can be found here.
next.config.js:
A list of available phases can be found here.
next.config.js:
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = async (phase, { defaultConfig }) => { // an async function
if (phase === PHASE_DEVELOPMENT_SERVER) {
return {
/* development only config options here */
}
}
return {
/* config options for all phases except development here */
}
}
next.config.js is a standard Node.js module—not a JSON file. It's used during the Next.js server runtime and build process, but it's not bundled into the browser build. If you prefer using ECMAScript modules, you can instead use next.config.mjs.
Notice below how the module is exported differently from the example above.
next.config.mjs:
next.config.mjs:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const somePackage = require('some-commonjs-package');
const nextConfig = { // a JSON object literal
reactStrictMode: true,
images: {
domains: ['example.com'],
},
};
export default nextConfig;
If your project uses TypeScript, you can write your configuration in a next.config.ts file to take advantage of TypeScript features.
next.config.ts:
next.config.ts:
import type { NextConfig } from 'next';
const nextConfig: NextConfig = { // a JSON object literal
/* config options here */
}
export default nextConfig;
Starting in Next.js 15.1, the next/experimental/testing/server package introduces tools to unit test your next.config.js file. The key utility, unstable_getResponseFromNextConfig, allows you to simulate requests and evaluate how the headers, redirects, and rewrites functions respond, returning a NextResponse object.
This function isolates and tests only the routing logic defined in next.config.js -- it does not account for middleware or file system routes, so actual production behavior may differ.
You can use testing libraries like Jest to write and run these unit tests. Jest makes it easy to assert the expected status codes and redirect URLs, enabling quick and reliable validation of your config logic.
nextConfig.test.js:
This function isolates and tests only the routing logic defined in next.config.js -- it does not account for middleware or file system routes, so actual production behavior may differ.
You can use testing libraries like Jest to write and run these unit tests. Jest makes it easy to assert the expected status codes and redirect URLs, enabling quick and reliable validation of your config logic.
nextConfig.test.js:
import {
getRedirectUrl,
unstable_getResponseFromNextConfig,
} from 'next/experimental/testing/server'
describe('next.config.js redirects', () => {
it('should redirect /test to /test2', async () => {
const response = await unstable_getResponseFromNextConfig({
url: 'https://nextjs.org/test',
nextConfig: {
async redirects() {
return [
{ source: '/test', destination: '/test2', permanent: false }
]
},
},
})
expect(response.status).toEqual(307)
expect(getRedirectUrl(response)).toEqual('https://nextjs.org/test2')
})
})React
| 1. reactMaxHeadersLength | Defines the maximum character limit for HTTP headers generated by React Server Components and included in server responses, helping prevent header overflow issues. |
| 2. reactStrictMode | Activates React's Strict Mode during development to help identify potential problems by intentionally double-invoking functions and highlighting unsafe lifecycles. |
| 3. viewTransition | Enables the experimental View Transition API integration in Next.js App Router for smooth page transitions with native browser animations. |
CSS
| 1. cssChunking | Manages how CSS files are split and bundled into separate chunks for optimized loading performance and better caching strategies in production builds. |
| 2. inlineCss | Allows CSS to be embedded directly into HTML documents instead of being served as separate files, reducing HTTP requests but potentially increasing initial page size. |
| 3. sassOptions | Provides configuration options for the Sass preprocessor, including import paths, custom functions, and compiler-specific settings for .scss and .sass files. |
| 4. useLightningcss | Enables the experimental Lightning CSS parser and transformer as a faster alternative to the default CSS processing pipeline, offering improved build performance. |
Rendering
| 1. compress | Enables gzip compression for both dynamically rendered content and static assets to reduce bandwidth usage and improve page loading speeds. |
| 2. ppr | Activates Partial Prerendering, an experimental feature that combines static and dynamic rendering within the same page for optimal performance. |
| 3. serverActions | Configures the behavior and security settings for Server Actions, including size limits, allowed origins, and execution timeouts for server-side form handling. |
| 4. staticGeneration | Controls static site generation settings, including which pages are pre-rendered at build time and how static exports are handled. |
| 5. webVitalsAttribution | Enables detailed attribution reporting for Core Web Vitals metrics to help identify specific performance bottlenecks and optimization opportunities. |
'images'
| 1. localPatterns | Specifies allowed local file system paths for image optimization while blocking unauthorized access to other local images for security purposes. |
| 2. remotePatterns | Defines trusted external domains and URL patterns from which images can be optimized, preventing unauthorized image proxy usage and potential security vulnerabilities. |
| 3. loaderFile | Specifies a custom image optimization service or CDN configuration file to replace Next.js's built-in image optimization with third-party solutions. |
| 4. imageSizes | Defines an array of image widths that the Image component will generate for responsive images, optimizing for different screen sizes and device types. |
| 5. qualities | Sets available image quality levels (0-100) for different optimization scenarios, allowing fine-tuned control over file size versus visual quality trade-offs. |
| 6. formats | Specifies supported image formats (WebP, AVIF, etc.) for automatic format optimization based on browser support and file size efficiency. |
| 7. minimumCacheTTL | Sets the minimum Time to Live in seconds for cached optimized images, controlling how long images remain in the optimization cache before reprocessing. |
| 8. disableStaticImages | Prevents automatic optimization of statically imported images, useful when using custom image processing workflows or external optimization services. |
| 9. dangerouslyAllowSVG | Permits SVG image serving through the Image component despite potential XSS risks, requiring careful content validation and sanitization measures. |
| 10. contentDispositionType | Controls the Content-Disposition HTTP header for optimized images, determining whether images are displayed inline or downloaded as attachments. |
Server
| 1. allowedDevOrigins | Specifies additional trusted origins that can make requests to the Next.js development server, enabling cross-origin development scenarios and API access. |
| 2. assetPrefix | Configures a CDN URL prefix for static assets, allowing efficient content delivery through external content distribution networks for improved global performance. |
| 3. basePath | Sets a URL subpath for deploying Next.js applications under a subdirectory of a domain, enabling multiple applications to coexist on the same host. |
| 4. crossOrigin | Adds crossOrigin attributes to script tags generated by next/script component, controlling CORS behavior for externally loaded JavaScript resources. |
| 5. devIndicators | Customizes the visual development indicators that appear during local development, including compilation status, prerender indicators, and route information displays. |
| 6. htmlLimitedBots | Defines a list of user agent strings for web crawlers that should receive HTML responses with limited JavaScript execution, improving SEO and bot accessibility. |
| 7. httpAgentOptions | Configures HTTP agent settings including Keep-Alive behavior, connection pooling, and timeout values for server-side HTTP requests and API calls. |
URL
| 1. authInterrupts | Enables experimental authentication interrupt handling to automatically manage 'forbidden' (403) and 'unauthorized' (401) responses with custom redirect flows. |
| 2. logging | Controls the verbosity and format of data fetching logs displayed in the development console, helping debug API calls and server-side data requests. |
| 3. poweredByHeader | Removes the 'X-Powered-By: Next.js' HTTP header from responses for security through obscurity and to reduce server fingerprinting opportunities. |
| 4. trailingSlash | Determines whether URLs should include trailing slashes, affecting SEO, canonical URLs, and routing consistency across the application. |
| 5. typedRoutes | Enables experimental TypeScript support for statically typed route parameters and navigation, providing compile-time route validation and autocompletion. |
'redirects', 'rewrites' & 'headers'
Caching
| 1. cacheHandler | Integrates external caching solutions like Redis, Memcached, or custom cache providers to replace Next.js's default file-system based cache for improved scalability. |
| 2. cacheLife | Defines cache duration policies and invalidation strategies for different types of content, enabling fine-grained control over cache behavior and data freshness. |
| 3. dynamicIO | Enables experimental dynamic I/O optimization features that improve server-side rendering performance through intelligent request batching and caching strategies. |
| 4. expireTime | Customizes the stale-while-revalidate expiration time for Incremental Static Regeneration pages, balancing content freshness with performance optimization. |
| 5. generateEtags | Controls automatic ETag header generation for HTTP responses, which helps browsers and CDNs determine when cached content has changed. |
| 6. onDemandEntries | Manages memory usage in development by configuring how long pages remain in memory after being accessed and when they should be disposed. |
| 7. serverComponentsHmrCache | Determines whether fetch responses in Server Components are cached across Hot Module Replacement refresh cycles during development for faster reload times. |
| 8. staleTimes | Override default invalidation intervals for the Client Router Cache, controlling how long prefetched routes and data remain cached on the client side. |
| 9. useCache | Activates experimental caching improvements and optimizations throughout the Next.js rendering pipeline for enhanced application performance. |
Compiler
| 1. distDir | Specifies a custom directory name for build output instead of the default '.next' folder, useful for deployment pipelines and custom build configurations. |
| 2. eslint | Controls ESLint integration during builds, allowing you to disable linting errors and warnings or customize which rules are enforced in the build process. |
| 3. generateBuildId | Provides a custom function to generate unique build identifiers used for cache busting and deployment tracking across different application versions. |
| 4. mdxRs | Enables the new Rust-based MDX compiler for faster processing of MDX files in App Router applications, improving build performance for content-heavy sites. |
| 5. pageExtensions | Extends the default file extensions (.js, .jsx, .ts, .tsx) that Next.js recognizes as pages in the Pages Router, allowing custom file naming conventions. |
| 6. productionBrowserSourceMaps | Generates source maps for client-side JavaScript bundles in production builds, enabling better debugging and error tracking in deployed applications. |
| 7. reactCompiler | Activates the experimental React Compiler for automatic memoization and rendering optimizations, potentially improving runtime performance without manual optimization. |
| 8. turbopack | Configures Turbopack-specific build options for the experimental Rust-based bundler, offering significantly faster build times during development. |
| 9. typescript | Controls TypeScript integration and error reporting during builds, allowing you to customize type checking behavior or disable it entirely for faster builds. |
| 10. webpack | Provides access to customize the underlying webpack configuration used by Next.js, enabling advanced build customizations and plugin integrations. |
Packaging-Configurations.html
| 1. optimizePackageImports | Automatically tree-shakes large libraries by importing only the specific modules being used, reducing bundle size while maintaining convenient import syntax. |
| 2. output | Configures build output format and deployment tracking, including standalone mode for containerized deployments and trace file generation for serverless functions. |
| 3. serverExternalPackages | Excludes specific npm packages from Server Components bundling, allowing them to use native Node.js require() for better compatibility with certain libraries. |
| 4. transpilePackages | Automatically processes and bundles dependencies from monorepo packages or node_modules that require transpilation, enabling modern JavaScript features in dependencies. |
| 5. turbotrace | Enables a more efficient Rust-based dependency tracing engine for better tree shaking and bundle optimization, reducing final application size. |
| 6. urlImports | Allows importing JavaScript modules directly from external URLs, enabling the use of ES modules from CDNs without local installation or bundling. |