Setting up environment variable in nodeJs - node.js

How can we set environment variables in NodeJs
I have tried this in my terminal
NODE_ENV=prod
node index.js
and then inside my code when I try to log it (config.js file which is imported in index.js and where i configure everything)
console.log(process.env.NODE_ENV)
it gives me undefined

Use
export NODE_ENV=prod
also you should create a .env file and keep all your environments in the same.
In your config file set the default values
NODE_ENV = process.env.NODE_ENV || 'prod';

Related

Environment variables not changing in Node.js

set NODE_ENV=production not working in my pc. NODE_ENV is not changing from "development"
if(app.get('env') === 'development'){
app.use(morgan('tiny'));
console.log("Morgan enabled...");
}
set PORT=5000 not working - PORT is not changing from "3000".
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
As a Windows user, I had problems in the past with exporting / setting environment variables for node to use.
I ended up using the dotenv NPM package since you can be sure it correctly loads the environment variables regardless of what system you are developing on.
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.
First, install and save it:
npm i dotenv
Create a file in the root of your project called .env
PORT=5000
You can set any number of variables using simple X=Y syntax.
Then, somewhere in your code:
require('dotenv').config();
// my main application code
With the above example, you now have access to process.env.PORT which will equal 5000 (value set from the .env file)
Note: Avoid storing .env in your version control by adding a .gitignore rule:
node_modules/
# Other ignore rules...
# Add this line
.env
Good luck!
you should be installed dotenv by yarn add dotenv then make file to in the folder .env
in the server or the main page for app add this code
const dotenv=require('dotenv').config({path:'./env})
//this depand where are you store the .env and the name file for path
and in the file .env make variable
PORT=3000

require('config') loaded nothing in debug

My nodejs app config = require('config') (3.0.1) returns nothing in debug. Here is the console output:
config:
Config {}
NODE_ENV is only defined in development.json and loading in development has no problem.
Here is the files under ./config:
What could cause the config module failed to load in debug?
The config filenames need to be tied to the NODE_ENV or NODE_CONFIG_ENV you're setting when you run your app. (https://github.com/lorenwest/node-config/wiki/Configuration-Files#file-load-order)
You don't set NODE_ENV in the config files themselves.
So for example (assuming the command to run your app is npm start):
NODE_CONFIG_ENV=foo npm start
^ This would first load all of the config properties in default.json, then override them with any properties you set in foo.json. If you wanted to add a local.json, those properties would be a final override.
I believe it defaults to assuming your env is "development", and I'm guessing your default.json is empty.

Environment Variables not getting set in Nodejs app

For some reason I can't set the environment variables on my node js app. I am currently trying to use dotenv package to set my environment variables and I put a log statement in the config() method to print out the processes.env variable and it looks like it adds the variables correctly. However, once I'm back in my index.js when my app runs, logging the process.env only shows the following environment variables:
NODE_ENV : "development"
PUBLIC_URL : ""
I've tried just about everything. Why can't I set the environment variables for my node app?

how to configure express js application according to environment? like development, staging and production?

I am new to expressjs app development, now need to configure application as per environment. came across 'node-env-file' , 'cross-env'. but hardly understood anything. Pls suggest how to set env variables as per environment or some good documentation suggestions pls?
Based on environment, I would like to load my configuraiton file.As of now, I have two config files, one for dev and one for production.
The idea is to set NODE_ENV as the environmental variable to determine whether the given environment is production or staging or development. The code base will run based on this set variable.
The variable needs to set in .bash_profile
$ echo export NODE_ENV=production >> ~/.bash_profile
$ source ~/.bash_profile
For more, check Running Express.js in Production Mode
I follow Ghost.org (a Node.js production) app's model.
Setting environments
Once that is done, you can have the environmental details in respective json files like config.production.json, config.development.json
Next, you need to load one of these file based on the environment.
var env = process.env.NODE_ENV || 'development';
var Nconf = require('nconf'),
nconf = new Nconf.Provider(),
nconf.file('ghost3', __dirname + '/env/config.' + env + '.json');
For more on how Ghost does this, check config/index.js
I use a .env file with env vars:
VAR=VALUE
And read that with source command before running express
$ source .env
$ node app.js
Then, to access inside express, you can use:
var temp = process.env.VAR; //contains VALUE
You can use dotenv module, to automatically load .env file

Node JS, detect production environment

When I'm in dev mode I don't want my server to send email and some other stuff so I have this in server.js file:
process.env.NODE_ENV = 'development';
When I move it to production i change the value to 'production'.
Problem is of course that it is easy to forget on deployments. Is it possible somehow to detect when server is in production?
If it's not, is it possible to write a batch script that replaces a string in a file?
You shouldn't manually change values of process.env object, because this object is reflecting your execution environment.
In your code you should do the following:
const environment = process.env.NODE_ENV || 'development';
And then you launch your app in production like this:
$ NODE_ENV=production node app.js
If NODE_ENV environment variable is not set, then it will be set to development by default.
You could also use dotenv module in development to specify all environment variables in a file.
Furthermore, I've implemented a reusable module, which allows to automatically detect environment by analyzing both CLI arguments and NODE_ENV variable. This could be useful on your development machine, because you can easily change environment by passing a CLI argument to you Node.js program like this: $ node app.js --prod. It's also nice to use with Gulp: $ gulp build --prod.
Please see more details and use cases on the detect-environment's page.
The suggested way to tackle these kind of problems is by using the process global object provided by NodeJS. For example:
var env = process.env.NODE_ENV || "development";
By the above line. We can easily switch between development / production environment. If we haven't configured any environment variable it works with development environment.
process.env is an object that contains the user environment.
For example if we are running our application in a bash shell and have configured NODE_ENV to production. Then i can access that in node application as process.env.NODE_ENV.
There are multiple ways to define this NODE_ENV variable for nodejs applications:
## Setting environment variable for bash shell
export NODE_ENV=production
## Defined while starting the application
NODE_ENV=production node app.js
So i don't think you would require any batch file for this. When handling multiple configuration variables, follow this.
This is normally handled through configuration files (e.g. config frameworks like node-convict) and through environmental variables. In the start command in production, you might do something like:
NODE_ENV=production npm start
then the process.env.NODE_ENV would be properly set by any module in your app that cares.

Resources