0
.
├── backend
│   ├── node_modules
│   ├── package.json
│   ├── routes
│   └── server.js
├── frontend
│   ├── node_modules
│   ├── package.json
│   ├── public
│   └── src
├── config
│   ├── .env

Above is my project structure. I have 3 folders, frontend, backend and the config folder. I have my .env file inside my config folder. What i want is to read the variables from the env file inside the config folder using react js which is the frontend

Minsaf
  • 272
  • 1
  • 5
  • 14
  • For react js to recognize your environment variables you need to define them in the react app's root folder and start their names with `REACT_APP_`, check [documentation](https://create-react-app.dev/docs/adding-custom-environment-variables/) for reference. You might have to create another `.env` in the `frontend` directory. [check this answer](https://stackoverflow.com/q/64977509/20769551) for more info – Izebeafe Jun 13 '23 at 06:38
  • what have you tried so far ?? – Yeshwin Verma Jun 13 '23 at 06:38
  • is there any way to feed env variables from external sources to react app? – Minsaf Jun 13 '23 at 06:53

1 Answers1

1

You can follow those steps:

  1. Provide a variable in your .env file which start with REACT_APP_ (e.g: REACT_APP_MY_VAR)
  2. Then, in your code, you can get it using process.env (e.g: process.env.REACT_APP_MY_VAR)

Example:

Define the variables in .env file

REACT_APP_COUNT=0
REACT_APP_DOMAIN_NAME=stackoverflow

How to use?

console.log(process.env.REACT_APP_DOMAIN_NAME);

// output: stackoverflow

Don't forget to restart the application when you add a new environment variable.

Hritik Sharma
  • 1,756
  • 7
  • 24