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!');
}
Answer from kucing_terbang on Stack Overflow
Top answer
1 of 11
86

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!');
}
2 of 11
32

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

🌐
Clayton Errington
claytonerrington.com › blog › nodejs-environment-variable-checks
Checking for Environment Variables in a Node.js project
October 25, 2024 - const dotenv = require('dotenv') const path = require("path"); dotenv.config({ path: path.resolve(__dirname, '.env') }); const requiredEnvVars = [ 'REQUIRED_SECRET', 'WEBHOST', 'REQUIRED_PASSWORD' ] const missingVars = requiredEnvVars.filter(varName => !process.env[varName]); if ( missingVars.length > 0 ) { console.error('The following environment variables are missing:'); missingVars.forEach(varName => console.error(`- ${varName}`)); console.error('Please add required environment variables before continuing...'); process.exit(1); }else{ console.log('All required Environment variables are set!') } When the script starts, and loads your .env it adds your variable into the process.env and we are doing a filter where if the process.env[varName] does not exist, since it is not in our .env file, it will add it to the console log messages.
🌐
Better Stack
betterstack.com › community › questions › how-to-read-env-vars-in-node-js
How to read environment variables in Node.js | Better Stack Community
In Node.js, you can read environmental variables using the process.env object. This object provides access to the user environment, including environment variables.
🌐
GitHub
github.com › humanwhocodes › env
GitHub - humanwhocodes/env: A utility for verifying environment variables are present
const env = new Env(); // throws only if variables are not defined const { CLIENT_ID, CLIENT_SECRET } = env.exists; You can also specify an alternate object to read variables from. This can be useful for testing or in the browser (where there is no environment variable to read from by default):
Starred by 376 users
Forked by 17 users
Languages   JavaScript
🌐
Node.js
nodejs.org › en › learn › command-line › how-to-read-environment-variables-from-nodejs
Node.js — How to read environment variables from Node.js
In case you want to optionally read from a .env file, it's possible to avoid throwing an error if the file is missing using the --env-file-if-exists flag. ... Node.js provides a built-in API to load .env files directly from your code: ...
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-check-if-a-variable-exists-or-defined-in-javascript.php
How to Check If a Variable Exists or Defined in JavaScript
<script> var x; var y = 10; if(typeof x !== 'undefined'){ // this statement will not execute alert("Variable x is defined."); } if(typeof y !== 'undefined'){ // this statement will execute alert("Variable y is defined."); } // Attempt to access an undeclared z variable if(typeof z !== 'undefined'){ // this statement will not execute alert("Variable z is defined."); } /* Throws Uncaught ReferenceError: z is not defined, and halt the execution of the script */ if(z !== 'undefined'){ // this statement will not execute alert("Variable z is defined."); } /* If the following statement runs, it will also throw the Uncaught ReferenceError: z is not defined */ if(z){ // this statement will not execute alert("Variable z is defined."); } </script>
🌐
Sophiabits
sophiabits.com › home › blog › how to verify environment variables are set in next.js
How to verify environment variables are set in Next.js | Sophia Willows
June 24, 2023 - If you add that bit of code to your application, you’ll find that when you type process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY you get a string type back instead of string | undefined. Performing this interface augmentation naively would be dangerous, but in our case we’ve ensured that the variable exists at build time.
🌐
Dmitri Pavlutin
dmitripavlutin.com › environment-variables-javascript
Environment Variables in JavaScript: process.env
February 8, 2023 - The environment variables are defined outside of the JavaScript execution context. There's a set of environment variables defined by the OS, for example: ... NODE_ENV: determines if the script runs in development or production mode.
Find elsewhere
🌐
Webdevtutor
webdevtutor.net › blog › typescript-check-if-environment-variable-exists
How to Check if an Environment Variable Exists in TypeScript
if (process.env.MY_VARIABLE !== ... environment. Another approach to checking the existence of an environment variable is by using the hasOwnProperty method available on the process.env object....
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-defined-variable-checking
3 Ways to Check if a Variable is Defined in JavaScript
Compared to typeof approach, the try/catch is more precise because it determines solely if the variable is not defined, despite being initialized or uninitialized. Finally, to check for the existence of global variables, you can go with a simpler approach. Each global variable is stored as a property on the global object (window in a browser environment, global in NodeJS).
🌐
Reddit
reddit.com › r/typescript › how to properly deal with env variables?
r/typescript on Reddit: How to properly deal with env variables?
August 17, 2022 -

I'm using dotenv and storing all vars in a .env file for local development. When I use process.env I keep running into type issues all the time :(

I found some solutions online that say to extend the ProcessEnv interface, and although it seems to work I'm still running into issues.

For example when I use axios:

axios.get<User>(process.env.URL, ...)

I'm getting a compile time error of the form:

type 'string' | 'undefined' is not assignable to type 'string'

Any suggestions on how to properly set up types when using process.env?

🌐
Clerk
clerk.com › blog › how-to-set-environment-variables-in-nodejs
How to set environment variables in Node.js
December 27, 2024 - Before using any environment variables, make sure they are properly set by validating them during startup. This can be done by checking if the variable exists and has a value.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-check-the-existence-of-variable
JavaScript Check the existence of variable - GeeksforGeeks
July 11, 2025 - Example 1: This example checks whether a variable is defined or not. ... let GFG_Var; if (typeof GFG_Var === 'undefined') { console.log("Variable is Undefined"); } else { console.log("Variable is defined and" + " value is " + GFG_Var); }
🌐
Medium
medium.com › @python-javascript-php-html-css › how-to-retrieve-environment-variables-in-python-d4974d2e11b0
In Python, how can I retrieve environment variables?
August 24, 2024 - This is useful for accessing configuration settings without hardcoding them into your scripts. The script also shows how to set an environment variable with os.environ[‘VAR_NAME’] and check if a variable exists using the if ‘VAR_NAME’ in os.environ: condition.
🌐
Doppler
doppler.com › blog › environment-variables-node-js
Using Environment Variables in Node.js for App Configuration and Secrets
Because JavaScript won't error when accessing a key that doesn't exist in process.env, you'll need to design a solution for how your application will behave when a required environment variable is not supplied. One option is to use the ok method from the assert module: If executed without setting ...
🌐
CircleCI
discuss.circleci.com › build environment
How to check if an environment variable exists? - Build Environment - CircleCI Discuss
March 14, 2023 - I created an environment variable which is in this format STAGE_${CIRCLE_USERNAME}. So for my case the environment variable is STAGE_bernard. I am trying to check if the environment variable exists but my logic does not seem to be working. This is the config.yml : jobs: build: parameters: stage: type: string default: "" executor: aws-cli/default steps: - aws-cli/setup - checkout - run: command: | if [[ -z "STAGE_${CIR...