new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · API reference · all subjects

config

577 notes in this subject, read out of this brain and free to use. This is page 8 of 10.

eslint-config-next package overview

Next.js provides eslint-config-next, an ESLint configuration package that includes the @next/eslint-plugin-next plugin along with recommended rule-sets from eslint-plugin-react and eslint-plugin-react-hooks. It makes it easy to catch common issues in Next.js applications.

ESLint migration from next lint in v16.0.0

In Next.js v16.0.0, next lint and the eslint next.config.js option were removed in favor of the ESLint CLI. A codemod is available to help migrate from next lint to ESLint CLI.

Integrating eslint-config-prettier with Next.js

To make ESLint and Prettier work together, install eslint-config-prettier as a dev dependency, then add prettier from eslint-config-prettier/flat to your eslint.config.mjs by spreading it after the Next.js config in the defineConfig array.

next lint removal in Next.js 16

Starting with Next.js 16, the next lint command is removed. The eslint option in next.config.js is no longer needed and can be safely removed.

Running ESLint on staged files with lint-staged

To use ESLint with lint-staged for staged git files, create .lintstagedrc.js in the project root. Define a buildEslintCommand function that takes filenames, converts them to relative paths, and returns an eslint --fix command with the filenames. Export a module object with key '*.{js,jsx,ts,tsx}' that executes buildEslintCommand on the filenames array.

Adding Next.js ESLint config to existing setup

If adding Next.js to an existing ESLint setup, spread the Next.js config into your array (e.g. ...nextConfig). ESLint applies configs in order, so later rules can override earlier ones for matching files. This approach works well for straightforward setups; for complex setups with conflicting file patterns or plugins, use the plugin directly instead.

Disabling ESLint rules in Next.js config

You can modify or disable any rules provided by react, react-hooks, or next plugins by changing them using the rules property in eslint.config.mjs. For example: {'react/no-unescaped-entities': 'off', '@next/next/no-page-custom-font': 'off'}.

Using @next/eslint-plugin-next directly

Use @next/eslint-plugin-next directly if you have conflicting plugins installed separately (react, react-hooks, jsx-a11y, import), custom parserOptions different from Next.js defaults (only if you customized Babel configuration), or eslint-plugin-import with custom Node.js and/or TypeScript resolvers. First install the plugin, then add it to eslint.config.mjs with the plugin in the plugins object and spread nextPlugin.configs.recommended.rules into rules.

Specifying rootDir for @next/eslint-plugin-next in monorepo

In a monorepo where Next.js is not installed in the root directory, you can tell @next/eslint-plugin-next where to find your Next.js application using the settings property in eslint.config.mjs. The rootDir setting can be a path (relative or absolute), a glob (e.g. 'packages/*/'), or an array of paths and/or globs.

@next/eslint-plugin-next rules in recommended config

The @next/eslint-plugin-next plugin includes the following rules in its recommended config: @next/next/google-font-display (enforce font-display behavior with Google Fonts), @next/next/google-font-preconnect (ensure preconnect is used with Google Fonts), @next/next/inline-script-id (enforce id attribute on next/script components with inline content), @next/next/next-script-for-ga (prefer next/script component for inline Google Analytics), @next/next/no-assign-module-variable (prevent assignment to module variable), @next/next/no-async-client-component (prevent Client Components from being async functions), @next/next/no-before-interactive-script-outside-document (prevent next/script beforeInteractive strategy outside pages/_document.js), @next/next/no-css-tags (prevent manual stylesheet tags), @next/next/no-document-import-in-page (prevent importing next/document outside pages/_document.js), @next/next/no-duplicate-head (prevent duplicate usage of <Head> in pages/_document.js), @next/next/no-head-element (prevent usage of <head> element), @next/next/no-head-import-in-document (prevent usage of next/head in pages/_document.js), @next/next/no-html-link-for-pages (prevent usage of <a> elements to navigate to internal Next.js pages), @next/next/no-img-element (prevent usage of <img> element due to slower LCP and higher bandwidth), @next/next/no-page-custom-font (prevent page-only custom fonts), @next/next/no-script-component-in-head (prevent usage of next/script in next/head component), @next/next/no-styled-jsx-in-document (prevent usage of styled-jsx in pages/_document.js), @next/next/no-sync-scripts (prevent synchronous scripts), @next/next/no-title-in-document-head (prevent usage of <title> with Head component from next/document), @next/next/no-typos (prevent common typos in Next.js data fetching functions), and @next/next/no-unwanted-polyfillio (prevent duplicate polyfills from Polyfill.io).

Default ignores in eslint-config-next

eslint-config-next ignores the following directories and files by default: .next/**, out/**, build/**, and next-env.d.ts.

ESLint flat config setup for Next.js

To set up ESLint with Next.js using flat config: (1) Install eslint and eslint-config-next as dev dependencies. (2) Create eslint.config.mjs that imports defineConfig and globalIgnores from 'eslint/config', and nextVitals from 'eslint-config-next/core-web-vitals'. (3) Define eslintConfig using defineConfig with spread nextVitals and globalIgnores that exclude .next/**, out/**, build/**, and next-env.d.ts. (4) Run ESLint with npx eslint . (or pnpm exec eslint ., yarn eslint ., bunx eslint .).

eslint-config-next/core-web-vitals configuration

eslint-config-next/core-web-vitals includes everything from the base config and upgrades rules that impact Core Web Vitals from warnings to errors. It is recommended for most projects.

eslint-config-next/typescript configuration

For TypeScript projects, eslint-config-next/typescript adds TypeScript-specific linting rules from typescript-eslint. It should be used alongside the base or core-web-vitals config.

adapterPath configuration example

Example of configuring a custom adapter in next.config.js: module.exports = { adapterPath: require.resolve('./my-adapter.js') }

adapterPath config option

The adapterPath config option in next.config.js specifies the path to a custom deployment adapter module. It should be set to the resolved path of the adapter file, typically using require.resolve().

NEXT_ADAPTER_PATH environment variable

The NEXT_ADAPTER_PATH environment variable can be set as an alternative to adapterPath in next.config.js to enable zero-config usage of a custom deployment adapter on deployment platforms.

next.config.mts for CommonJS projects

For CommonJS projects using native ESM syntax in configuration, use `next.config.mts` instead of `next.config.ts` to explicitly indicate it is an ESM module. This avoids Node.js reparsing the file as ESM when module syntax is detected.

Type IntelliSense for environment variables

Next.js can generate a `.d.ts` file in `.next/types` containing information about loaded environment variables for editor IntelliSense. If the same environment variable key is defined in multiple files, it is deduplicated according to the Environment Variable Load Order. To enable this feature, set `experimental.typedEnv: true` in `next.config.ts` and ensure the project uses TypeScript.

experimental.typedEnv configuration

To enable type IntelliSense for environment variables, configure `experimental.typedEnv` in `next.config.ts`: ```ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { experimental: { typedEnv: true, }, } export default nextConfig ``` Types are generated based on environment variables loaded at development runtime, which excludes variables from `.env.production*` files by default. To include production-specific variables, run `next dev` with `NODE_ENV=production`.

End-to-end type safety in App Router

The Next.js App Router provides enhanced type safety through: (1) No serialization of data between fetching function and page—you can fetch directly in components, layouts, and pages on the server without needing to serialize data for the client. Values like `Date`, `Map`, and `Set` can be used directly. (2) Streamlined data flow between components with colocated data fetching, eliminating the need to manually type boundaries between server and client.

Async Server Component data fetching example

Example of end-to-end type safety with async Server Components: ```tsx async function getData() { const res = await fetch('https://api.example.com/...') // The return value is *not* serialized // You can return Date, Map, Set, etc. return res.json() } export default async function Page() { const name = await getData() return '...' } ```

Route-aware type helpers in App Router

Next.js generates global type helpers for App Router routes available without imports and generated during `next dev`, `next build`, or via `next typegen`: `PageProps`, `LayoutProps`, and `RouteContext`.

IDE TypeScript plugin for Next.js

Next.js includes a custom TypeScript plugin and type checker that VSCode and other code editors can use for advanced type-checking and auto-completion. Enable it in VS Code by: (1) Opening the command palette (Ctrl/⌘ + Shift + P), (2) Searching for 'TypeScript: Select TypeScript Version', (3) Selecting 'Use Workspace Version'.

TypeScript IDE plugin capabilities

The Next.js TypeScript IDE plugin can: warn if invalid values for segment config options are passed, show available options and in-context documentation, ensure the 'use client' directive is used correctly, and ensure client hooks like `useState` are only used in Client Components.

Custom tsconfig path configuration

You can use a different TypeScript configuration for builds or tooling by setting `typescript.tsconfigPath` in `next.config.ts` to point Next.js to another `tsconfig` file: ```ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { typescript: { tsconfigPath: 'tsconfig.build.json', }, } export default nextConfig ```

Separate tsconfig for production builds

Example of using a different TypeScript configuration for production builds: ```ts import type { NextConfig } from 'next' const isProd = process.env.NODE_ENV === 'production' const nextConfig: NextConfig = { typescript: { tsconfigPath: isProd ? 'tsconfig.build.json' : 'tsconfig.json', }, } export default nextConfig ```

typescript.tsconfigPath behavior

The configured `tsconfig` file is used in `next dev`, `next build`, and `next typegen`. In development, only `tsconfig.json` is watched for changes. If you edit a different file name via `typescript.tsconfigPath`, you must restart the dev server to apply changes. IDEs typically read `tsconfig.json` for diagnostics and IntelliSense.

Disabling TypeScript errors in production builds

Next.js fails your production build (`next build`) when TypeScript errors are present. To dangerously allow production builds to complete even with errors, enable the `ignoreBuildErrors` option in the `typescript` config in `next.config.ts`. However, you should still run type checks as part of your build or deploy process.

ignoreBuildErrors configuration

To disable TypeScript error checking in production builds: ```ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { typescript: { // !! WARN !! // Dangerously allow production builds to successfully complete even if // your project has type errors. // !! WARN !! ignoreBuildErrors: true, }, } export default nextConfig ```

Checking TypeScript errors manually

You can run `tsc --noEmit` to check for TypeScript errors yourself before building. This is useful for CI/CD pipelines where you'd like to check for TypeScript errors before deploying.

Custom type declarations example

To add custom type declarations, create a new file like `new-types.d.ts` and reference it in your `tsconfig.json`: ```json { "compilerOptions": { "skipLibCheck": true }, "include": [ "new-types.d.ts", "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx" ], "exclude": ["node_modules"] } ```

Incremental type checking

Since v10.2.1, Next.js supports incremental type checking when enabled in your `tsconfig.json`. This can help speed up type checking in larger applications.

Async Server Components TypeScript requirements

To use an `async` Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and `@types/react` 18.2.8 or higher. If you are using an older version, you may see a `'Promise<Element>' is not a valid JSX element` type error. Updating to the latest version should resolve this issue.

jsconfig.json migration to TypeScript

If you already have a `jsconfig.json` file and want to migrate to TypeScript, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, then delete the old `jsconfig.json` file.

Route typing in custom components

To accept `href` in a custom component wrapping `next/link`, use a generic: ```tsx import type { Route } from 'next' import Link from 'next/link' function Card<T extends string>({ href }: { href: Route<T> | URL }) { return ( <Link href={href}> <div>My Card</div> </Link> ) } ```

Custom type declarations in Next.js

Do not modify `next-env.d.ts` as it is automatically generated and any changes will be overwritten. Instead, create a new `.d.ts` file (for example, `new-types.d.ts`) and reference it in your `tsconfig.json` `include` array.

TypeScript setup in Next.js projects

Next.js comes with built-in TypeScript support. When you create a new project with `create-next-app`, the necessary packages are automatically installed and proper settings are configured. To add TypeScript to an existing project, rename a file to `.ts` or `.tsx`, then run `next dev` and `next build` to automatically install dependencies and add a `tsconfig.json` file with recommended config options.

TypeScript 7 support in Next.js

TypeScript 7 does not provide the JavaScript compiler API. To use TypeScript 7 during `next build`, you must install it in your project using a package manager (pnpm, npm, yarn, or bun). Next.js uses the project-local `tsc` CLI by default, so no additional configuration is required. To use the JavaScript compiler API instead, set `experimental.useTypeScriptCli` to `false`.

TypeScript 7 CLI type checking behavior

When using TypeScript 7 CLI type checking: it prints native `tsc` diagnostics without Next.js-specific code frames or error rewrites for routes, pages, layouts, or route handlers. The CLI checks the complete project selected by your `tsconfig` file, including test files and `.next/dev/types` when included by that configuration. `next build --debug-build-paths` does not narrow the files that are type checked and produces a warning when used with this option.

next-env.d.ts file

Next.js generates a `next-env.d.ts` file in your project root that references Next.js type definitions. This file allows TypeScript to recognize non-code imports like images and stylesheets, and Next.js-specific types. It is regenerated by running `next dev`, `next build`, or `next typegen`. The file is managed by Next.js and should not be edited manually. It must be in your `tsconfig.json` `include` array and should be added to `.gitignore`.

TypeScript configuration file types

You can use TypeScript and import types in your Next.js configuration by creating a `next.config.ts` file. Module resolution in `next.config.ts` is currently limited to CommonJS. ECMAScript Modules (ESM) syntax is available when using Node.js native TypeScript resolver for Node.js v22.10.0 and higher.

next.config.ts example with NextConfig type

Example of type-checking a Next.js configuration file using TypeScript: ```ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { /* config options here */ } export default nextConfig ```

JSDoc type checking in next.config.js

When using `next.config.js`, you can add type checking in your IDE using JSDoc with the `@ts-check` comment: ```js // @ts-check /** @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } module.exports = nextConfig ```

Node.js native TypeScript resolver for next.config.ts

Node.js native TypeScript resolver is available on Node.js v22.10.0+ and detected via `process.features.typescript`. When present, `next.config.ts` can use native ESM syntax, including top-level `await` and dynamic `import()`. In Node.js v22.18.0+, this feature is enabled by default. For versions v22.10.0 to v22.17.x, opt in with `NODE_OPTIONS=--experimental-transform-types`.

next.config.ts with ESM projects

When `"type"` is set to `"module"` in `package.json`, your project uses ESM. In this case, you can write `next.config.ts` directly with ESM syntax. All `.js` and `.ts` files in ESM projects are treated as ESM modules by default, and you may need to rename files with CommonJS syntax to `.cjs` or `.cts` extensions.

Statically typed links in Next.js

Next.js can statically type links to prevent typos and errors when using `next/link`. In the App Router, it also types `next/navigation` methods like `push`, `replace`, and `prefetch`. Literal `href` strings are validated, while non-literal `href`s may require a cast with `as Route`. To enable this feature, set `typedRoutes: true` in `next.config.ts` and ensure the project uses TypeScript.

typedRoutes configuration

To enable statically typed links, configure `typedRoutes` in `next.config.ts`: ```ts import type { NextConfig } from 'next' const nextConfig: NextConfig = { typedRoutes: true, } export default nextConfig ``` Next.js will generate a link definition in `.next/types` containing information about all existing routes in your application.

tsconfig.json include for typedRoutes

If you set up your project without `create-next-app`, ensure the generated Next.js types are included by adding `.next/types/**/*.ts` to the `include` array in your `tsconfig.json`: ```json { "include": [ "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx" ], "exclude": ["node_modules"] } ```

Typed links usage with next/link and next/navigation

Example of using typed links in App Router: ```tsx 'use client' import type { Route } from 'next' import Link from 'next/link' import { useRouter } from 'next/navigation' export default function Example() { const router = useRouter() const slug = 'nextjs' return ( <> {/* Link: literal and dynamic */} <Link href="/about" /> <Link href={`/blog/${slug}`} /> <Link href={('/blog/' + slug) as Route} /> {/* TypeScript error if href is not a valid route */} <Link href="/aboot" /> {/* Router: literal and dynamic strings are validated */} <button onClick={() => router.push('/about')}>Push About</button> <button onClick={() => router.replace(`/blog/${slug}`)}>Replace Blog</button> <button onClick={() => router.prefetch('/contact')}>Prefetch Contact</button> {/* For non-literal strings, cast to Route */} <button onClick={() => router.push(('/blog/' + slug) as Route)}> Push Non-literal Blog </button> </> ) } ```

Navigation items with typed routes

Example of typing a data structure for navigation with routes: ```ts import type { Route } from 'next' type NavItem<T extends string = string> = { href: T label: string } export const navItems: NavItem<Route>[] = [ { href: '/', label: 'Home' }, { href: '/about', label: 'About' }, { href: '/blog', label: 'Blog' }, ] ``` Then render the links: ```tsx import Link from 'next/link' import { navItems } from './nav-items' export function Nav() { return ( <nav> {navItems.map((item) => ( <Link key={item.href} href={item.href}> {item.label} </Link> ))} </nav> ) } ```

How typed routes work

When running `next typegen`, `next dev`, or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application. This file is included in `tsconfig.json` and the TypeScript compiler uses it to provide feedback in your editor about invalid links.

supportsImmutableAssets config option

When config.supportsImmutableAssets is enabled, Next.js outputs immutable content-addressed static assets under the public path /_next/static/immutable/*. This prefix differentiates immutable static assets from non-immutable static assets at the CDN level. Set this property to true in adapter modifyConfig during phase-production-build to signal support for deploying immutable static assets.

config.outputHashSalt for rotating content hashes

You can use config.outputHashSalt to set a salt for the content hashes if you want to rotate the hashes for any reason, such as after a detected hash collision.

Edge Runtime node_modules ES Modules requirement

node_modules can be used in the Edge Runtime as long as they implement ES Modules and do not use native Node.js APIs.

Edge Runtime disabled JavaScript features

The following JavaScript language features are disabled in the Edge Runtime and will not work: eval, new Function(evalString), WebAssembly.compile, WebAssembly.instantiate.

Edge Runtime unstable_allowDynamic configuration

You can relax the dynamic code evaluation check in Proxy configuration using unstable_allowDynamic, which accepts a glob or array of globs relative to your application root folder. Example: export const config = { unstable_allowDynamic: ['/lib/utilities.js', '**/node_modules/function-bind/**'] }. Be warned that if these statements are executed on the Edge, they will throw and cause a runtime error.

Edge Runtime supported Crypto APIs

The Edge Runtime supports these Crypto APIs: crypto, CryptoKey, SubtleCrypto.

Node.js Runtime is default server runtime

Next.js has two server runtimes: Node.js Runtime (default) with access to all Node.js APIs used for rendering, and Edge Runtime with limited APIs.

Edge Runtime does not support ISR

The Edge Runtime does not support Incremental Static Regeneration (ISR).

Give your agent this brain