nx: Unable to pass node enviroment variables to node-app

  • I am running the latest version
  • I checked the documentation and found no answer
  • I checked to make sure that this issue has not already been filed
  • I’m reporting the issue to the correct repository (not related to Angular, AngularCLI or any dependency)

Expected Behavior

I want to have an Express App inside the workspace created by Nx. So I created a node-app using the CLI, and was able to get it working so far. The problem is that I am using dotenv to load some variables into process.env. I don’t want to use environment.ts files because those files are in version control.

The issue I am facing is that on development using ng serve, I did not figured a way to load enviroment variables into the child process (I see on source that it uses fork).

On production I would just use pm2 or something to load the vars into the node process, or load it from the .env file.

Also, I cannot have it as an asset that is copied over to dist, because on rebuild the dist .env file cannot be overwritten, only if it could have assets setup that is only copied on ng serve and not copied on ng build

Current Behavior

Unable to pass process.env variables from ng serve.

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

  1. Create workspace with node-app
  2. Use process.env['SOME_VAR'] inside node-app
  3. Try to pass this var to ng serve your-app

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (2 by maintainers)

Most upvoted comments

I was able to find a correct solution, closing…

@jmcdo29 dotenv works for me, and the setup is like this:

In my main.ts server file I placed this as the first line.

require('dotenv').config()

Optionally, if any problems, for debugging you can put this code:

const result = require('dotenv').config()
if (result.error) {
  throw result.error
}
console.log(result.parsed)

And in your root directory just create .env file, the root is the curent working directory I suppose

ORIENTDB_ROOT_PASSWORD="root"
ORIENTDB_HOST="localhost"
ORIENTDB_POR=2424

In my case I was trying to set NODE_ENV to test to use the appropriate env file (I have one for development and another for testing). I found the solution here: https://stackoverflow.com/a/59805161/8526764

For anyone who is still having the problem, try defining dotenv import in a separate file and import that file in main.ts as the first line. ES6 imports are hoisted and ran in order of declaration.

Example

// config.ts
import * as dotenv from 'dotenv';
dotenv.config({path: 'path to your env file'});

// main.ts
import './config.ts';
// reset of your code