Configuration

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:
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:
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:
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:
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

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
viewTransition Enable ViewTransition API from React in App Router

CSS

cssChunking Use the `cssChunking` option to control how CSS files are chunked in your Next.js application.
inlineCss Enable inline CSS support.
sassOptions Configure Sass options.
useLightningcss Enable experimental support for Lightning CSS.

Rendering

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.
serverActions Configure Server Actions behavior in your Next.js application.
staticGeneration* Learn how to configure static generation in your Next.js application.
ppr Learn how to enable Partial Prerendering in Next.js.
images Custom configuration for the next/image loader
webVitalsAttribution Learn how to use the webVitalsAttribution option to pinpoint the source of Web Vitals issues.

Server

allowedDevOrigins Use `allowedDevOrigins` to configure additional origins that can request the dev server.
crossOrigin Use the `crossOrigin` option to add a crossOrigin tag on the `script` tags generated by `next/script`.
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.
basePath Use `basePath` to deploy a Next.js application under a sub-path of a domain.
assetPrefix Learn how to use the assetPrefix config option to configure your CDN.
devIndicators Configuration options for the on-screen indicator that gives context about the current route you're viewing during development.

URL

redirects Add redirects to your Next.js app.
rewrites Add rewrites to your Next.js app.
trailingSlash Configure Next.js pages to resolve with or without a trailing slash.
typedRoutes Enable experimental support for statically typed links.
logging Configure how data fetches are logged to the console when running Next.js in development mode.
headers Add custom HTTP headers to your Next.js app.
poweredByHeader Next.js will add the `x-powered-by` header by default. Learn to opt-out of it here.
authInterrupts Learn how to enable the experimental `authInterrupts` configuration option to use `forbidden` and `unauthorized`.

Caching

cacheLife Learn how to set up cacheLife configurations in Next.js.
cacheHandler Configure the Next.js cache used for storing and revalidating data to use any external service like Redis, Memcached, or others.
staleTimes Learn how to override the invalidation time of the Client Router Cache.
serverComponentsHmrCache Configure whether fetch responses in Server Components are cached across HMR refresh requests.
expireTime Customize stale-while-revalidate expire time for ISR enabled pages.
onDemandEntries Configure how Next.js will dispose and keep in memory pages created in development.
useCache Learn how to enable the useCache flag in Next.js.
generateEtags Next.js will generate etags for every page by default. Learn more about how to disable etag generation here.
dynamicIO Learn how to enable the dynamicIO flag in Next.js.

Compiler

distDir Set a custom build directory to use instead of the default .next directory.
generateBuildId Configure the build id, which is used to identify the current build in which your application is being served.
reactCompiler Enable the React Compiler to automatically optimize component rendering.
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
webpack Learn how to customize the webpack config used by Next.js
env Learn to add and access environment variables in your Next.js application at build time.
urlImports Configure Next.js to allow importing modules from external URLs.
mdxRs Use the new Rust compiler to compile MDX files in the App Router.
eslint Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.
typescript Next.js reports TypeScript errors by default. Learn to opt-out of this behavior here.
exportPathMap Customize the pages that will be exported as HTML files when using `next export`.
productionBrowserSourceMaps Enables browser source map generation during the production build.
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.
serverExternalPackages Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.
optimizePackageImports API Reference for optimizePackageImports Next.js Config Option
pageExtensions Extend the default page extensions used by Next.js when resolving pages in the Pages Router.