share env variable beween turborepo monorepo project

Viewed 2880

I ve setup a basic turborepo project and I want to share .env variables across the all the apps and some of packages. If I set one .env file in the root of project and how can all apps and packages access them. Or for my requirement do I need to set multiple .env files in all apps and packages?

3 Answers

To load the env variables from .env into the process env you can use https://www.npmjs.com/package/dotenv.

Then to share the env variables in your monorepo :

In each workspace/app add require('dotenv').config({path: /custom/path/to/.env}) (assuming common js module resolution here) as early as possible as per docs (meaning e.g. for a next js app in next.config.js), where /custom/path/to/.env would be the relative path to your root .env (e.g. two folders up:../../.env)

I've found this approach to work.

  1. Install env-cmd (yarn install env-cmd)
  2. Make a shell script called turbo-run.sh that does the following:
# remember to use direct paths to files because yarn has a habit
# of stripping out `--` flags (which are used in turborepo to pass
# in extra args to turbo commands)
./node_modules/.bin/env-cmd \
  --file $ENV_FILE \
    ./node_modules/.bin/turbo run \
      $@

(also chmod +x it so that you can execute it)

  1. Then setup your package.json scripts to have a turbo-run command that calls ./turbo-run.sh
  2. Now you can do yarn turbo-run foo and ensure that it always calls env-cmd with the appropriate ENV_FILE file.
Related