Node Env not set? - iisnode

This is a general question though I haven't found where I am going wrong.
Using Windows Server with Azures kudu stand alone to host a local project.
Also using React, Webpack, Redux
Windows environment var is set to production
Package.json has set NODE_ENV=production && etc.. for
both start and build scripts
web.config has iisnode node_env=production
running node I get the node_env is indeed production
However when I build it's giving me the development build when I do something like
if (process.env.NODE_ENV === 'production') {
module.exports = require('./buildProduction.js')
}
else {
module.exports = require('./buildDevelopment.js')
}
What gives?

I came to the same conclusion and searched why this is and thanks to neagtivetwelve for the comment # https://github.com/webpack/webpack/issues/1720
In short setting
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
fixes the issue. Instead of
new webpack.DefinePlugin({
'process.env.NODE_ENV': process.env.NODE_ENV,
}),
Even though I have in the build script to set the session NODE_ENV var and set within the system environment vars I would still get the wrong result until this change was made even though opening node from cmd and typing process.env.NODE_ENV yields the correct result.
Anyway I hope it helps someone else.

Related

Heroku NODE_ENV is always "development" despite setting config var to "staging" (NestJS app)

In my Heroku environment where I deploy my NestJS application, I set all my Config Vars through the Heroku UI. I have set my NODE_ENV config var to staging using the Heroku UI. I've even ran this command heroku config:set NODE_ENV=staging -a <my-staging-environment. When I run heroku config -a <my-staging-environment>, I see that NODE_ENV is set to staging, but for whatever reason, when I console.log this variable from my code, it outputs development. Below is some example code where it is logs development as the value for NODE_ENV in my TypeOrm configuration. This is causing the ssl property to not get set to the correct value, and I cannot connect to my Heroku Postgres database because of it. I only intend to set it to development for local development purposes.
require('dotenv').config();
console.log(process.env.NODE_ENV); // outputs "development" - idk where this value is coming from
console.log(process.env.DATABASE_URL); // outputs the correct value that I set in Heroku Config Vars
const typeOrmConfig: TypeOrmModuleOptions = {
type: 'postgres',
url: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV !== 'development' ? { rejectUnauthorized: false } : false, // ternary evaluates to the wrong value
// ... other config options
};
I use dotenv, and I made sure to .gitignore my .env file. I don't recall ever setting this variable to development. The only place I see it set to NODE_ENV=development in my code is in my .env-example file. I do commit this file to source control, but it's just an example file and not a real .env file and it shouldn't actually be being used.
Does anyone have any idea why this is happening?
I have found that it is not a Heroku issue. Rather it is a NestJS/Nx issue.
See:
process.env.NODE_ENV always 'development' when building nestjs app with nrwl nx

Can you run Sapper with NODE_ENV=test

I'm converting a project from Angular + Node.js server --> Sapper. In relation to e2e tests, there is something I can't understand; can I run Sapper with NODE_ENV env variable set to test? When I run export NODE_ENV=test && sapper dev the variable is always dev. How can I fix this?
My current work-around is to build the application, and then start it with node __sapper__/build, but this is not very nice when developing e2e tests.
Sapper is an open-source project, so we can check how NODE_ENV is set: https://github.com/sveltejs/sapper.
When running sapper dev, the environmental variable NODE_ENV is set in /src/api/dev.ts
(/src/api/dev.ts)
process.env.NODE_ENV = 'development';
where it's hard-coded to development.
The variable can be set to other values (including testing) in
(/src/cli.ts)
178. process.env.NODE_ENV = process.env.NODE_ENV || 'production';
so I surmise you would need sapper prod (or something similar, check it) to use this NODE_ENV.
You should also check it that doesn't beat the purpose of what you're trying to achieve, perhaps sticking to sapper dev is preferable to running in non-dev mode.

jestjs - how to parametrize test execution from cli in ci?

i have 4 environments :
dev (developers area)
test (test area)
preprod (pre production environment)
production (production environment)
these environments needs different configuration to execute tests (differents urls, usernames, assets, and so on).
how to pass there configurations to jest as a parameter in continous integration?
As you can read here, jest would not permits to pass custom arguments you can use to handle custom configuration loaded at runtime.
i propose a workaround working for me.
create a configuration file, e.g. config.js
edit config.js and exports modules switching for the environment
switch (env) {
case "test":
module.exports = {
baseUrl: 'https://test.website.com'
}
break;
case "production":
module.exports = {
baseUrl: 'https://production.website.com'
}
break;
}
create a javascript files for every environment you need
test-configuration.js
production-configuration.js
edit these files writing in the environment variables
for example test-configuration.js will be
process.env.ENVIRONMENT = "test"
load configuration for your test files as it was a static file
const config = require('./config.js')
use jest setupFiles to add a setupFiles that load the environment variables.
for example, running
jest --setupFiles=./test-configuration.js
jest will load the test-configuration.js file that will set "test" on the "process.env.ENVIRONMENT" variables, so config.js file will "switch" on the "test" environment and all your test will use it.
so now you can (or CI can) loads configuration as needed.
For anyone facing the same issue – can't pass environment url to your custom setup file and tests. The solution might be dumb but it works without modifying the code much.
In package.json modify your scripts to export environment before running jest:
"scripts": {
"test": "jest",
"test:dev": "export ENVIRONMENT=https://dev.environment/ && jest",
"test:prod": "export ENVIRONMENT=https://prod.environment/ && jest"
}
Then you can access your code:
const page = await browser.newPage();
await page.goto(process.env.ENVIRONMENT);
console.log(process.env.ENVIRONMENT);

Heroku failed to load ./.env

My Problem
I am having trouble loading my environment variables on Heroku production.
When pushing to Heroku I get following error message during the build script:
Failed to load ./.env.
Current Setup
I am using a .env file in the root of my app locally. I can succesfully load my environment variables using the dotenv-webpack plugin as follows:
//webpack.config
const Dotenv = require('dotenv-webpack')
module.exports = {
// other settings...
plugins: [
new Dotenv(),
]
};
Loading the environment variables:
//server.js
require('dotenv').config();
console.log(process.env.MY_VARIABLE);
This works like a charm locally, but fails on Heroku.
Note: My config vars have been set on Heroku, so that's not the problem.
What I tried
I have already tried to force load the .env file from the root of my app like this:
new Dotenv({ path: path.resolve(__dirname, './.env') });
Someone also pointed out that the Heroku environment might be system wide environment variables so I tried to load them using:
new Dotenv({ systemVars: true });
Neither of these attempts worked for me.
My guess
I have noticed that Heroku saves their .env file under ./tmp/build_someRandomBuildId/.env. My guess is that the .env file is not on the root of the directory, hence why dotenv can't find it. There is also no way to hardcode the location of this file in my Webpack configuration as the build ID is randomized with every build. Is there a way to tell Webpack to look for the file in a dynamic location?
Today i stumbled upon this problem, i tried several solutions but none worked. My App was working locally but in production mode (heroku) it was not loading process.env correctly.
then i found this https://www.npmjs.com/package/dotenv-webpack
//webpack.config.js
plugins: [
new Dotenv({ systemvars: true }),
],
Just setting systemvars to true does the trick..
For now I have tested this using different keys for the .env file and the heroku dashboard; They are not connected, and they replace themself correctly in production or dev mode.
Use the package "dotenv-webpack" instead of "dotenv".
I hope this saves some time to anyone facing the same problem
I finally found the solution, leaving this here for others who have the same problem as I did.
I used dotenv-webpack to set my environment variables locally, which worked like a charm. Heroku on the other hand sets their environment variables automatically, so there is no need to set them yourself. There is no need to look for a .env file. All I had to do was split up my webpack.config in 2 separate files.
//webpack.dev
require('dotenv').config();
plugins: [
new Dotenv()
],
Load .env file locally.
//webpack.prod
require('dotenv').config();
plugins: [
new webpack.DefinePlugin({
'process.env': {
'YOUR_VARIABLE': JSON.stringify(process.env.YOUR_VARIABLE),
}
});
]
Get your environment variables from Heroku and write them to your own process.env
If you are not using Webpacks, the idea's solution is similar to the accepted answer.
Heroku works on "production" mode by default, so if the problem in Heroku is with Dotenv (which should not be used anyways in Heroku), disable the use of Dotenv in production time like this:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config() }
}
...and then, access env variables just by doing:
var someVar = process.env.SOME_VARIABLE;
Don't forget to set the environment variables on Heroku first by using Console Commandline in your app's dashboard, or with an app.json file.

meanjs best practice to setup process evn for database

In my attempt to get a 'hello world' skill with meanjs.org product, I cloned 0.4.2 and setup a mongolab account.
I opened > config > env > development.js, to setup db URL, where I have this:
db: {
uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
For trial, I simply replaced process.env.MONGOLAB_URI with my URL from mongolab and everthing worked for sure, but I doubt this is the way to go. I see a Procfile there, may be I should specify the process.env.MONGOLAB_URI there? Where I could specify it, so that if I upload it to Heroku, say, it will setup the process.env.MONGOLAB_URI and no edit will be needed here please?
p.s. I googled and searched SOF
Well just a small progress,
I got to my gulpfile.js and setup a task as:
gulp.task('setmydb', function () {
process.env.MONGOLAB_URI =
'mongodb://mylogin:mypassword#ds157479.mlab.com:57479/meantst1';
});
Then at the end of the file, added into the task sequence:
// Run the project in development mode
gulp.task('default', function (done) {
runSequence('env:dev', 'lint', ['setmydb','nodemon', 'watch'], done);
});
Well it worked, but I'm still not sure if this indeed is how it must be done! So please help me get sure.
Just in case if someone else also needed, this is how I solved my problem:
Setting configuration variables | Heroku
I first followed the Heroku getting started and edited their app there, added this root:
app.get('/envtst', function(request, response) {
var xterm = process.env.XVAR ==='yes' ? 'yes' : 'no';
response.send(xterm);
});
Then pushed the app to Heroku and also setup my test variable XVAR via command line:
heroku config:set XVAR=yes
finally, opened the root in browser and verified.

Resources