Resolving the module not found
error in Next.js
While working with Next.js and performing sanitization on a variable, you may encounter the following error message:
1 | Module not found: Error: Can't resolve 'net' |
This error indicates that a core Node.js module is missing. It is important not to run npm install net
or any similar commands. If you have already attempted to install such modules, execute npm uninstall
to remove them.
The root cause of this issue is that Next.js is attempting to execute backend code in the frontend, resulting in the error.
In my case, I encountered this problem when using the DOMPurify library. Initially, I was using it within a component, but I discovered that it needed to be used in the getStaticProps()
method instead.
The getStaticProps()
method runs during the build process in the Node environment, which aligns with the expectations of the DOMPurify library.
By making this adjustment and utilizing the getStaticProps()
method for code execution, you can resolve the module not found
error and ensure the proper functioning of your Next.js application.
tags: [“Next.js”, “module not found error”, “DOMPurify”, “getStaticProps”]