简体   繁体   中英

How to set env variables across the app with create-react-app on the client side

Hey I have my simple Todo app with the client where I have create-react-app installed and the server with node . I want to set env variables across my app but I am confused how to do it properly.

I have set my .env file in the root directory of the app.

我的应用程序目录

In the .env file there is only REACT_APP_HOST=http://localhost:3000 .

I wanted to display it in the client directory like so:

const { REACT_APP_HOST } = process.env;
console.log({ REACT_APP_HOST });

The code above shows me undefined . The whole process.env is an empty object.

I have tried to move the .env to the client directory and it works well then but thats not the point I think.

How to do it properly if I would like to use the .env variables also in the server side ? Do I need to create two separate .env files to serve the client and the server in my case or maybe create-react-app need some extra configuration to be served by one .env file ?

If it'll help here you have my github repo .

  • Create a .env file in the root of your application (same level as src ):

     REACT_APP_API = http://XX.XX.XXX.XXX:XXXX 

That's it, by naming your variables with REACT_APP prefix you don't even need to use dotenv.require() . Now REACT_APP_API is available at process.env.REACT_APP_API

  1. You have to create two .env file . One is in client and another is in server(if needed).
  2. You dont need to set any other configuration for client. By default client directory support .env if it is done with create-react-app. You may get more information at @ custom .env
  3. If you need to use .env for server . create .env at server folder. Add dotenv module. You have to follow instruction from this link. dotenv doc

Right, You must have to create a .env file in the root of our project. Perhaps it will be the same level as src .

Please note this link. https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM