Environment variables configuration problem with web3.js in React crypto project

I’m working on a digital token creation app using React and web3.js but running into some webpack errors. The problem started when I tried to load environment variables in my blockchain interaction file. Here’s the code that’s causing issues:

require('dotenv').config();
const providerUrl = process.env.REACT_APP_PROVIDER_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3Instance = createAlchemyWeb3(providerUrl);

The file is located at /token-app/src/helpers/blockchain.js and when I try to run it, I get multiple webpack errors about missing Node.js modules like ‘stream’, ‘fs’, ‘path’, ‘crypto’, ‘assert’, ‘http’, ‘https’, ‘url’, and ‘os’. The errors mention that webpack 5 no longer includes polyfills for these core Node.js modules by default. Each error suggests adding fallback configurations or installing browserify versions of these modules. Has anyone dealt with similar webpack polyfill issues when using web3 libraries in React apps?

Wait, are you using Create React App? That might be making this way more complicated. What version of web3.js are you running? And have you checked if your environment variables are loading correctly before messing with webpack?

I had a similar setup break once - turned out it wasn’t just the polyfills but how CRA handles dotenv. You probably don’t even need that require('dotenv').config() line if you’re using CRA since it auto-loads .env files.

Are you getting these errors in development or when building for production? The webpack errors can look different depending on when they hit. Did you recently upgrade dependencies or is this a fresh project?

Might be a simpler fix before you dive into configuring webpack fallbacks.

This issue often arises when using webpack 5 with web3.js. I encountered similar problems while developing a crypto project. A straightforward solution is to create a webpack.config.js file in the root directory of your project. Within that file, configure the resolve.fallback settings for the missing Node.js modules, like so: crypto: require.resolve('crypto-browserify') and stream: require.resolve('stream-browserify'). After setting up these fallbacks, make sure to also install the corresponding browserify polyfills via npm. If possible, consider using ethers.js instead, as it generally integrates more smoothly with web applications and doesn’t require these polyfills. However, if you need to stick with web3.js, tools like react-app-rewired can assist in modifying the webpack configuration without having to eject from Create React App.

had this exact headache last month! dont mess with webpack configs - just switch to the newer web3 version or use import instead of require. that fixed it for me. also, you probably dont need dotenv in React since CRA handles env vars automatically.