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.
- Create workspace with node-app
- Use
process.env['SOME_VAR']inside node-app - 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)
I was able to find a correct solution, closing…
@jmcdo29
dotenvworks for me, and the setup is like this:In my
main.tsserver file I placed this as the first line.Optionally, if any problems, for debugging you can put this code:
And in your root directory just create
.envfile, the root is the curent working directory I supposeIn my case I was trying to set
NODE_ENVtotestto use the appropriate env file (I have one for development and another for testing). I found the solution here: https://stackoverflow.com/a/59805161/8526764For 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