How to Solve the Module not found: Cannot resolve 'fs' error in Next.js

Webpack 4 version

To resolve the error with Webpack 4, you need to tell webpack to set the module to ‘empty’ on the client-side (!isServer).

This is also a solution when you are working with older Next.js versions.

The configuration essentially tells Webpack to create an empty module for fs, which effectively suppresses the error.

Update your next.config.js with the following:

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
webpack: (config, { isServer }) => {
if (!isServer) {
// set 'fs' to an empty module on the client to prevent this error on build --> Error: Can't resolve 'fs'
config.node = {
fs: "empty",
};
}

return config;
},
};

Webpack 5 version

To resolve the error with Webpack 5, you need to tell webpack not to resolve the module on the client-side (!isServer).

Update your next.config.js with the following:

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
webpack: (config, { isServer }) => {
if (!isServer) {
// don't resolve 'fs' module on the client to prevent this error on build --> Error: Can't resolve 'fs'
config.resolve.fallback = {
fs: false,
};
}

return config;
},
};

How to Solve the Module not found: Cannot resolve 'fs' error in Next.js
https://blog.justforlxz.com/2023/04/19/How-to-Solve-the-Module-not-found-Cannot-resolve-fs-error-in-Next-js/
作者
小竹
发布于
2023年4月19日
许可协议