Reputation: 21
I made a basic Node.js/React project, and my .env file doesn't work. My project is at https://github.com/TheGElCOgecko/weather-predictor/tree/main. The main details is that I am using dotenv-webpack, my .env file is in the root directory, the project is a React/Node.js project, whenever I try and print a value from the .env file, it prints "undefined" (I print it in App.js), and when I deployed it on GitHub Pages using "npm run deploy", it straight up deleted my .env file.
I tried using dotenv instead of dotenv-webpack, but that didn't work and it wouldn't compile if I included "require('dotenv').config();". My webpack.config.js used to include this:
resolve: {
fallback: {
"path": require.resolve("path-browserify"),
"os": require.resolve("os-browserify/browser"),
"crypto": require.resolve("crypto-browserify"),
}
},
I switched to dotenv-webpack because at least that was compiling (whereas using dotenv resulted in compilation failing), but maybe that was the wrong choice?
Upvotes: 0
Views: 51
Reputation: 222503
dotenv
can't be used as you tried, It's not webpack plugin and doesn't support client-side apps:
plugins: [
new Dotenv(),
]
This is what dotenv-webpack
does, and you try to solve a problem that shouldn't exist in the first place.
The project is created with create-react-app
, which is a preconfigured wrapper around Webpack, and uses its commands to run the app. CRA ignores webpack.config.json and doesn't need an additional configuration, unless proven otherwise. Internal Webpack configuration can be extended but this should be done in a special way, e.g. with Craco.
CRA already supports dotenv
and implements the solution similar to dotenv-webpack
that works out of the box. The problem is that environment variable doesn't take the requirement for REACT_APP_
prefix into account. Any unprefixed variables are ignored for security reasons.
REACT_APP_API_KEY_TEST
should be defined in .env
, then it will be available as process.env.REACT_APP_API_KEY_TEST
in React app.
Upvotes: 0