Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

share env variable beween turborepo monorepo project

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?

like image 822
Adam Avatar asked Sep 11 '25 06:09

Adam


1 Answers

As of December'22, the recommended way of doing this as per the official turbo docs is as follows:

  1. cd root-directory-of-your-project.
  2. npm add -D dotenv-cli (or with pnpm: pnpm add -D dotenv-cli -w).
  3. Create a .env file in the root directory of your project.
    • Add your .env to your project's root .gitignore.
  4. Add your variables to the newly created .env file.
    • If you are using nextjs remember to prefix your public variables with NEXT_PUBLIC_* (example: NEXT_PUBLIC_GOOGLE_ANALYTICS_TOKEN=1234).
  5. On your turbo.json file, add the variables on which each pipeline job depends.
    • Example:
    {
      "$schema": "https://turborepo.org/schema.json",
      "pipeline": {
        "dev:frontend": {
          "outputs": ["dist/**", ".next/**"],
          "env": ["NEXT_PUBLIC_GOOGLE_ANALYTICS_TOKEN"]
        },
        "dev:backend": {
          "outputs": ["dist/**", ".next/**"],
          "env": ["DATABASE_URL"]
        }
      }
    }
    
  6. Restart your local development server. Try logging process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_TOKEN.

Once finished, the structure of the project should look similar to the following:

apps
    backend     <<< Your backend code. You don't need to keep any .env file here.
    frontend    <<< Your frontend code. You don't need to keep any .env file here.
package.json    <<< Where you should install dotenv-cli as a dev dependency.
turbo.json      <<< Where pipeline jobs and their dependencies on environment variables are specified.
.env            <<< Where all your environment variables will be stored.
like image 90
Erwol Avatar answered Sep 13 '25 20:09

Erwol