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.

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some NextJS Help?

Search fiverr to find help quickly from experienced NextJS developers.



Supported by