So I have install npm config module.
I have trying to set a local variable that stores a secret/privateKey.
Tried setting an environment variable/private key using the following command
export VIDLY_JWTPRIVATEKEY=MYSECUREKEY
however it don't think It is being set as I get an error via
console.log("FATAL ERROR: JWTPRIVATEKEY is not defined");
This is how I am checking if the key is set..
index.js
if (!config.get("JWTPRIVATEKEY")) {
console.log("FATAL ERROR: JWTPRIVATEKEY is not defined");
// node environment variable. 1 (any other number exc. 0) is exit the app, 0 is success
process.exit(1);
}
userAuth.js I once again try to get the private, however its not set (?)
#code above
const token = jwt.sign({ _id: user._id }, config.get("JWTPRIVATEKEY"));
default.json (in config module folder)
{
"JWTPRIVATEKEY": ""
}
custom-environment-variables.json (in config folder)
{
"JWTPRIVATEKEY": "VIDLY_JWTPRIVATEKEY"
}
**
ERROR: "FATAL ERROR: JWTPRIVATEKEY is not defined"
**
What am I doing wrong?
Instead of setting the variable with this way, you can try to set it in production and development config folders like this:
config/development.js
const config = {
env: 'development',
JWTPRIVATEKEY: <your_dev_key>
};
module.exports = config;
config/production.js
const config = {
env: 'production',
JWTPRIVATEKEY: <your_prod_key>
};
module.exports = config;
it is two years later! but i think it can be useful, atleast for others.
if you set environment variable AND run the app in IDE's Terminal, it will not work!
but if do these in "cmd", it works.
Related
I have a node.js application built using graphql. I need to check an 'environment variable' to see what environment I'm on (development, testing, production). Based on that environment, I need to set a url. I think I have a vague idea of what I need but don't know how to accomplish it.
Currently my config.js file looks something like this:
const configuration = convict({
env: {
format: ['development', 'testing', 'production'],
default: 'development',
arg: 'nodeEnv',
env: 'NODE_ENV'
}
const env = configuration.get('env');
configuration.loadFile(`./config/${env}.json`);
configuration.validate({allowed: 'strict'});
module.exports = configuration.getProperties();
)};
And then in a separate file where I actually need to set the url based on the environment, I need to do so based on the kind of environment (development, test or production) that I'm on. The code in that file would be:
If(env=='development'){
const url = 'abc.def.com/xxx/yyy/zzz/graphql';
}
Else If (env == 'testing'){
const url = 'xxx.yyyy.com/abc/def/ghi/graphql';
}
Else{
const url = '123.abc.com/cdc/def/hhh/graphql';
}
I tried to console.log the env value but when I try the following:
console.log( env );
I get an error: Reference error: env is not defined.
Can someone point me to what I'm missing/doing wrong to access the env variable?
You can access them like this:
process.env.VARIABLE_NAME
In my node app, I want to set production and development in my config.js file.
For that I have all most set all thing but I'm still missing something.
I want to get config data like database credential from config file based on my development mode. If I upload on live then app will use live cred. On other hand if I used local then it should be use local cred.
module.exports = function () {
console.log("Process env is ::: ", process.env.NODE_ENV);
if (process.env.NODE_ENV == 'production') {
return {
db : {
host:'localhost',
batabase:'dbname',
username:'',
password:''
}
}
} else {
return {
db : {
host:'localhost',
batabase:'dbname',
username:'',
password:''
}
}
}
};
I have taken ref from this answer
Just try this way.
module.exports = (function () {
process.env.NODE_ENV='development';
if(process.env.NODE_ENV === 'production'){
// Config data of Live
}else{
//Config data of Local
}
})()
This works for me. :)
process.env refers to the Environment Variables exists at the time you start you nodejs app . (it's part of the os)
When you deploy to cloud , usually it's handled for you already (process.env.NODE_ENV = production) .
Some cloud providers even give you the option to control it via a GUI .
But for local environment , you can use .dotenv package . (https://github.com/motdotla/dotenv)
With this package you create a .env file at the top of your project ,
and just write down NODE_ENV = local/staging/production
Please note that you can always run in shell:
export NODE_ENV=production
(WATCH FOR WHITESPACES !)
before you start you nodejs app which will also give you the effect
of controlling process.env
Using the config files in other files, just by requiring it .
const config = require('path/to/config.js');
then config.data.host will be changed depend on the NODE_ENV
I am learning how to configure my Node.js App environment. For this I am using config module.
Below is my index.js file:
`
const config=require('config');
const express=require('express');
const app=express();
app.use(express.json()); //BUILT-IN EXPRESS MIDDLEWARE-FUNCTION
//CONFIGURATION
console.log('Current Working Environment:',process.env.NODE_ENV);
console.log('Name is:', config.get('name'));
console.log('Server is:', config.get('mail.host'));
console.log('Password is:', config.get('mail.password'));
`
I set NODE_ENV to production by the power shell command: $env:NODE_ENV="production".
My production.json file inside the config folder is:
`{
"name":"My Productoin Environmet",
"mail":{
"host": "Prod-Environment"
}
}`
And custom-environment-variables.json file is:
`{
"mail":{
"passwrod":"app_password"
}
}`
I set app_password to 12345678 by the power shell command : $env:app_password="12345678"
config.get() is supposed to look at various sources to look for this configurations including, json files, configuration files and also environment variables. But whenever I run my app, I get the following error:
`throw new Error('Configuration property "' + property + '" is not defined'); Error: Configuration property "mail.password" is not defined`
If I remove the line : console.log('Password is:', config.get('mail.password')); everything goes well. Please, guide me what is the solution?
Firstly you have a lot of syntactical errors for example in
custom-environment-variables.json
{
"mail":{
"password":"app_password"
}
}
Now if u need to store the password of your mail server in the environment variables
On windows
$env:app_password=12345
On Linux and OSX:
export app_password=12345
how to run ?
app.js
const config = require("config");
console.log("Mail Password: " + config.get("mail.password"));
i had the same problem because i didn't define an environment variable for storing the password of the mail server. So, my suggestion will be define your environment variable for storing the password using the below command line (mac) and then your code should work.
export app_password=/* the password you want to set */
how to define an environment variable for storing the password of the mail server.
While defining environment variables in command_prompt don't put space on either side of '=' sign.....
eg:
set app_password = 123456 -----> is wrong way
set app_password=123456 -----> will work
The issue in 99% of cases is in the name of the file in the config folder, storing your custom variables
To add on: make sure your file has .json extension.
Brand new to node trying to understand a project. The project loads on dev on a windows machine just fine, but throws this error on Azure App Services..
TypeError: Cannot read property 'database' of undefined
when trying:
config.database for example in index.js
models/index.js
const env = process.env.NODE_ENV || "development";
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
>>> var whatever = config.database; <<<
config/config.json
{
"development": {
"logging": false,
"dialect": "mssql",
"username": "whatever",
"password": "whatever",
"database": "whatever",
"host": "whatever",
"dialectOptions": {
"encrypt": true
}
}
}
No idea where to start with this since it works fine on local. The file location seems correct, path is valid, path.join() works fine...
Thank you!
There is really only one main possibility here and you need to do a little bit of your own debugging to verify it.
Because this statement does not generate an error:
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
That means that require(path.join(__dirname, '..', 'config', 'config.json')) is returning a Javascript object. So, there must indeed be a file at the path you construct and it must be giving you an object when you require() it.
But, the error itself: TypeError: Cannot read property 'database' of undefined when you try to reference config.database means that config is undefined. The only way that happens is that you're using a value for env that is not in your config object.
That's like trying to do this:
const obj = {development: {someKey: "someValue"}}; // what require() gives you
const env = "test"; // your value for env
const config = obj[env]; // reading non-existent [env] property
console.log(config); // undefined
So, add console.log(env) to your code to see what env actually is and then verify that you have an object in your config data structure for that specific value (or set the desired value in the environment).
If you had verified the value of env yourself with basic debugging steps before posting here, you probably would have solved your own problem (hoping you can learn simple techniques to solve more of your own problems).
If you didn't follow all of my original logic, you could also just debug it like this:
const env = process.env.NODE_ENV || "development";
console.log("env: ", env);
const configPath = path.join(__dirname, '..', 'config', 'config.json');
console.log("configPath: ", configPath);
const configObj = require(configPath);
console.log("configObj: ", configObj);
const config = configObj[env];
console.log("config: ", config);
I am trying to execute a command in Node:
cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global
Basically, I want to execute a Git command that returns global configuration (for the current user).
This works fine for me when I execute the command directly on cli. It also works if I do it like this in Node:
var exec = require('child_process').exec;
var config = {
maxBuffer: 10000 * 1024
};
exec('cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global', config, function() {
console.log(arguments);
});
However, as soon as I specify the environment to the config:
var exec = require('child_process').exec;
var config = {
maxBuffer: 10000 * 1024,
env: { // <--- this one
}
};
exec('cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global', config, function() {
console.log(arguments);
});
Things break:
Command failed: fatal: unable to read config file
'(null)/(null)/.gitconfig': No such file or directory
I know the reason, it is because the executed Git program is no longer executed under the user environment (like it is in cli), and can't retrieve the user directory to read global configuration (in Git, global config = user config) and I believe /(null)/(null)/.gitconfig should be /Users/MyName/.gitconfig which does exist.
My question is, how can I specify the current user environment while still being able to specify my own additional environment properties?
I solved it.
I retrieved the current environment from process.env and extended it with my own properties:
var environment = process.env;
environment.customProp = 'foo';
var config = {
maxBuffer: 10000 * 1024,
env: environment
};
So the problem was I missed the entire environment when I overwrote it.