Next.js Discord

Discord Forum

Next doesn't load environment in Turborepo

Answered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I loaded up the Next + Turborepo starter, setup T3env, placed my .env in the root, and Next isn't loading the env file.

To get the .env to load I need to prefix any command with dotenv-cli: dotenv -- turbo dev which is kind of annoying

I can reproduce this by
- cloning the starter: https://vercel.com/templates/next.js/turborepo-next-basic
- converting next.config.js to .mjs
- creating .env.local with SOME_VAR=123 in monorepo root
- adding to next.config.mjs: console.log(process.env.SOME_VAR);
- see that turbo run dev logs undefined

Am I just missing something extremely basic?
Answered by Ray
try these setup in apps/web/packages.json
  "scripts": {
    "dev": "pnpm with-env next dev",
    "build": "pnpm with-env next build",
    "start": "pnpm with-env next start",
    "lint": "pnpm with-env next lint",
    "with-env": "dotenv -e ../../.env --"
  },
View full answer

10 Replies

I've met this issue several time in this week - try renaming your .env.local to .env and check again
on some machines .env.local is not working, but .env is... badly
Asian black bearOP
unfortunately doesn't work
where did you created .env file? 😄
@Asian black bear unfortunately doesn't work
try these setup in apps/web/packages.json
  "scripts": {
    "dev": "pnpm with-env next dev",
    "build": "pnpm with-env next build",
    "start": "pnpm with-env next start",
    "lint": "pnpm with-env next lint",
    "with-env": "dotenv -e ../../.env --"
  },
Answer
@Ray try these setup in apps/web/packages.json json "scripts": { "dev": "pnpm with-env next dev", "build": "pnpm with-env next build", "start": "pnpm with-env next start", "lint": "pnpm with-env next lint", "with-env": "dotenv -e ../../.env --" },
yeah, that can be the solution as well, but only if your apps are using same env vars, in other situation you need to create .env.local in each aplication's root (for example /apps/web/ and /apps/docs separately)
placing .env into apps/web/ also did work but i feel like that kinda defeats the purpose of a monorepo in a way
in monorepo you are supposed to aggregate multiple separate porjects, that shares packages, generally, so it's natural that each app have it's own env vars 😄
docs app doesn't need env for cms used in blog for example, to give it more image