I want to access environment variables from my .env file, located in the root directory, and use them in my App.js React file using dotenv. However, I am not able to access them. on the client side (App.js).
The variables I want to use: root/.env
The file I want to use them in: root/client/src/App.js
PORT=5432
TEST=911
REACT_APP_WEATHER=12345678
import './App.css';
require("dotenv").config();
// Doesn't show the variables in the .env file
console.log(process.env);
function App() {
return (
<div className="App">
Hello
</div>
);
}
export default App;
I read that dotenv (which is installed in my root directory) doesn't work on client-side and only on server-side Using environment variables in React. Do I need to install that webpack? I tried installing it in my client but it created many errors.
Note: I want to store my server and client environment variables in the same .env file
With create-react-app you don't have to use dotenv library of anything like that. To read from .env file all you have to do is prefix all the variables name with REACT_APP_. For example:
REACT_APP_PORT=5432
REACT_APP_TEST=911
REACT_APP_WEATHER=12345678
create-react-app will automatically make it available to you during the build time. On your react app, from anywhere, you can console.log this:
console.log(process.env.REACT_APP_PORT); //5432
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With