Accessing .env variables outside of React app directory

Viewed 1961

My project's structure is:

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

Where frontend is a React app and backend is an Express app. I have an environment variable API_KEY=... in .env that I need to use in both the backend in the frontend apps.

  • In the Express backend app, I can access it easily using process.env.API_KEY without issues, even though it's outside of the backend app folder.

  • However, I also need to access that key from the React frontend app, which returns undefined when I use process.env.API_KEY. From React docs, it is said that for a React app you need to:

    1. Name the variable REACT_APP_API_KEY
    2. Make sure that it is located inside of the React app directory.

    So yeah, I could create another .env file inside of the React app and follow these instructions, but I feel like it is adding unnecessary duplicated code:

    1. I'd have two .env files which seems a bit confusing.
    2. I'd have the same secret key in two different files, which is also confusing, and every time it changes I have to edit two files instead of one.
    3. I'd have to protect that new .env file from my version control software, which increases vulnerability.

Are there any workarounds that would enable me to just have the API key in the root directory of the project? Is it common practice to have same api key in multiple files?

1 Answers

IF WORKING ON MERN PROJECT>>>

{ROOT DIRECTORY PACKAGE.JSON}

"scripts": {
    "start": "node backend/server.js",
    "server": "nodemon backend/server.js",
    "client": "npm start --prefix frontend", // frontend is my react folder 
    "dev": "concurrently \"npm run server\" \"npm run client\" "  }

Add this kind of scripts in your package.json of root directory .

And then run "npm run client" from the root directory (i did run frontend command by client key...thats why i run npm run client)

OR THE OTHER SIMPLE THING YOU CAN DO IS IF YOU ONLY WANT YOUR REACT APP TO START....

run simple line from root directory....

npm start --prefix frontend

(As frontend is your react folder)
Related