How can I check if an environment variable is set in Node.js?
Javascriptnode.jsEnvironment VariablesJavascript Problem Overview
I would like to check if an environment variable is set in my Express JS server and perform different operations depending on whether or not it is set.
I've tried this:
if(process.env.MYKEY !== 'undefined'){
console.log('It is set!');
} else {
console.log('No set!');
}
I'm testing without the process.env.MYKEY
but the console prints "It is set".
Javascript Solutions
Solution 1 - Javascript
This is working fine in my Node.js project:
if(process.env.MYKEY) {
console.log('It is set!');
}
else {
console.log('No set!');
}
EDIT:
Note that, As @Salketer mentioned, depends on the needs, falsy value will be considered as false
in snippet above. In case a falsy value is considered as valid value. Use hasOwnProperty
or checking the value once again inside the block.
> x = {a: ''}
{ a: '' }
> x.hasOwnProperty('a')
true
Or, feel free to use the in operator
if ("MYKEY" in process.env) {
console.log('It is set!');
} else {
console.log('No set!');
}
Solution 2 - Javascript
I use this snippet to find out whether the environment variable is set
if ('DEBUG' in process.env) {
console.log("Env var is set:", process.env.DEBUG)
} else {
console.log("Env var IS NOT SET")
}
Theoretical Notes
As mentioned in the NodeJS 8 docs:
> The process.env
property returns an object containing the user environment. See environ(7).
>
> [...]
>
> Assigning a property on process.env
will implicitly convert the value to a string.
>
>
>
> process.env.test = null
> console.log(process.env.test);
> // => 'null'
> process.env.test = undefined;
> console.log(process.env.test);
> // => 'undefined'
Though, when the variable isn't set in the environment, the appropriate key is not present in the process.env
object at all and the corresponding property of the process.env
is undefined
.
Here is another one example (be aware of quotes used in the example):
console.log(process.env.asdf, typeof process.env.asdf)
// => undefined 'undefined'
console.log('asdf' in process.env)
// => false
// after touching (getting the value) the undefined var
// is still not present:
console.log(process.env.asdf)
// => undefined
// let's set the value of the env-variable
process.env.asdf = undefined
console.log(process.env.asdf)
// => 'undefined'
process.env.asdf = 123
console.log(process.env.asdf)
// => '123'
A side-note about the code style
I moved this awkward and weird part of the answer away from StackOverflow: it is here
Solution 3 - Javascript
Why not check whether the key exists in the environment variables?
if ('MYKEY' in Object.keys(process.env))
console.log("It is set!");
else
console.log("Not set!");
Solution 4 - Javascript
As the value (if exist) will be a string, as mentioned in the documentation:
process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'
and empty string can be returned (that happened to me in CI process + GCP server),
I would create a function to clean the values from process.env
:
function clean(value) {
const FALSY_VALUES = ['', 'null', 'false', 'undefined'];
if (!value || FALSY_VALUES.includes(value)) {
return undefined;
}
return value;
}
const env = {
isProduction: proces.env.NODE_ENV === 'production',
isTest: proces.env.NODE_ENV === 'test',
isDev: proces.env.NODE_ENV === 'development',
MYKEY: clean(process.env.MYKEY),
};
// Read an environment variable, which is validated and cleaned
env.MYKEY // -> 'custom values'
// Some shortcuts (boolean) properties for checking its value:
env.isProduction // true if NODE_ENV === 'production'
env.isTest // true if NODE_ENV === 'test'
env.isDev // true if NODE_ENV === 'development'
Solution 5 - Javascript
EDIT (removed old incorrect answer)
As maxkoryukov said, it should be:
# in test.js
if ("TEST_ENV" in process.env) {
console.log("TRUE: " + process.env["TEST_ENV"])
} else {
console.log("FALSE")
}
This was true with he following test:
$> node test.js
FALSE
$> export TEST_ENV="SOMETHING"
$> node test.js
TRUE: SOMETHING
This also works when the variable is an empty string (tested in a new bash session/terminal window).
$> node test.js
FALSE
$> export TEST_ENV=""
$> node test.js
TRUE:
Solution 6 - Javascript
If you're assigning a value with your if statement, you could do it like this
var thisIsSet = 'asddas';
var newVariable = thisIsSet ||'otherValue'
console.log(newVariable)
Results in asddas
Solution 7 - Javascript
I do practice to use built-in Node.js assert library.
const assert = require('assert');
assert(process.env.MY_VARIABLE, 'MY_VARIABLE is missing');
// or if you need to check some value
assert(process.env.MY_VARIABLE.length > 1, 'MY_VARIABLE should have length greater then 1');
I use to add this validation on top of the index.js, and keep it up to date with the code requirements. This way is also easy to check which variables are required for the project, if for some reason .env.example is not in the code.
Solution 8 - Javascript
It's good way to check your environment variable
if (process.env.YOUR_ VARIABLE) {
// If your variable is exist
}
Otherwise, If you would like to check multiple environment variables, you can check this node module
out.
Solution 9 - Javascript
You can create .env.example
which stores all the required env variable by the application.
After this you can load this .env.example
and compare with .env
.
In this way, you can check all the required envs on the time of application start.
To minimize the task, you can use scan-env npm package, which does the same.
const scanEnv = require("scan-env");
const scanResult = scanEnv();
if (!scanResult) {
console.error("Environment variables are missing.");
}
Solution 10 - Javascript
You can solve easily with || operator with default value attribution case the env var doesn't exist:
const mykey = process.env.MYKEY || '1234';
Solution 11 - Javascript
let dotenv;
try {
dotenv = require('dotenv');
dotenv.config();
}
catch(err) {
console.log(err);
// if vars are not available...
}
//... vars should be available at this point