Home > Software design >  Adding Variables to .env file and getting undefiened in my front-end
Adding Variables to .env file and getting undefiened in my front-end

Time:03-01

I'm trying to add a variable to my .env file, so here is the steps I followed 1- I created a .env file in the root directory of the project, under the src directory 2- I added this variable

REACT_APP_BASE_URL='lablabla'

3- I tried to access it from my app.tsx in the same directory (I'm using TS for the whole app)

 console.log("lol: ", process.env.REACT_APP_BASE_URL)

And I get undefined at my console

Things I have tried:

I tried to install dotenv and use

require('dotenv').config()

and I ran into a lot of issues, so I decided to remove it as I learned it came out of the box already with react app

CodePudding user response:

under the src directory 2- I added this variable

What do you mean by that?

Create .env file under root directory. Add this content

REACT_APP_BASE_URL='My-content'

In App.jsx get it this way

console.log(process.env.REACT_APP_BASE_URL);

It's important to start your env variables with prefix REACT_APP_ and once you modify it reload the dev server.

  • Related