nx-remotecache-custom icon indicating copy to clipboard operation
nx-remotecache-custom copied to clipboard

Loading dotenv prevents nx from properly layering env files

Open cuddlecake opened this issue 2 years ago • 2 comments

Hi,

NX has the feature of allowing developers to create .env files specific to different targets and configurations: https://nx.dev/recipes/environment-variables/define-environment-variables

E.g. having a baseline .env file and .env.serve with overrides

Under the hood, they parse each file and layer them according to the rules mentioned in the docs, and then override those with process.env, e.g.

// Start With Dotenv Variables
...this.getDotenvVariablesForTask(task),
// User Process Env Variables override Dotenv Variables
...process.env,

Which makes sense, since user provided environment variables should override environment files.

The issues is, this library uses dotenv to parse and configure relevant variables from .env file, during which this line is executed:

if (!processEnv[key]) {
  processEnv[key] = parsed[key]
}

This means that process.env is populated by dotenv with the values from .env if they aren't already present, which prevents NX from properly layering the environment files, because process.env will always override everything with the values from .env (the code from this library is executed earlier than NX's internal loading code).

My suggestion would be to read the .env file manually and parse it using dotenv.parse(dotenvFileContent) instead of calling dotenv.config().

For us, since we're not using dotenv, we disabled this option anyway.

cuddlecake avatar May 23 '23 12:05 cuddlecake

Ah interesting, I might have missed that during one of the upgrade. I'll see if I maybe can use the dotenv parser from NX directly, without any custom code. Would be way nicer.

NiklasPor avatar May 23 '23 12:05 NiklasPor

This issue has been fixed in Nx directly:

https://github.com/nrwl/nx/blob/3d9bd16ce0f322e28e082bbb09f73069310ed6f2/packages/nx/src/tasks-runner/task-env.ts#L186-L201

cuddlecake avatar Apr 23 '24 12:04 cuddlecake