I'm trying to work with MongoDB and React.js but I have problems with MongoDB dependencies.
package.json/dependencies :
"dependencies": {
"dotenv": "^16.3.1",
"mongodb": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.10.1",
"react-scripts": "^5.0.1",
"sass": "^1.64.1",
"webpack": "^5.88.2"
},
and the two kind of errors I get (about 60 repetitions for the first one and 10 for the second one) :
ERROR in ./node_modules/whatwg-url/dist/encoding.js 6:4-19
Module not found: Error: Can't resolve 'util' in 'D:\Documents\Dev\_Projects\proto-bus\node_modules\whatwg-url\dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
- install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "util": false }
second one :
ERROR in ./node_modules/mongodb/lib/cmap/auth/mongocr.js 7:15-32
Module not found: Error: Can't resolve 'crypto' in 'D:\Documents\Dev\_Projects\proto-bus\node_modules\mongodb\lib\cmap\auth'
The first error concerning polyfill and webpack can be resolved by adding a fallback and installing the npm package, but the second cannot.
I found information on the internet about compatibility issues between Web3 and Webpack 5, but downgrading the packages didn't work ([email protected] and [email protected]). So I think there's an easier way of solving this problem than manually adding fallbacks.
Another possibility is that MongoDB can't work with react, and needs an express server.
Thanks in advance for your help.
So in order to close this issue, MongoDB client is not made to work with React. Indeed, React is a frontend framework and MongoDB a backend client, which needs some packages different from those provided by React.
To conclude, I've found two solutions : use Mongoose with React (same npm project) or express and MongoDB (in a different project). The REST API provided by MongoDB serverside client is depreciated, so that's not a good option for a project that will be in production. I'm going to code my own backend API with express and MongoDB because I prefer it to mongoose, it gives me more flexibility.