useLightningcss configuration example
Example configuration in next.config.ts: import type { NextConfig } from 'next'; const nextConfig: NextConfig = { experimental: { useLightningcss: false, } }; export default nextConfig. Example configuration in next.config.js: const nextConfig = { experimental: { useLightningcss: true, } }; module.exports = nextConfig.
lightningCssFeatures configuration example
Example configuration in next.config.ts: import type { NextConfig } from 'next'; const nextConfig: NextConfig = { experimental: { useLightningcss: true, lightningCssFeatures: { include: ['light-dark', 'oklab-colors'], exclude: ['nesting'], }, }, }; export default nextConfig.
useLightningcss config option
The useLightningcss configuration option enables experimental support for Lightning CSS with webpack as a CSS transformer and minifier written in Rust. When not set, Next.js defaults to PostCSS with postcss-preset-env on webpack. Turbopack uses Lightning CSS by default since Next 14.2 and this option has no effect on Turbopack. Set it in the experimental object of next.config.ts or next.config.js.
useLightningcss default behavior
By default, useLightningcss is set to false and is ignored on Turbopack. When set to true on webpack, it disables PostCSS processing.
lightningCssFeatures config option
The lightningCssFeatures option in experimental config allows overriding which CSS features Lightning CSS transpiles. It takes an object with include and exclude arrays. This applies to both webpack (when useLightningcss is enabled) and Turbopack. By default, Lightning CSS decides which features to transpile based on browserslist targets.
lightningCssFeatures include and exclude
lightningCssFeatures has two options: include (string[]) which specifies features to always transpile regardless of browser targets, and exclude (string[]) which specifies features to never transpile even when browser targets would require them.
lightningCssFeatures available individual features
Individual CSS features that can be included or excluded: nesting (CSS Nesting), not-selector-list (:not with multiple selectors), dir-selector (:dir() selector), lang-selector-list (:lang() with multiple languages), is-selector (:is() selector), text-decoration-thickness-percent (percentage values in text-decoration-thickness), media-interval-syntax (media query range interval syntax), media-range-syntax (media query range syntax like width >= 600px), custom-media-queries (@custom-media rules), clamp-function (clamp() function), color-function (color() function), oklab-colors (oklab() and oklch() colors), lab-colors (lab() and lch() colors), p3-colors (Display P3 colors), hex-alpha-colors (4 and 8 digit hex colors with alpha), space-separated-color-notation (space-separated color notation like rgb(0 0 0)), font-family-system-ui (system-ui font family), double-position-gradients (double-position gradient stops), vendor-prefixes (vendor-prefixed properties and values), logical-properties (logical properties and values), light-dark (light-dark() color function).
lightningCssFeatures composite groups
Composite groups provide shorthand for enabling multiple features at once: selectors (includes nesting, not-selector-list, dir-selector, lang-selector-list, is-selector), media-queries (includes media-interval-syntax, media-range-syntax, custom-media-queries), colors (includes color-function, oklab-colors, lab-colors, p3-colors, hex-alpha-colors, space-separated-color-notation, light-dark).
useLightningcss version history
In version 16.2.0, lightningCssFeatures was added. In version 15.1.0, support for useSwcCss was removed from Turbopack. In version 14.2.0, Turbopack's default CSS processor was changed from @swc/css to Lightning CSS, useLightningcss became ignored on Turbopack, and a legacy experimental.turbo.useSwcCss option was added.
headers matched parameters in key and value
Matched parameters from the source pattern can be used in both the header key and value fields. For example, in pattern /blog/:slug, you can use :slug in the value field or construct dynamic keys like x-slug-:slug.
headers basePath config option
The headers config supports a basePath property (boolean, default undefined). If basePath is false, the basePath from next.config.js won't be included when matching. This can be used for external rewrites only. By default, each source is automatically prefixed with the basePath unless basePath: false is set on the header.
headers locale config option
The headers config supports a locale property (boolean, default undefined). If locale is false, the locale should not be included when matching. By default, when using i18n support, each source is automatically prefixed to handle configured locales unless locale: false is set. If locale: false is used, you must prefix the source with a locale for it to be matched correctly.
headers Cache-Control immutable assets cannot be overridden
Next.js sets the Cache-Control header of 'public, max-age=31536000, immutable' for truly immutable assets and this cannot be overridden. These immutable files contain a SHA-hash in the file name, such as Static Image Imports. You cannot set Cache-Control headers in next.config.js for these assets.
headers CORS example with Access-Control headers
To set CORS headers, use Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers. Example: source: '/api/:path*', headers: [{key: 'Access-Control-Allow-Origin', value: '*'}, {key: 'Access-Control-Allow-Methods', value: 'GET, POST, PUT, DELETE, OPTIONS'}, {key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization'}]
headers X-DNS-Prefetch-Control value
The X-DNS-Prefetch-Control header controls DNS prefetching. Set key: 'X-DNS-Prefetch-Control', value: 'on' to allow browsers to proactively perform domain name resolution on external links, images, CSS, JavaScript, and more.
headers Strict-Transport-Security for HTTPS enforcement
The Strict-Transport-Security header informs browsers it should only be accessed using HTTPS, instead of HTTP. Example: key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' - this makes all present and future subdomains use HTTPS for a max-age of 2 years.
headers X-Frame-Options for clickjacking prevention
The X-Frame-Options header indicates whether the site should be allowed to be displayed within an iframe, which can prevent clickjacking attacks. Example: key: 'X-Frame-Options', value: 'SAMEORIGIN'. Note: This header has been superseded by CSP's frame-ancestors option, which has better support in modern browsers.
headers Permissions-Policy for feature and API control
The Permissions-Policy header allows you to control which features and APIs can be used in the browser. It was previously named Feature-Policy. Example: key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()'
headers X-Content-Type-Options nosniff value
The X-Content-Type-Options header prevents the browser from attempting to guess the type of content if the Content-Type header is not explicitly set. This can prevent XSS exploits for websites that allow users to upload and share files. The only valid value for this header is nosniff. Example: key: 'X-Content-Type-Options', value: 'nosniff'
headers config basic example structure
Example of headers configuration in next.config.js: module.exports = { headers() { return [{ source: '/about', headers: [{ key: 'x-custom-header', value: 'my custom header value' }, { key: 'x-another-custom-header', value: 'my other custom header value' }] }] } }
headers Referrer-Policy for navigation information control
The Referrer-Policy header controls how much information the browser includes when navigating from the current website to another. Example: key: 'Referrer-Policy', value: 'origin-when-cross-origin'
headers check priority before filesystem
Headers are checked before the filesystem which includes pages and /public files.
headers version history
Headers feature version history: v9.5.0 - Headers added; v10.2.0 - has added; v13.3.0 - missing added.
headers overriding behavior when paths match
If two headers match the same path and set the same header key, the last header key will override the first. For example, if both /:path* and /hello set x-hello, the value from /hello (matched last) takes precedence.
headers config function in next.config.js
The headers key in next.config.js can be defined as a synchronous or async function. It should return or resolve to an array of objects with source and headers properties. Each header object in the headers array must have key and value properties.
headers source property pattern matching
The source property defines the incoming request path pattern. Path matches are allowed using parameters like /blog/:slug. The pattern /blog/:slug matches /blog/first-post and /blog/post-1 but not nested paths like /blog/a/b. Patterns are anchored to the start, so /blog/:slug will not match /archive/blog/first-post.
headers path modifiers: wildcard, one-or-more, zero-or-one
Path parameters in source support modifiers: * (zero or more), + (one or more), ? (zero or one). For example, /blog/:slug* matches /blog, /blog/a, and /blog/a/b/c. The wildcard /blog/:slug* will match /blog/a/b/c/d/hello-world.
headers has and missing conditional matching
The has and missing fields allow conditional header application. Both the source and all has items must match and all missing items must not match for the header to be applied. Each has or missing item has fields: type (String: header, cookie, host, or query), key (String: the key from the selected type), and value (String or undefined: the value to check for; if undefined any value will match).
headers has missing regex value capture groups
In has and missing items, the value field can use a regex-like string to capture a specific part of the value using named capture groups. For example, value: 'first-(?<paramName>.*)' for value 'first-second' will capture 'second' as paramName, which becomes usable in header values and keys as :paramName.
useTypeScriptCli config example
To disable the TypeScript CLI checker and use the JavaScript compiler API instead, set experimental.useTypeScriptCli to false in next.config.ts or next.config.js: const nextConfig = { experimental: { useTypeScriptCli: false } }
useTypeScriptCli config option
The experimental.useTypeScriptCli configuration option controls whether Next.js runs the project-local TypeScript CLI (tsc command) or uses the TypeScript JavaScript compiler API for type checking during production builds. By default, it is true, enabling the CLI checker which supports TypeScript 6 and TypeScript 7. Setting it to false uses the TypeScript JavaScript compiler API instead, but this is unavailable in TypeScript 7, causing next build to exit with an error if you opt out while using TypeScript 7.
useTypeScriptCli behavior with TypeScript diagnostics
When useTypeScriptCli is enabled, TypeScript diagnostics are printed directly from tsc. Next.js-specific code frames and error rewriting are not applied.
useTypeScriptCli project scope
When useTypeScriptCli is enabled, the complete project selected by the configured tsconfig file is checked, including test files and .next/dev/types when included. The --debug-build-paths option does not limit this set and produces a warning when combined with the CLI checker.
useTypeScriptCli with Next.js setup
When useTypeScriptCli is enabled, Next.js continues to generate next-env.d.ts and route types and applies its recommended tsconfig settings before running the checker.
useTypeScriptCli interaction with other TypeScript config
The typescript.tsconfigPath config option selects the project passed to tsc when useTypeScriptCli is enabled. The typescript.ignoreBuildErrors config option skips the type-checking step entirely, including the CLI checker.
webVitalsAttribution provides attribution details
When webVitalsAttribution is enabled, it allows obtaining in-depth information like entries for PerformanceEventTiming, PerformanceNavigationTiming, and PerformanceResourceTiming. This helps pinpoint the specific elements and resources contributing to Web Vitals issues.
CLS attribution identifies shifted elements
When CLS (Cumulative Layout Shift) attribution is enabled, it helps identify the first element that shifted when the largest layout shift occurred on the page.
LCP attribution identifies content element and resource
When LCP (Largest Contentful Paint) attribution is enabled, it helps identify the element corresponding to the LCP for the page. If the LCP element is an image, the attribution provides the URL of the image resource, allowing optimization of the specific asset.
webVitalsAttribution config option
The webVitalsAttribution option in next.config.js enables Web Vitals attribution, which provides in-depth information about the source of Web Vitals issues. It is disabled by default and can be enabled per metric. The option accepts an array of metric names that correspond to web-vitals metrics, such as 'CLS' and 'LCP'.
webVitalsAttribution syntax
To enable webVitalsAttribution in next.config.js, add an experimental object with the webVitalsAttribution property set to an array of metric strings. Example: module.exports = { experimental: { webVitalsAttribution: ['CLS', 'LCP'] } }
useOffline connectivity check backoff schedule
Delays between connectivity checks are stepped, not exponential, and capped at 3 seconds. Attempt 1: 500 ms delay before next check. Attempt 2: 1 s delay. Attempt 3: 2 s delay. Attempt 4 and after: 3 s delay. The browser's online event short-circuits the current wait and runs a connectivity check immediately.
Connectivity check method
Each connectivity check issues a single HEAD request to the current page's URL with the RSC header set, the same endpoint navigations use. The request is aborted after 200 ms. Two outcomes count as 'online': the fetch resolves normally, or the 200 ms timeout aborts the request. A truly offline request fails almost instantly (DNS or TCP error), so if it's still pending at 200 ms the TCP handshake succeeded and the server is reachable. Any other rejection schedules the next check.
Offline state entry paths
The offline state is entered through two paths: Browser event - Next.js registers a window.addEventListener('offline', ...) listener. When the OS reports the network interface as down, the offline state flips on immediately. Failed fetch - Any navigation, prefetch, or Server Action request whose fetch() rejects with a non-abort, non-timeout error calls into the offline module, catching cases where the browser still reports navigator.onLine === true but the actual request cannot reach the origin.
useOffline behaviors when enabled
When useOffline is enabled, Next.js will: listen for the browser's offline and online events to track connectivity; detect network failures on navigation, prefetch, and Server Action requests; poll for connectivity using HEAD requests with backoff while offline; automatically retry blocked requests once connectivity is restored; and make the useOffline hook available from next/offline.
useOffline configuration option
The useOffline configuration option enables offline connectivity detection and automatic retry of failed navigation, prefetch, and Server Action requests. When enabled, it also exposes the useOffline hook for reading the current offline state from Client Components.
useOffline configuration example
To enable useOffline, add it to the experimental configuration in next.config.ts or next.config.js:
TypeScript:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useOffline: true,
},
}
export default nextConfig
JavaScript:
module.exports = {
experimental: {
useOffline: true,
},
}
useOffline version history
The experimental.useOffline configuration option was introduced in v16.x.0.
useOffline traffic control at reconnection
useOffline prevents runaway traffic bursts: while offline, failed fetches reject locally at the browser's network layer and never reach the origin; the polling loop issues one HEAD request at a time with delays capped at 3 seconds; when connectivity returns, each pending navigation and Server Action fires once with only the last navigation attempt kept pending; prefetches run through the existing prefetch queue, not all at once.
useOffline retry of framework requests
While the offline state is active, any navigation, prefetch, or Server Action waits for the next connectivity check to succeed, whether it was newly issued or already in flight when the connection dropped. When the check succeeds, the request runs once with no extra backoff. If it fails with a network error, the app re-enters the offline state and the polling loop starts again.
useOffline polling loop behavior
The polling loop never gives up on its own. It continues at the 3-second cap until a check succeeds or the page unloads. A device that goes offline for hours and then regains connectivity will have its polling loop resume and resolve normally.
webpack config plugin alternatives
Some commonly requested features are available as official Next.js plugins: @next/mdx for MDX support and @next/bundle-analyzer for bundle analysis, which may reduce the need for custom webpack configuration.
webpack function signature and parameters
The webpack configuration function in next.config.js receives two arguments: the config object and an options object. The options object contains: buildId (String, unique identifier between builds), dev (Boolean, indicates development compilation), isServer (Boolean, true for server-side and false for client-side compilation), nextRuntime (String | undefined, either 'edge' or 'nodejs' for server-side, undefined for client-side), and defaultLoaders (Object containing babel configuration). The function must return the modified config.
webpack function execution frequency
The webpack function in next.config.js is executed three times during the build: twice for the server (nodejs and edge runtimes) and once for the client. The isServer property can be used to distinguish between client and server configurations.
nextRuntime property behavior
The nextRuntime property indicates the target runtime for server-side compilation. It is either 'edge' or 'nodejs', and is undefined for client-side compilation. The isServer property is true when nextRuntime is 'edge' or 'nodejs'. The 'edge' runtime is currently for proxy and Server Components in edge runtime only.
defaultLoaders object structure
The defaultLoaders object passed in the webpack function's second argument contains default loaders used internally by Next.js. It includes a babel property which is an Object containing the default babel-loader configuration.
webpack config changes not covered by semver
Changes to webpack configuration in Next.js are not covered by semantic versioning, so custom webpack modifications should proceed at your own risk.
webpack config example with custom loader
Example of extending webpack config by adding a custom loader that depends on babel-loader:
```js
module.exports = {
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx/,
use: [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: pluginOptions.options,
},
],
})
return config
},
}
```
This example shows how to add a custom MDX loader that chains with the default babel loader.
Check for built-in feature support before custom webpack config
Before adding custom webpack configuration, verify that Next.js doesn't already support your use case. Common features with built-in support include CSS imports, CSS modules, Sass/SCSS imports, Sass/SCSS modules, and customizing babel configuration (Pages Router only).
Configuration documentation overview
Next.js has configuration documentation covering how to configure Next.js applications. This appears to be an index page for configuration topics.
eslint-config-next base configuration
eslint-config-next is the base configuration that includes Next.js, React, and React Hooks rules. It supports both JavaScript and TypeScript files.