Is there a way to share a single .env file for several Create-React-App apps in a monorepo?

Viewed 1822

I have a Lerna monorepo with several CRA apps and Node.js services. The CRA apps have common environment variables, so I'd like to be able to create one .env file that they all share.

Unfortunately, my two attempts so far have failed.

  1. I thought perhaps I could add dotenv to each CRA app and use dotenv.config({ path: '...' }) at the entry-point of each app. I was surprised that the env vars were all undefined, even though they'd been prefixed with REACT_APP_

  2. I tried loading the shared .env by piggy-backing the react-scripts start command by changing it to react-scripts start -r dotenv/config dotenv_config_path=/custom/path/to/your/env/vars. Obviously this didn't work because dotenv isn't being executed by node, but react-scripts doesn't have usage docs that I can find, and looking through node_modules/react-scripts/scripts/start.js doesn't present an obvious way for passing arguments.

So, I guess my question is: can I share a single .env file among several CRA apps without ejecting and setting the .env path manually for each app? I'd like to avoid this if possible.

Thank you!

--UPDATE--

I found a solution a few minutes after posting (sorry!).

I was able to install dotenv-cli and change the scripts for each CRA app to:

"scripts": {
  "start": "dotenv -e ../../.env react-scripts start",
  "build": "dotenv -e ../../.env react-scripts build",
  "test": "dotenv -e ../../.env react-scripts test",
  "eject": "react-scripts eject"
}

This had the desired effect of sharing a single .env among many CRA apps, though I'm not sure if there is a cleaner/better way.

1 Answers

As an option, you can consider using aliases. Meaning to put your .env file into the repository's root and create aliases to each package like so ln -s [source] [destination] (this example would work for MacOS, not sure about other OSs).

Related