Published: July 30 2021

Next.js + Webpack - Fix for ModuleNotFoundError: Module not found: Error: Can't resolve '...'

If you're building a Next.js app that uses a Node.js module that only exists on the server-side such as the file system (fs) module, you may see the following error on build because the module can't be found on the client-side (the browser):

ModuleNotFoundError: Module not found: Error: Can't resolve 'fs' in 'C:\Projects\next-js-11-jwt-authentication-example\helpers'


Fix for Webpack 5

To fix the error with Webpack 5, update your Next.js config file (/next.config.js) with the following, it tells webpack not to resolve the module on the client-side (!isServer).

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;
    }
}


Fix for Webpack 4

To fix the error with Webpack 4, update your Next.js config file (/next.config.js) with the following, it tells webpack to set the module to 'empty' on the client-side (!isServer).

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;
    }
}


For more info on adding custom webpack config to Next.js see https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config.

 


Need Some NextJS Help?

Search fiverr for freelance NextJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by