Search code examples
javascriptnode.jsenvironment-variablespackage.jsonturborepo

How to use both root and app level env files with turborepo


I have a monorepo with the following script:

"start": "env-cmd -f .env turbo run start --parallel",

If I run yarn start at the root, it runs all my apps using the .env file at the root.

A lot of my environment variables are only used in one specific app and my /.env file is getting cluttered as I keep on adding new apps. I want to keep that .env file for shared environment variables only and have children .env files at the root of each apps for specific configurations.

Example if I have an app called web located in /apps/web, I would like to add an /apps/web/.env file that is used only when building the web app.

How can I achieve that ?


Solution

    1. You can leave your global envs in monorepo root .env file. They will be available in all your workspaces by default.
    2. You should add dotenv-cli package as dev_deps for workspaces that require .env file with workspace-specific variables.
    3. Update your scripts in package.json:
    • Add "with-env": "dotenv -e ./.env --"
    • Update "dev": "pnpm with-env next dev",
    • Update "build": "pnpm with-env next build"
    1. Remove all workspace-specific envs from monorepo root .env file (and from turbo.json globalEnvs and add .env files (with workspace-specific envs) to your workspaces to the root (package.json level).