klugjo
klugjo

Reputation: 20885

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 ?

Upvotes: 4

Views: 6369

Answers (2)

MadaShindeInai
MadaShindeInai

Reputation: 590

  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).

Upvotes: 4

Tom
Tom

Reputation: 16246

Not sure how to run both root and app level, but if you want just the app level, do the following:

  1. in your root turbo.json put in all the keys:
"globalEnv": [
  "MY_KEY",
  "MY_OTHER_KEY"
],
//a. ".env" is the default, you don't need the following line unless you have a custom .env file name. e,.g. .env.local
//b. Note "globalDependencies" in the following line is referring to your .env file under the app folder, not the root one.
"globalDependencies": [".env.local"] 
  1. in your web project, put your .env or .env.local file there.
MY_KEY='SOMETHING'
MY_OTHER_KEY='SOMETHING ELSE'
  1. Clear all your cache in the cache folder (just in case), then run:

turbo run dev --filter=my-web-project

That's it, your web app will pick up the env file in your app folder, not from your root folder.

ref: https://turbo.build/repo/docs/reference/configuration#globalEnv

Upvotes: 1

Related Questions