"Can't resolve 'encoding'" warning in NextJS caused by try/require from `node_modules`

431 views Asked by At

In a NextJS 13.4.19 app in typescript, using @apollo/[email protected] causes a warning at the build step, coming from ApolloServer/node-fetch. This seems caused by a try / require in node-fetch:

  • ./node_modules/node-fetch/lib/index.js:
let convert;
try {
  convert = require('encoding').convert;
} catch (e) {}
  • Warning:
- warn Compiled with warnings

./node_modules/node-fetch/lib/index.js
Module not found: Can't resolve 'encoding' in 'C:<...>\apollo-server-encoding-warn\node_modules\node-fetch\lib'

Import trace for requested module:
./node_modules/node-fetch/lib/index.js
./node_modules/@apollo/server/dist/esm/plugin/schemaReporting/schemaReporter.js
./node_modules/@apollo/server/dist/esm/plugin/schemaReporting/index.js
./node_modules/@apollo/server/dist/esm/ApolloServer.js
./node_modules/@apollo/server/dist/esm/index.js
./app/api/graphql/route.ts
  • tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

Manually installing the encoding package acts as a workaround to remove this warning, but it's not a very satisfying solution as I wouldn't want to install every future package which presence is checked using this pattern.

This warning happens both when building and running in dev mode, is there a way I can tell NextJs/typescript to not report these warnings when they're coming from node_modules ? Or is it symptomatic of something else that I missed ?

2

There are 2 answers

0
AlexAngc On BEST ANSWER

I ended up finding that this warning was in fact coming from Webpack, and while browsing the options I found that I could target-suppress it by updating the next.config.js file as follow:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.ignoreWarnings = [
      // https://webpack.js.org/configuration/other-options/#ignorewarnings
      {
        module: /node-fetch/,
        message: /.*Can't resolve 'encoding'.*/,
      },
    ];

    return config;
  },
};

module.exports = nextConfig;
1
daudln On

I faced this warn while running Apollo server with NextJS 13

To fix this issue, you can try the following:

  1. Install the encoding module.
npm install encoding

or

yarn add encoding
  1. Restart your development server. This will ensure that the changes you made to your node_modules directory are picked up.