Next.js Discord

Discord Forum

Turborepo .env files not loading

Unanswered
Yacare Caiman posted this in #help-forum
Open in Discord
Yacare CaimanOP
In my current current set up I can't seem to access my .env no matter where I place it (root, inside a package under /packages, inside app under /apps). It just returns "undefined".

package.json:
{
  "name": "turborepo",
  "private": true,
  "scripts": {
    "build": "turbo run build",
    "dev": "turbo run dev",
    "lint": "turbo run lint",
    "format": "prettier --write \"**/*.{ts,tsx,md}\"",
    "check-types": "turbo run check-types"
  },
  "dependencies": {
    "@biomejs/biome": "1.9.4",
    "@manypkg/cli": "^0.23.0",
    "turbo": "2.3.3",
    "typescript": "^5.7.3"
  },
  "engines": {
    "node": ">=18"
  },
  "packageManager": "pnpm@8.15.4",
  "resolutions": {
    "jackspeak": "2.1.1"
  }
}


turbo.json:
{
  "$schema": "https://turbo.build/schema.json",
  "ui": "stream",
  "globalDependencies": ["**/.env"],
  "tasks": {
    "build": {
      "env": [
        "TEST_ENV"
      ],
      "inputs": ["$TURBO_DEFAULT$", ".env*"],
      "dependsOn": ["^build"],
      "outputs": [".next/**", "!.next/cache/**", ".expo/**", "dist/**"]
    },
    "start": {
      "cache": false
    },
    "test": {
      "cache": false
    },
    "lint": {
      "dependsOn": ["^lint"],
      "inputs": ["$TURBO_DEFAULT$", ".env*"]
    },
    "check-types": {
      "dependsOn": ["^check-types"],
      "inputs": ["$TURBO_DEFAULT$"]
    },
    "dev": {
      "inputs": ["$TURBO_DEFAULT$", ".env*"],
      "persistent": true,
      "cache": false
    }
  }
}


packages/test/src/index.ts:
export const test = () => {
  console.log(`Has ENV: ${process.env.TEST_ENV}`);
};

2 Replies

Yacare CaimanOP
Only way I was able to access the env variables was by adding this, but is this the right way to go about this?

import { resolve } from "node:path";
import { config } from "dotenv";

config({ path: resolve(__dirname, "../../../.env") });


Thought I'd be able to access my root .env without this or at least the package / app directory level .env file any code is running in, but it seems I need to resolve that with dotenv as well.
hi i made a monorepo starter, i was able to get the envs
https://github.com/roopaish/fs-mono
check here you might find something