next.js: next-lint Doesn't Support ESLint 9

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/vigilant-pine-6wmz8y

To Reproduce

  1. Add next lint script to package.json per https://nextjs.org/docs/app/building-your-application/configuring/eslint
  2. Add .eslintrc.json to project per https://nextjs.org/docs/app/building-your-application/configuring/eslint
{
  "extends": "next/core-web-vitals"
}
  1. Run lint and get an error
➜  /workspace git:(master) ✗ npm run lint

> lint
> next lint

Invalid Options:
- Unknown options: useEslintrc, extensions, resolvePluginsRelativeTo, rulePaths, ignorePath, reportUnusedDisableDirectives
- 'extensions' has been removed.
- 'resolvePluginsRelativeTo' has been removed.
- 'ignorePath' has been removed.
- 'rulePaths' has been removed. Please define your rules using plugins.
- 'reportUnusedDisableDirectives' has been removed. Please use the 'overrideConfig.linterOptions.reportUnusedDisableDirectives' option instead.

Current vs. Expected behavior

Expected lint to run successfully, but it failed with errors.

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP PREEMPT_DYNAMIC Sun Aug  6 20:05:33 UTC 2023
  Available memory (MB): 4102
  Available CPU cores: 2
Binaries:
  Node: 20.9.0
  npm: 9.8.1
  Yarn: 1.22.19
  pnpm: 8.10.2
Relevant Packages:
  next: 14.2.1-canary.0 // Latest available version is detected (14.2.1-canary.0).
  eslint-config-next: 14.1.4
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.1.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

ESLint (eslint-config-next)

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local), next start (local)

Additional context

It looks like this is coming from https://github.com/vercel/next.js/blob/canary/packages/next/src/cli/next-lint.ts. This needs to be changed to support ESLint 9’s flat config https://eslint.org/docs/latest/use/migrate-to-9.0.0#flat-config. The migration guide is at https://eslint.org/docs/latest/use/configure/migration-guide

NEXT-3112

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 349
  • Comments: 110 (24 by maintainers)

Commits related to this issue

Most upvoted comments

we’re on it, gonna land very very soon, thank you all for your patience! And yes, it will be part of Next 15!

The reason why it took us so long to get to is that some of the upstream dependencies were also not up to date, so we were waiting on them.

Bumping this, it is breaking package update automation at my corp

Not a fix but you can ignore eslint during build like so:

// next.config.js
module.exports = {
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
}

This way you have manual control over eslint, you can run a custom linting config before build.

IMHO, the adoption should be done gradually in the following steps:

  • Migrate eslint-config-next, so it exposes both the legacy eslintrc config and the new flat config.
  • Change Next.js internal ESLint implementation, allows it to accept both the legacy config .eslintrc and the new flat config eslint.config.js.
  • Change next lint so that it can accept eslint.config.js
  • Change create-next-app built-in template to use eslint.config.js
  • Change Next.js example to use eslint.config.js

Same issue here, I thought I was crazy. Downgrade to an old version for now… 🤖 😸

devDependencies:
- eslint 9.1.1
+ eslint 8.57.0 (9.1.1 is available)

Bumping this for visibility, it does not seem to prevent build but unsure of the impact.

✓ Compiled successfully
   Linting and checking validity of types  .. 
⨯ ESLint: Invalid Options: - Unknown options: useEslintrc, extensions - 'extensions' has been removed.
✓ Linting and checking validity of type
"next": "^14.2.0",
"eslint-config-next": "^14.2.0",
"eslint": "^9.0.0",
{
  "extends": "next/core-web-vitals"
}

We’re planning on releasing an RC2 today and 15 in the following week, assuming there’s no blockers.

ESLint v8 is now official EOL as of today: https://eslint.org/blog/2024/09/eslint-v8-eol-version-support/#eslint-v8.x-end-of-life-is-october-5%2C-2024

I skimmed through this thread and it seems like the only workaround identified was to downgrade to v8, so with this change, Next is now shipping with unsupported packages.

Hopefully Vercel can dedicate some folks on this. To me, it seems like a pretty bad look to have a Next package script just not work OOTB. Vercel is an actual company, not a scrappy startup or a loose group of volunteers, so IMO they should find it easier to get some hands on this.

For those using @next/eslint-plugin-next, the ESLint Compatibility Utilities worked for me. CodeSandbox example: https://codesandbox.io/p/devbox/vibrant-hill-29h4tw

npm install --save-dev @next/eslint-plugin-next @eslint/compat @eslint/eslintrc

eslint.config.mjs:

import { fixupConfigRules } from "@eslint/compat";
import { FlatCompat } from "@eslint/eslintrc";

const compat = new FlatCompat();

export default [
  {
    ignores: [".next/"],
  },
  ...fixupConfigRules(compat.extends("plugin:@next/next/core-web-vitals")),
];

package.json:

{
  "scripts": {
    "lint": "eslint"
  },
  "dependencies": {
    "next": "^14.2.3",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@eslint/compat": "^1.0.1",
    "@eslint/eslintrc": "^3.0.2",
    "@next/eslint-plugin-next": "^14.2.3",
    "eslint": "^9.2.0"
  }
}

It looks like Vercel has underestimated ESLint. I think a dedicated team is needed for the migration as soon as possible. ESLint 8 has been deprecated for a week now, and all projects will start migrating to ESLint v9.

@SalahAdDin @AlbinoGeek @DamienCassou there might be an easier migration path, I wrote a setup guide for Eslint 9 with Next.js, starting from a minimal app, this should probably scale to work with any project but please let me know if there is any issue, this is kind of a long read : Eslint 9 & Next.js — Setup Guide


TLDR;

  • You should install and override eslint 9 to avoid any issues on npm install
  • You should declare your own build and lint rules
  • You should opt-out of Next.js linting during build
  • You should migrate your .eslintrc.(js|json|yml) using ESlint’s @eslint/migrate-config
  • You should patch problematic plugins using ESLint’s fixupPluginRules

The resulting files should look something like this

package.json

{
...
  "scripts": {
    "dev": "next dev",
    "build": "npm run lint && next build",
    "start": "next start",
    "lint": "eslint ."
   },
  ...
  "devDependencies": {
    ...
    "eslint": "^9.8.0",
    ...
  },
  "overrides": {
    "eslint": "^9.8.0"
  }
}

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;

eslint.config.mjs

// @ts-check
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupPluginRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

const pluginsToPatch = [
  "@next/next",
  // Other plugins to patch, example :
  // "react-hooks",
];

const compatConfig = [...compat.extends("next/core-web-vitals")];

const patchedConfig = compatConfig.map((entry) => {
  const plugins = entry.plugins;
  for (const key in plugins) {
    if (plugins.hasOwnProperty(key) && pluginsToPatch.includes(key)) {
      plugins[key] = fixupPluginRules(plugins[key]);
    }
  }
  return entry;
});

const config = [...patchedConfig, { ignores: [".next/*"] }];

export default config;

I’ve forced the usage of eslint-plugin-import-x by setting an override for eslint-config-next in my package.json:

{
  # ...
  "overrides": {
    "eslint-config-next": {
      "eslint": "$eslint", # this means using dependency's value
      "eslint-plugin-import": "npm:eslint-plugin-import-x@4.2.1"
    }
  }
}

This seems to work but I did have to disable a @next rule, because it isn’t compatible with eslint@9:

'@next/next/no-duplicate-head': 'off',

I’m curious if is this works for everyone!

Update: ESLint 9 is now supported as of the Next.js 15 RC 2. v15 stable release coming soon 🙏

https://x.com/nextjs/status/1846276572812124565

Just pointing out that the PRs listed in https://github.com/vercel/next.js/issues/64409#issuecomment-2146312946 are merged. As best I can tell, ESLint 9 support is no longer blocked by downstream dependencies.

Not a fix but you can ignore eslint during build like so:

// next.config.js
module.exports = {
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
}

This way you have manual control over eslint, you can run a custom linting config before build.

I went back to version "eslint": "^8.41.0" and the error stopped.

So, when will the ESLint v9.x migration be complete?

Nobody knows when or if this will happen. You have the following options right now:

  • Stay on eslint 8 and wait and see if support eventually rolls out (you should probably do this),
  • Try one of the various hacks mentioned above,
  • Migrate away from eslint and lose first-class support from next,
  • Live without linting (not the end of the world),
  • Fix it yourself and open a PR, or
  • Go sponsor the project, donate some money to try and help get the work done.

This is the nature of volunteer-operated FOSS. There is no guarantee, there is no obligation.

rant By choosing to use an open source project like next, you are assuming a certain amount of risk, and you are transitively assuming hidden risk from all the nested dependencies of such a project. The big lie you are told is that such frameworks abstract away all these problems, that you will never have to deal with them. But the truth is that if you can't deal with them, then using these dependencies is a bad choice for commercial production applications.

If you don’t have your own mirroring npm registry setup, you’re not ready to use FOSS in production. If you can’t dig into the underlying source code and understand on at least a basic level what’s going on, you’re not ready to use FOSS in production. If you can’t figure out your own workarounds to problems like the one described in this thread, you’re not ready to use FOSS in production.

It really is disingenuous for organizations to represent projects like next as a batteries-included, comprehensive solution to your problem of building a website, but I also understand that that’s the state of market competition. If any framework described on their marketing page what responsibilities users are actually taking on by building something on top of their code, everybody would be scared off toward something that hides those inevitable complexities from potential users.

Yeah it’s breaking change because ESLint 9.0.0 is a major release with a ton of breaking changes. You better hope NextJS didn’t adhoc around every single ESLint implementation detail, so the migration to the newest version wouldn’t take forever on their end. For now a “fix” is to update next and eslint-config-next to 14.2.1 which limits the range of required ESLint version to eslint@"^7.23.0 || ^8.0.0" and therefore will crash on install/update instead.

So wait until Next 15 is out? 🤦🏻‍♂️ By then eslint 10 might probably drop and the cycle starts all over

@ztanner , is Next.js 15 considering supporting Eslint v9?

IMHO, the adoption should be done gradually in the following steps:

  • Migrate eslint-config-next, so it exposes both the legacy eslintrc config and the new flat config.

  • Change Next.js internal ESLint implementation, allows it to accept both the legacy config .eslintrc and the new flat config eslint.config.js.

  • Change next lint so that it can accept eslint.config.js

  • Change create-next-app built-in template to use eslint.config.js

  • Change Next.js example to use eslint.config.js

I would like to add that the new flat config file can have multiple names:

  • eslint.config.js
  • eslint.config.mjs
  • eslint.config.cjs

Source: https://eslint.org/docs/latest/use/configure/configuration-files#configuration-file

For those using TypeScript + ESLint + NextJS + Prettier, here’s a simplified, yet complete eslint.config.mjs configuration that works for my team, based on @poksme’s solution:

// @ts-check
import { fixupPluginRules } from '@eslint/compat'
import { FlatCompat } from '@eslint/eslintrc'
import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'

// NOTE: This is a workaround for ESLint plugins that have not been updated to use the new ESLint 9 flat config format.
// See https://github.com/vercel/next.js/issues/64409
function fixCompatibility(...configNames) {
  return new FlatCompat().extends(...configNames).map((entry) => {
    const plugins = entry.plugins
    for (const key in plugins) {
      // eslint-disable-next-line no-prototype-builtins
      if (plugins.hasOwnProperty(key)) {
        plugins[key] = fixupPluginRules(plugins[key])
      }
    }
    return entry
  })
}

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.strictTypeChecked,
  ...tseslint.configs.stylisticTypeChecked,
  /**
   * If you want to add other ESLint configs / plugins:
   * - either add its ESLint 9 flat config before this comment
   * - or if they don't support it yet, add the name you'd put in the .eslintrc.json to the `fixCompatibility` call
   */
  // @ts-expect-error - Probably due to weird typing bug, but it works: "Argument of type 'FlatConfig' is not assignable to parameter of type 'ConfigWithExtends'. Types of property 'languageOptions' are incompatible."
  ...fixCompatibility('next', 'plugin:prettier/recommended'),
  {
    languageOptions: {
      parser: tseslint.parser,
      ecmaVersion: 2022,
      sourceType: 'module',
      parserOptions: {
        project: true,
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
        ecmaFeatures: { jsx: true },
      },
    },
  },
  {
    files: ['eslint.config.mjs', 'next.config.mjs'],
    ...tseslint.configs.disableTypeChecked,
  },
  {
    ignores: ['.next/**/*', 'node_modules/**/*', 'dist/**/*', 'build/**/*', 'coverage/**/*'],
  }
)

Including the packages mentioned in @poksme’s setup guide, be sure to have all the following installed:

npm install --save-dev @eslint/compat @eslint/eslintrc @eslint/js @types/eslint__js eslint eslint-config-next eslint-plugin-prettier eslint-plugin-react-hooks prettier typescript typescript-eslint

and use

  "overrides": {
    "eslint": "^9"
  }

in your package.json to resolve the package conflict between ESLint v9 and eslint-config-next.

@samcx the Next.js team may also want to consider switching from eslint-plugin-import to eslint-plugin-import-x, due to incompatibilities and other multiple issues and missing features

I mentioned something similar in my comment on the eslint-plugin-import issue (unfortunately marked as spam) - that it’s possible to switch to eslint-plugin-import-x:


In case anyone wants to upgrade to ESLint v9 now, an alternative is to switch to the eslint-plugin-import-x fork:

  1. Install eslint-plugin-import-x
  2. Install @typescript-eslint/parser for TypeScript support
-import eslintImport from 'eslint-plugin-import';
+import eslintImportX from 'eslint-plugin-import-x';

/** @type {import('@typescript-eslint/utils/ts-eslint').FlatConfig.ConfigArray} */
const configArray = [
  {
    plugins: {
-     import: eslintImport,
+     'import-x': eslintImportX,
    },
    settings: {
      'import-x/parsers': {
        '@typescript-eslint/parser': ['.ts', '.tsx'],
      },
      'import-x/resolver': {
        // Load <rootdir>/tsconfig.json
        typescript: true,
        node: true,
      },
    },
    rules: {
      // Error on imports that don't match the underlying file system
-     // https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
-     'import/no-unresolved': 'error',
+     // https://github.com/un-ts/eslint-plugin-import-x/blob/master/docs/rules/no-unresolved.md
+     'import-x/no-unresolved': 'error',
  },
];

@jamiter From the moment the ESLint team started the tracking threads below, someone from Vercel should’ve had a team looking into which dependencies are in use, what they might be able to do help get them upgraded on time (or even earlier), and an idea of how bad things might look if they ended up still shipping with v8 after it was EOL.

But here we are.

How could eslint 9 and its configuration get so complicated? It’s mind-boggling.

@feedthejim Wouldnt backporting this to v14 be better? Eslint 8 is already EOL while next v14 is still active dev.

Hi everyone,

Unfortunately, we were not able to ship this with Next.js 15. The current understanding of this is that we cannot do a clean ship of this until certain plugins add support for ESLint v9. For example:

We will share updates as they come!

Question on import plugin, but it looks like they released support two weeks ago, but through a different PR?

sources:

Is there more that is being waited on or was that the only thing that was needed?

EDIT: forgot link to PR 🤦🏻‍♀️

@bvobart thank you for taking the time to go through my guide and test if for yourself !

Following your comment, I wanted to confirm that setting up Typescript ESLint and Prettier ESLint was as simple as possible using the flat config. So continuing on my example project, I was able to add both with 2 lines change for each.

Setup Typescript ESLint

npm install --save-dev eslint @eslint/js @types/eslint__js typescript typescript-eslint
  • Import Typescript ESLint and add it to your config array in eslint.config.mjs
 // @ts-check  
 import path from "node:path";  
 import { fileURLToPath } from "node:url";  
 import js from "@eslint/js";  
+import ts from "typescript-eslint";  
 import { FlatCompat } from "@eslint/eslintrc";  
 import { fixupPluginRules } from "@eslint/compat";  
  
...  
  
 const config = [  
   ...patchedConfig,   
+  ...ts.configs.recommended,  
   { ignores: [".next/*"] },  
 ];

Setup Prettier ESLint

npm install --save-dev eslint-plugin-prettier eslint-config-prettier  
npm install --save-dev --save-exact prettier
  • Import Prettier ESLint and add it to your config array in eslint.config.mjs
// @ts-check  
 import path from "node:path";  
 import { fileURLToPath } from "node:url";  
 import js from "@eslint/js";  
 import ts from "typescript-eslint";  
+import prettierConfigRecommended from "eslint-plugin-prettier/recommended";  
 import { FlatCompat } from "@eslint/eslintrc";  
 import { fixupPluginRules } from "@eslint/compat";  
  
...  
  
 const config = [  
   ...patchedConfig,   
   ...ts.configs.recommended,  
+  prettierConfigRecommended, // Last since it disables some previously set rules  
   { ignores: [".next/*"] },  
 ];

-> I have updated my guide to add these simple examples.


Your provided code seems quite a bit more complex, this is due to TypeChecked linting as documented here. It requires a bit more setup, but should be simpler than your current configuration, here is an example with recommendedTypeChecked but this also works with any TypeChecked ruleset :

  • Add the ruleset and required configuration to eslint.config.mjs
 const config = [  
   ...patchedConfig,   
-  ...ts.configs.recommended,
+  ...ts.configs.recommendedTypeChecked,
+  {
+    languageOptions: {
+      parserOptions: {
+        projectService: true,
+        tsconfigRootDir: import.meta.dirname,
+      },
+    },
+  },
   prettierConfigRecommended, // Last since it disables some previously set rules  
   { ignores: [".next/*"] },  
 ];
  • (Might be specific to your current ts config) Include config files to your tsconfig.json
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "*.config.mjs"],

And you should be done !

@SalahAdDin

Why do we need so many complicated configurations?

This is a single configuration file that replaces your previous configuration file. That is mostly auto-generated by running npx @eslint/migrate-config .eslintrc.json my addition here is a map and a for loop to patch specific plugins. We need this because of 30+ breaking changes introduced by ESLint 9 in order to enable features and developer experience enhancements in the future.

why do we need to install more extra pages?

Not sure what you call pages, if you mean packages it’s because ESLint after introducing many breaking changes also spent time, energy and ressources to develop utilities to help developers like us migrate to the newer ESLint 9 without having to wait for upstream fixes. All of these packages are devDependencies and will not have impact on your production bundle / performance.

It does not seem simple and you used the migration script, you didn’t create a simple configuration.

I invite you to re-read my message, I was saying “easier migration path” not “I created a simple configuration”. That being said, I believe this is the minimal necessary changes to fix a complex problem.

Please be mindful of people in the community trying to help on this issue and also open source developers like the one working on ESLint and Next.js providing utilities, options and opt-outs to help on complex matters.

we cannot do a clean ship of this until certain plugins add support for ESLint v9

@samcx just as a note (probably you’ve already seen the tweet thread), there are ways of shipping a config with those unsupporting plugins like eslint-plugin-react:

As long as there green checkmarks in this comment (and the purple ones are not closed with won't fix), the framework is blocked from updating to ESLint 9.

I wouldn’t be so pessimistic!

It’s not pessimism. But I don’t see a good reason to upgrade to a version filled with experimental changes just for the sake of using eslint 9, at this rate I’m considering dropping next altogether.

eslint/eslint#18391 does list import as having eslint 9 support, which seems to be incorrect. It was stated 6 days ago that eslint-plugin-import does not yet support eslint@9, and the peer dependency is still set to eslint@8.

If you look at the entries for import in each of those tracking tables, you’ll see that they both point at the same issue, https://github.com/import-js/eslint-plugin-import/issues/2556. The problem is that this issue is only to implement flat config support, so the table in eslint/eslint#18391 should really not list it. I suspect that both tables were updated to indicate success when the one linked issue was closed, and mistakenly so.

The issue for supporting eslint@9, the one that should be linked in that table, is https://github.com/import-js/eslint-plugin-import/issues/2948 which has been locked.

Edit: I left a comment over there to try and get the table corrected.

Double edit: It’s now been corrected. Also the maintainer of eslint-plugin-import +1’d my comment, which I’ll take as double-confirmation that it is correct to say that it does not currently support eslint@9.

@controversial

OMG… 😢

So, when will the ESLint v9.x migration be complete?

ESLint v8.x end of life is October 5, 2024.

As of now, there is already less than a month left until EOL.

This is the issue where we can see the migration plan on the Next.js side, but is there any discussion going on?

If you know, please let us know 🙏


P.S. Why 👎 emoji added to my comment…? Is there anyone who can tell me the reason? (I’m sorry if I said it wrong. I’m not a native English speaker)

If only eslint-import is blocker right now then maybe its a good to consider use their fork https://github.com/un-ts/eslint-plugin-import-x ? Looks like it’s a drop in replacement

We’ve also abanndoned next-lint, and working on moving away from NextJS entirely honestly, the platform lock-in and requirement to run their server because of the Image component, fonts, and other things, are all deal-breakers for us.

@ldeveber that’s not correct; eslint-plugin-import has not released support for eslint v9

see import-js/eslint-plugin-import#2996

The PR you linked adds support for using flat config under eslint v8, which is not what this issue is about.

Quoting the first message in the PR you linked:

And just to be clear, this is only aiming to provide support for flat config (which is a separate issue than supporting eslint v9)

Thank you, but my question still remains:

Is there more that is being waited on or was that the only thing that was needed?

Or more specifically, are there specific parts of 9 that are being waited on, or just allowing 9 as a dependency?

EDIT: Additionally trying to understand, because the official eslint version 9 support tracking listed it as supported? They’re tracking flat config as a second post, and since BOTH were updated it makes it seem like full support is there. So if that is wrong, I would like to provide them with what is missing to fix the listing as to not mislead others?

And just want to clarify that I’m looking for more details to help, not trying to harp on what you guys do!

I recently updated my guide here to use fixupConfigRules instead of fixupPluginRules + a map + a list of deps to patch. This results in a more simple migration & catch-all strategy.

TLDR; Updated minimum necessary changes to run eslint 9 with next.js build flow

  1. npm install -D eslint@latest
  2. Override eslint version and add the necessary changes to scripts in package.json
 ...
   "scripts": {
     "dev": "next dev",
+    "prebuild": "npm run lint",
     "build": "next build",
     "start": "next start",
-    "lint": "next lint"
+    "lint": "eslint ."
   },
   ...
   "devDependencies": {
     ...
     "eslint": "^9.9.0",
     ...
   },
+  "overrides": {
+    "eslint": "^9.9.0"
+  }
  1. Configure next.config.mjs to skip linting phase in next build
/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;
  1. npm install @eslint/js @eslint/eslintrc @eslint/compat eslint-plugin-react-hooks@latest -D
  2. Generate your eslint.config.mjs file with npx @eslint/migrate-config .eslintrc.json and call fixupConfigRules
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupConfigRules } from "@eslint/compat"

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
    baseDirectory: __dirname,
    recommendedConfig: js.configs.recommended,
    allConfig: js.configs.all
});

export default fixupConfigRules([...compat.extends("next/core-web-vitals")]);

Now both npm run lint and npm run build should work using the latest eslint version.

  • This is a starting point for your migration, I recommend adding ignore files, typescript and prettier support as detailed here
  • You might have specific dependency on type compilation, if so you can run next build --experimental-build-mode compile before linting.

This way, you can avoid some headaches. for followers.

  "overrides": {
-  "eslint": "^9.9.0",
+   "eslint": "$eslint" <-- this means using dependency's value
  }

Is there any update on a simple eslint.config.js configuration that works with NextJS and the ESLint v9? Using this doesn’t work anymore with the new version of ESLint "extends": "next/core-web-vitals"

I recently updated my guide here to use fixupConfigRules instead of fixupPluginRules + a map + a list of deps to patch. This results in a more simple migration & catch-all strategy.


TLDR; Updated minimum necessary changes to run eslint 9 with next.js build flow

  1. npm install -D eslint@latest
  2. Override eslint version and add the necessary changes to scripts in package.json
 ...
   "scripts": {
     "dev": "next dev",
+    "prebuild": "npm run lint",
     "build": "next build",
     "start": "next start",
-    "lint": "next lint"
+    "lint": "eslint ."
   },
   ...
   "devDependencies": {
     ...
     "eslint": "^9.9.0",
     ...
   },
+  "overrides": {
+    "eslint": "^9.9.0"
+  }
  1. Configure next.config.mjs to skip linting phase in next build
/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;
  1. npm install @eslint/js @eslint/eslintrc @eslint/compat eslint-plugin-react-hooks@latest -D
  2. Generate your eslint.config.mjs file with npx @eslint/migrate-config .eslintrc.json and call fixupConfigRules
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupConfigRules } from "@eslint/compat"

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
    baseDirectory: __dirname,
    recommendedConfig: js.configs.recommended,
    allConfig: js.configs.all
});

export default fixupConfigRules([...compat.extends("next/core-web-vitals")]);

Now both npm run lint and npm run build should work using the latest eslint version.


  • This is a starting point for your migration, I recommend adding ignore files, typescript and prettier support as detailed here
  • You might have specific dependency on type compilation, if so you can run next build --experimental-build-mode compile before linting.

If this gains attention from maintainers, this might be the perfect opportunity to rework some of the linting / doctoring behaviour of next lint, for example to support biome & eslint 9

Related: https://github.com/vercel/next.js/discussions/59347 https://github.com/vercel/next.js/discussions/59165

I’d be happy to contribute or add more context / ideas!

It would be nice to get the eslint v9 support back ported to v14. As it stands now, you can’t upgrade to eslint@9 due to this issue, but having tried converting to flat configs in just v8, that gets really ugly really fast. Being able to use eslint@9 in next v14 would create a much smoother upgrade path to v15.

For anyone hitting here, I also wanted to have tslint support, so the flat-packed eslint.config.mjs I’m using that combines a few of these suggestions:

Packages

pnpm add --save-dev eslint @eslint/js @types/eslint__js typescript typescript-eslint

eslint.config.mjs

import path from "node:path";
import { fileURLToPath } from "node:url";
import eslint from "@eslint/js";
import tseslint from 'typescript-eslint';

import { FlatCompat } from "@eslint/eslintrc";
import { fixupConfigRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const recommendedConfig = {
    ...eslint.configs.recommended,
    ...tseslint.configs.recommended,
}
  
const allConfig = {
    ...eslint.configs.all,
    ...tseslint.configs.all,
}

const compat = new FlatCompat({
    baseDirectory: __dirname,
    recommendedConfig: recommendedConfig,
    allConfig: allConfig
});

const fullConfig = tseslint.config(
    eslint.configs.recommended,
    ...tseslint.configs.recommended,
    ...compat.extends("next/core-web-vitals"),
    {
      rules: {
        "@next/next/no-img-element": "off",
      },
    },
    {
        ignores: [".next/**/*"],
    }
  );

export default fixupConfigRules(fullConfig);

If they do end up mucking about with eslint 9 support, perhaps they could simultaneously separate doctoring logic from next lint so we can use alternative linters, such as Biome …

Same error

Screenshot 2024-04-22 204334

.eslintrc.json : { "extends": "next/core-web-vitals" }

I updated all the packages to the latest version but this still does not solve the problem

I don’t want to go back to the old version to fix it. If anyone knows how to solve the problem without going to the old version, please help me 🙏

Isn’t Next 15 based on React 19? If so, how could it be released as stable without a stable release of React 19 first?

The release mentioned above is our second RC (Release Candidate) – not the final stable release. We’re close to a stable release for v15 now (so if you try it out, please let us know).

Upgrading to Next.js v15 does not require React 19, but it does support it if desired. If you are using the Pages Router, you can continue to use React 18. If you are using the App Router, the React version is vendored using the canary channel for frameworks (which is v19+).

deprecated eslint@8.57.1: This version is no longer supported.

eslint 8 is officially deprecated already :S

@TomasHubelbauer, downgrading to v8 isn’t the only workaround. See https://github.com/vercel/next.js/issues/64409#issuecomment-2343832704

Do agree with the sentiment that this needs some more attention.

I stumbled upon this “solution” for the few projects we have that are forced to stick with Next, since they’re too old to migrate.

What are you migrating to?

@tobi1220 Nice try, but app router is less suited for static export than pages router.

I have an ESlint configuration that works without problem on Next. The only thing is that it does not embark Next’s configuration as it is currently broken. I’m not even sure what is in their configuration and mine enumerates all rules anyways so it’s not really a concern. Upgrade to ESlint 9.x is critical in my opinion as the community is moving to it rather quickly and configurations will most likely rely on ESlint 9. This version resolves so many problems with managing configurations that I don’t think people will bother maintaining legacy versions for a long time.

You will have the same “lock-in” in any hybrid render framework. How do you think server rendering works if not by running a nodejs server to turn the templates into html?

While the specifics aren’t useful to this ticket specifically (I’d be more than happy to move this to gitter.im or whichever platform to discuss in detail) our use-case is not that of server rendering, we never needed that feature to begin with.

We just needed a compile-time rendered React framework, of which there are many options. We deploy PWAs (Progressive Web Apps) and app store applications written in React, which use export type build, which continues to be road-blocked by these server features being opt-out instead of opt-in.

We avoided the nextjs-server features for this reason. So, when we run next export (or set the build type to output: export etc, whatever the syntax happens to be in this version, it changes from version to version); we get static HTML and JS files, which can easily be deployed to run on a CDN itself, inside an APK on a device, inside an EXE on Windows (think: Electron, WailsJS specifically in our case), etc etc etc.

For those following this later: https://nextjs.org/docs/pages/building-your-application/deploying/static-exports

Remember, according to the Docs, this is a supported use-case. Just, half the features do not work when doing so (and this is adaquately documented, I don’t have any complaints there specifically.)

I Use this until next adds support for eslint^9: eslint.config.mjs

import { fixupConfigRules } from '@eslint/compat'
import globals from 'globals'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import js from '@eslint/js'
import { FlatCompat } from '@eslint/eslintrc'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const compat = new FlatCompat({
    baseDirectory: __dirname,
    recommendedConfig: js.configs.recommended,
    allConfig: js.configs.all
})

/** @type { import("eslint").Linter.Config[] } */
export default [
    ...fixupConfigRules(
        compat.extends(
            'eslint:recommended',
            'plugin:react/recommended',
            'plugin:react/jsx-runtime',
            'plugin:react-hooks/recommended',
            'plugin:@typescript-eslint/recommended',
            'prettier'
        )
    ),
    {
        languageOptions: {
            globals: {
                ...globals.browser,
                ...globals.node
            }
        },

        settings: {
            react: {
                version: 'detect'
            },

            'import/resolver': {
                node: {
                    paths: ['.'],
                    extensions: ['.js', '.jsx', '.ts', '.tsx']
                }
            }
        },

        rules: {
            'react/jsx-max-props-per-line': [
                'warn',
                {
                    maximum: 8
                }
            ],

            '@typescript-eslint/ban-ts-comment': 'off',

            '@typescript-eslint/no-empty-function': [
                'error',
                {
                    allow: ['arrowFunctions']
                }
            ],
            '@typescript-eslint/no-implicit-any': 'warn',
            '@typescript-eslint/no-explicit-any': 'warn',
        }
    },
    {
        files: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx']
    }
]

You have to change your npm scripts to use eslint directly package.json

"lint": "eslint ./src",
"lint-fix": "eslint ./src --fix"

...

"devDependencies": {
        "@eslint/compat": "^1.1.1",
        "eslint": "^9.9.0",
        "eslint-config-next": "^14.2.5",
        "eslint-config-prettier": "^9.1.0",
        "eslint-plugin-react": "^7.35.0",
        "eslint-plugin-react-hooks": "^4.6.2",
        "globals": "^15.9.0",
        "typescript-eslint": "^8.0.1"
}

As somebody who went ahead and switched to biome, it’s very nice. You lose all the next-specific custom eslint rules which are of varying importance, but it’s been worth it for me.

https://github.com/vercel/next.js/discussions/59347 seems like the way forward.

@AlbinoGeek There is no reason to wait, you can use eslint v9 in nextjs project today. The only problem is that the complexity that eslint-config-next was hiding away will now be clearly visible. Here is the relevant part of our configuration:

import jsxA11yPlugin from "eslint-plugin-jsx-a11y";
import nextPlugin from "@next/eslint-plugin-next";
import reactHooksPlugin from "eslint-plugin-react-hooks";
import reactRecommended from "eslint-plugin-react/configs/recommended.js";

const patchedNextPlugin = fixupPluginRules(nextPlugin);
const patchedReactHooksPlugin = fixupPluginRules(reactHooksPlugin);

const eslintConfig = [
    {
        name: "Country: react our rules",
        rules: {
	    "react/jsx-boolean-value": "error",
	    "react/jsx-max-props-per-line": "error",
	    "react/jsx-filename-extension": "error",
	    "react/jsx-sort-props": [
	        "error",
	        {
		    callbacksLast: true,
		    shorthandFirst: true,
		    reservedFirst: true,
		    multiline: "last",
	        },
	    ],
        },
    },
    {
	name: "Country: react hooks plugin",
	plugins: { "react-hooks": patchedReactHooksPlugin },
	rules: {
	    ...patchedReactHooksPlugin.configs.recommended.rules,
	    "react-hooks/exhaustive-deps": ["error"],
	},
    },
    {
	name: "Country: next plugin",
	plugins: { "@next/next": patchedNextPlugin },
	rules: {
	    ...patchedNextPlugin.configs["recommended"].rules,
	    ...patchedNextPlugin.configs["core-web-vitals"].rules,
	},
    },
    {
	name: "Country: jsx-a11y plugin",
	plugins: { "jsx-a11y": jsxA11yPlugin },
	...jsxA11yPlugin.flatConfigs.recommended,
    },
    {
	// We can't load eslint-config-next because it uses
	// @rushstack/eslint-patch which is not compatible with eslint
	// v9:
	name: "Country: eslint-config-next reimplemented",
	rules: {
	    "import/no-anonymous-default-export": "error",
	    "react/no-unknown-property": "off",
	    "react/react-in-jsx-scope": "off",
	    "react/prop-types": "off",
	    "jsx-a11y/alt-text": [
		"error",
		{ elements: ["img"], img: ["Image"] },
	    ],
	    "jsx-a11y/aria-props": "error",
	    "jsx-a11y/aria-proptypes": "error",
	    "jsx-a11y/aria-unsupported-elements": "error",
	    "jsx-a11y/role-has-required-aria-props": "error",
	    "jsx-a11y/role-supports-aria-props": "error",
	    "react/jsx-no-target-blank": "off",
	},
    }
]

Many of us switched over to Biome during that eslint-upgrade-mess. Is enabling third-party linters (or just Biome) via next lint also on the roadmap? See https://github.com/vercel/next.js/discussions/59347 (and I mean w/o just blindly ignoring lint errors during build what currently seems to be the only option).

It is, but no ETA just yet.

@simplenotezy

Make sure your replace the rule "lint": "next lint" in your package.json by your own linting strategy, probably "lint": "eslint ."

Thanks. Found your blog article and found a similar instruction.

@simplenotezy

Make sure your replace the rule "lint": "next lint" in your package.json by your own linting strategy, probably "lint": "eslint ."

Yes, that’s very true. Because there is no plugin or custom rule support of any kind, biome has no real ecosystem to speak of. The only rules that exist are those that are built into biome.

I would argue, however, that most people switch have to be okay with less available rules as tradeoff for simplicity and speed. I think that complexity vs simplicity is much more a locus of discourse here than slow vs fast (though that’s obviously nice as well).

The question is, of course, as always, what is the right tool for the job? And that can only be answered on a case-by-case basis. In my case, I am working on a project with no real frontend team to speak of so I don’t have a bunch of complex requirements or custom rules or anything. But I’m sure I will in the future when the team grows further. On the previous project I worked on, which had more frontend team members, I definitely needed all of eslint’s functionality. We had plenty of custom rules to help team members write code with consistent style and avoid common pitfalls, which was invaluable. But now, being essentially a one-man frontend team, the main things I need from linting/formatting are speed and simplicity.

I care more about the formatting anyway, as I’m basically familiar with all the relevant linting rules myself already and for some reason getting prettier to work consistently and not thrash in my IDE was a constant struggle.

So for me, at this exact moment in time, with this project, with this team, biome is a great fit.

If I were not in this exact situation or one very much like it, I would just pin eslint to 8 for now and wait for either 1. the eslint 9 mess to be sorted out, or 2. biome to become more mature.

YMMV

Did you guys try OXLint?

Yes, that’s very true. Because there is no plugin or custom rule support of any kind, biome has no real ecosystem to speak of. The only rules that exist are those that are built into biome.

I would argue, however, that most people switch have to be okay with less available rules as tradeoff for simplicity and speed. I think that complexity vs simplicity is much more a locus of discourse here than slow vs fast (though that’s obviously nice as well).

The question is, of course, as always, what is the right tool for the job? And that can only be answered on a case-by-case basis. In my case, I am working on a project with no real frontend team to speak of so I don’t have a bunch of complex requirements or custom rules or anything. But I’m sure I will in the future when the team grows further. On the previous project I worked on, which had more frontend team members, I definitely needed all of eslint’s functionality. We had plenty of custom rules to help team members write code with consistent style and avoid common pitfalls, which was invaluable. But now, being essentially a one-man frontend team, the main things I need from linting/formatting are speed and simplicity.

I care more about the formatting anyway, as I’m basically familiar with all the relevant linting rules myself already and for some reason getting prettier to work consistently and not thrash in my IDE was a constant struggle.

So for me, at this exact moment in time, with this project, with this team, biome is a great fit.

If I were not in this exact situation or one very much like it, I would just pin eslint to 8 for now and wait for either 1. the eslint 9 mess to be sorted out, or 2. biome to become more mature.

YMMV

The set of lint rules available in Biome is a tiny fraction of what’s available in the eslint ecosystem, so most people switching have to be ok with dramatically reducing the coverage/effectiveness of their linting (as a tradeoff for lint speed).

Thanks @controversial for taking the time to provide a detailed example it makes a lot more sense now. I think the issue we are facing here is that with this next lint opt-out we are re-ordering the build flow. Next default build flow is :

  1. Compile (Next Trigger)
  2. Lint Check (Next Trigger)
  3. Type Check (Next Trigger)
  4. Generate Pages (Next Trigger)

What I was suggesting was to disable automatic next lint trigger and do it before build flow :

  1. Lint Check (Manual Trigger)
  2. Compile (Next Trigger) ~Lint Check (Next Trigger)~
  3. Type Check (Next Trigger)
  4. Generate Pages (Next Trigger)

But you just demonstrated that this is breaking your code where linting relies on compiled types. And I agree with you, I believe I overlooked the changes it introduces : i.e. not having the same type environment during type-aware linting vs type checking.

From there I tinkered with various possibilities to try to keep the same order, but I believe the safest would be :

  • Create a npm check script only for checking the code (compile types -> lint -> typecheck)
  • Configure next build to only compile & generate pages
  • Run check then next build in your npm build script

Please use the following code as pseudo-code, this may vary depending on your deployment flow

package.json

"compile": "next build --experimental-build-mode compile",
"typecheck": "tsc",
"lint": "eslint ."
"check": "npm run compile && npm run lint && npm run typecheck",
"build": "npm run check && next build"

while disabling automatic checks next.config.mjs

const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
  typescript: {
    ignoreBuildErrors: true, // This actually do not run the typecheck step at all according to docs : https://nextjs.org/docs/app/api-reference/next-config-js/typescript
  },
  experimental: {
    typedRoutes: true,
  },
};

This actually runs next build twice but once only for compiling files, and there is no way around it, if we want typechecking on compiled types, we need to compile code first.


⚠️ Experimental Flags Solution

If CI/CD performance is more important than production code safety, you might be able to save some build time using the following flow :

  1. next build --experimental-build-mode compile
  2. eslint .
  3. tsc
  4. next build --experimental-build-mode generate

Notice that this is the exact same build flow built-in next but triggered manually. Only the lack of documentation and the experimental flag name advices us to avoid using this for production build.

Do you have a reproducible error that triggers a linting error (depending on these generated types)

My app has a series of pages under a specific prefix (say /steps/...) for which I want to define an order in my code. Imagine these pages are /steps/first, /steps/second, and /steps/third.

I derive a type to validate the names of those steps like this:

import type { Route as NextRoute } from 'next';
type CutStepId<T extends string> = T extends `/steps/${infer Suffix}` ? Suffix : never;
type StepId = CutStepId<NextRoute>;

i.e. under the above example, value 'second' would be assignable to StepId but 'foo' would not. This is useful because I can assign a sequence like const mySeq = ['first', 'second', 'third'] satisfies StepId[];, and later have <Link href={`/steps/${mySeq[i]}`} /> pass type checking under typedRoutes.

Before next build has run, NextRoute is string instead of a union of route strings. This trivially causes linting errors under tseslint.configs.recommendedTypeChecked rules like @typescript-eslint/no-unsafe-assignment, because StepId will evaluate to never instead of 'first' | 'second' | 'third': Screenshot 2024-08-08 at 11 41 42 AM

but not a typing error ?

during next build, the missing types are generated before type checking. So next build type checking succeeds, even though eslint would fail to run before next build.


If (like I do) you need type-aware linting to have the same set of next-generated types that it would if it were run by Next during a build, I think the only fix is to run eslint after next build.

The unfortunate consequence of that approach would be that lint-failing builds take much longer to fail than they did when linting could run between “compiled successfully” and the later stages of next build (“collecting page data,” “generating static pages,” “collecting build traces,” “finalizing page optimization”).

I recognize this use of next-generated types in my app is something of an edge case, but I do think that having the same type environment during type-aware linting vs type checking is important/valuable/desirable in the general case.

It’s nice and all but the blocker in this case is upstream dependencies as per this comment (which got hidden). Do not do these hacks unless you really have to, otherwise you are going to debug problems of ad-hoc patching after nextjs updates its support for it.

@SalahAdDin @AlbinoGeek @DamienCassou there might be an easier migration path, I wrote a setup guide for Eslint 9 with Next.js, starting from a minimal app, this should probably scale to work with any project but please let me know if there is any issue, this is kind of a long read : Eslint 9 & Next.js — Setup Guide

TLDR;

* You should install and override eslint 9 to avoid any issues on `npm install`

* You should declare your own `build` and `lint` rules

* You should opt-out of Next.js linting during build

* You should migrate your `.eslintrc.(js|json|yml)` using ESlint's  `@eslint/migrate-config`

* You should patch problematic plugins using ESLint's `fixupPluginRules`

The resulting files should look something like this

package.json

{
...
  "scripts": {
    "dev": "next dev",
    "build": "npm run lint && next build",
    "start": "next start",
    "lint": "eslint ."
   },
  ...
  "devDependencies": {
    ...
    "eslint": "^9.8.0",
    ...
  },
  "overrides": {
    "eslint": "^9.8.0"
  }
}

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;

eslint.config.mjs

// @ts-check
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupPluginRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

const pluginsToPatch = [
  "@next/next",
  // Other plugins to patch, example :
  // "react-hooks",
];

const compatConfig = [...compat.extends("next/core-web-vitals")];

const patchedConfig = compatConfig.map((entry) => {
  const plugins = entry.plugins;
  for (const key in plugins) {
    if (plugins.hasOwnProperty(key) && pluginsToPatch.includes(key)) {
      plugins[key] = fixupPluginRules(plugins[key]);
    }
  }
  return entry;
});

const config = [...patchedConfig, { ignores: [".next/*"] }];

export default config;

Why do we need so many complicated configurations? why do we need to install more extra pages? It does not seem simple and you used the migration script, you didn’t create a simple configuration.

Please do not write comments unrelated to the issue.

This involves sending spam messages to people who have subscribed to the issue.

Isn’t Next 15 based on React 19?

Support for react 19, not dependent on.

Isn’t Next 15 based on React 19? If so, how could it be released as stable without a stable release of React 19 first?

@feedthejim

we’re on it, gonna land very very soon

I don’t know about others, but to me, in this context, a simple “soon” is a matter of weeks, a “very soon” is a few days, and “very very soon” is about a couple hours… 😶

So wait until Next 15 is out? 🤦🏻‍♂️ By then eslint 10 might probably drop and the cycle starts all over

I wouldn’t be so pessimistic!

Many of us switched over to Biome during that eslint-upgrade-mess. Is enabling third-party linters (or just Biome) via next lint also on the roadmap? See https://github.com/vercel/next.js/discussions/59347 (and I mean w/o just blindly ignoring lint errors during build what currently seems to be the only option).

My guess is that Vercel is working hard to release Next 15, as the Next.js conference is just around the corner. Perhaps they’ll then advice to update to Next 15, which I assume will support eslint 9.

@SalahAdDin @AlbinoGeek @DamienCassou there might be an easier migration path, I wrote a setup guide for Eslint 9 with Next.js, starting from a minimal app, this should probably scale to work with any project but please let me know if there is any issue, this is kind of a long read : Eslint 9 & Next.js — Setup Guide

TLDR;

  • You should install and override eslint 9 to avoid any issues on npm install
  • You should declare your own build and lint rules
  • You should opt-out of Next.js linting during build
  • You should migrate your .eslintrc.(js|json|yml) using ESlint’s @eslint/migrate-config
  • You should patch problematic plugins using ESLint’s fixupPluginRules

The resulting files should look something like this

package.json

{
...
  "scripts": {
    "dev": "next dev",
    "build": "npm run lint && next build",
    "start": "next start",
    "lint": "eslint ."
   },
  ...
  "devDependencies": {
    ...
    "eslint": "^9.8.0",
    ...
  },
  "overrides": {
    "eslint": "^9.8.0"
  }
}

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;

eslint.config.mjs

// @ts-check
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupPluginRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

const pluginsToPatch = [
  "@next/next",
  // Other plugins to patch, example :
  // "react-hooks",
];

const compatConfig = [...compat.extends("next/core-web-vitals")];

const patchedConfig = compatConfig.map((entry) => {
  const plugins = entry.plugins;
  for (const key in plugins) {
    if (plugins.hasOwnProperty(key) && pluginsToPatch.includes(key)) {
      plugins[key] = fixupPluginRules(plugins[key]);
    }
  }
  return entry;
});

const config = [...patchedConfig, { ignores: [".next/*"] }];

export default config;

@SalahAdDin @AlbinoGeek @DamienCassou there might be an easier migration path, I wrote a setup guide for Eslint 9 with Next.js, starting from a minimal app, this should probably scale to work with any project but please let me know if there is any issue, this is kind of a long read : Eslint 9 & Next.js — Setup Guide

TLDR;

  • You should install and override eslint 9 to avoid any issues on npm install
  • You should declare your own build and lint rules
  • You should opt-out of Next.js linting during build
  • You should migrate your .eslintrc.(js|json|yml) using ESlint’s @eslint/migrate-config
  • You should patch problematic plugins using ESLint’s fixupPluginRules

The resulting files should look something like this

package.json

{
...
  "scripts": {
    "dev": "next dev",
    "build": "npm run lint && next build",
    "start": "next start",
    "lint": "eslint ."
   },
  ...
  "devDependencies": {
    ...
    "eslint": "^9.8.0",
    ...
  },
  "overrides": {
    "eslint": "^9.8.0"
  }
}

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;

eslint.config.mjs

// @ts-check
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupPluginRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

const pluginsToPatch = [
  "@next/next",
  // Other plugins to patch, example :
  // "react-hooks",
];

const compatConfig = [...compat.extends("next/core-web-vitals")];

const patchedConfig = compatConfig.map((entry) => {
  const plugins = entry.plugins;
  for (const key in plugins) {
    if (plugins.hasOwnProperty(key) && pluginsToPatch.includes(key)) {
      plugins[key] = fixupPluginRules(plugins[key]);
    }
  }
  return entry;
});

const config = [...patchedConfig, { ignores: [".next/*"] }];

export default config;

I tried following your suggestions, however, when running “npm run lint”, it seems as though the file is not read, because it asks me to setup eslint:

? How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint
❯  Strict (recommended)
   Base
   Cancel

Did I miss a step?

@ldeveber that’s not correct; eslint-plugin-import has not released support for eslint v9

see https://github.com/import-js/eslint-plugin-import/pull/2996

The PR you linked adds support for using flat config under eslint v8, which is not what this issue is about.

Quoting the first message in the PR you linked:

And just to be clear, this is only aiming to provide support for flat config (which is a separate issue than supporting eslint v9)

@AlbinoGeek I don’t get it, if you don’t need any SSR, why even use an isomorphic framework in the first place? While static export is an officially supported feature, it’s also known and pointed out in the docs that a lot of basic features will not work. (Also note that you linked the docs of the pages router, since this is deprecated make sure to switch to the app router.)

We will not be switching to the App Router for existing sites any time soon, as that requires a complete recode. Likewise, as you say, we don’t have a reason to use NextJS for future projects, as our use-case is no longer a first-party feature, to be blunt.

You will have the same “lock-in” in any hybrid render framework. How do you think server rendering works if not by running a nodejs server to turn the templates into html?

Thanks @controversial for the feedback! While I understand the point you are making, I was unable to produce a linting error specific to typescript-eslint relying on route types generated at build.

After going through Statically Typed Links my understanding is that this typedRoutes experimental feature is specific to type checking, and the type checking flow is unchanged :

  • Either next dev generates the types definitions -> your code editor runs type checker
  • Or next build generates the types definitions -> (skips linting) -> runs type checker For example here, I can trigger a typing error while skipping linting phase Screenshot 2024-08-08 at 09 57 26

Do you have a reproducible error that triggers a linting error (depending on these generated types) but not a typing error ?

One problem with setting eslint.ignoreDuringBuilds and running eslint yourself is that Next won’t generate route types before lint runs.

During next build, for the app directory, linting runs after the webpack build has run, which guarantees that the type definitions generated by next-types-plugin are present for the type-checking/linting step

If (like I do) you have type-sensitive lint rules (i.e. typescript-eslint) and you use next-generated types like Route, your lint script might fail to run before next build (in the absence of those types) in a way that it wouldn’t if it were run during next build

@SalahAdDin

Why do we need so many complicated configurations?

This is a single configuration file that replaces your previous configuration file. That is mostly auto-generated by running npx @eslint/migrate-config .eslintrc.json my addition here is a map and a for loop to patch specific plugins. We need this because of 30+ breaking changes introduced by ESLint 9 in order to enable features and developer experience enhancements in the future.

why do we need to install more extra pages?

Not sure what you call pages, if you mean packages it’s because ESLint after introducing many breaking changes also spent time, energy and ressources to develop utilities to help developers like us migrate to the newer ESLint 9 without having to wait for upstream fixes. All of these packages are devDependencies and will not have impact on your production bundle / performance.

It does not seem simple and you used the migration script, you didn’t create a simple configuration.

I invite you to re-read my message, I was saying “easier migration path” not “I created a simple configuration”. That being said, I believe this is the minimal necessary changes to fix a complex problem.

Please be mindful of people in the community trying to help on this issue and also open source developers like the one working on ESLint and Next.js providing utilities, options and opt-outs to help on complex matters.

Let’s move to a better and faster linter.

As somebody who went ahead and switched to biome, it’s very nice. You lose all the next-specific custom eslint rules which are of varying importance, but it’s been worth it for me.

#59347 seems like the way forward.

You did well man, do you have any configuration file or migration tutorial?

@SalahAdDin @AlbinoGeek @DamienCassou there might be an easier migration path, I wrote a setup guide for Eslint 9 with Next.js, starting from a minimal app, this should probably scale to work with any project but please let me know if there is any issue, this is kind of a long read : Eslint 9 & Next.js — Setup Guide

TLDR;

  • You should install and override eslint 9 to avoid any issues on npm install
  • You should declare your own build and lint rules
  • You should opt-out of Next.js linting during build
  • You should migrate your .eslintrc.(js|json|yml) using ESlint’s @eslint/migrate-config
  • You should patch problematic plugins using ESLint’s fixupPluginRules

The resulting files should look something like this

package.json

{
...
  "scripts": {
    "dev": "next dev",
    "build": "npm run lint && next build",
    "start": "next start",
    "lint": "eslint ."
   },
  ...
  "devDependencies": {
    ...
    "eslint": "^9.8.0",
    ...
  },
  "overrides": {
    "eslint": "^9.8.0"
  }
}

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
};

export default nextConfig;

eslint.config.mjs

// @ts-check
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import { fixupPluginRules } from "@eslint/compat";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

const pluginsToPatch = [
  "@next/next",
  // Other plugins to patch, example :
  // "react-hooks",
];

const compatConfig = [...compat.extends("next/core-web-vitals")];

const patchedConfig = compatConfig.map((entry) => {
  const plugins = entry.plugins;
  for (const key in plugins) {
    if (plugins.hasOwnProperty(key) && pluginsToPatch.includes(key)) {
      plugins[key] = fixupPluginRules(plugins[key]);
    }
  }
  return entry;
});

const config = [...patchedConfig, { ignores: [".next/*"] }];

export default config;

With this approach, do you just handle linting on the build process manually on the CI for example?

We’re about to hit 4 months, could we please get an idea on the official stance here?

Should we hold back all NextJS projects on ESLint ^8 <9 indefinitely?


If this is the case, we’ll have to tell Dependabot to skip eslint@9 across our Enterprise -_-

what about to move to OXLint?

The only package update of relevance is eslint-config-next, which is tied to the version of next, aka wait for one of the newest nextjs versions. Until then you have to stick to old one.