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 useprocess.env.API_KEY
. From React docs, it is said that for a React app you need to:- Name the variable
REACT_APP_API_KEY
- 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:- I'd have two
.env
files which seems a bit confusing. - 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.
- I'd have to protect that new
.env
file from my version control software, which increases vulnerability.
- Name the variable
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?