I have a problem accessing the variables in the .env (which is located in /bot/.env). If I try to do for example const { var1 } = process.env; it shows me the first variable of the file, but instead if I try to do const { token } = process.env.var1; it returns undefined ( The file from which I try to access is the index.js, located in /bot/src/index.js).
Code example (.env):
VAR1=MA31xz13S //TOKEN EXAMPLE
VAR2=1234567890 //ID EXAMPLE
Code example 1 (index.js):
require("dotenv").config();
const { var1, var2 } = process.env; //var1 prints MA31xz13S, var2 prints undefined
Code example 2 (index.js):
require("dotenv").config();
const { var1 } = process.env.VAR1; //This prints UNDEFINED
const { var2 } = process.env.VAR2; //This prints UNDEFINED
Code example 3 (index.js):
require("dotenv").config();
const { var1 } = process.env; //This prints MA31xz13S
const { var2 } = process.env.VAR2; //This prints UNDEFINED
(UPDATE) TO BE MORE CLEAR, var1 is a discord bot token, and var2 is the ClientID
2
Answers
The issue is due to a misunderstanding ofenvironment variables work.
In .env file,two variables are provided: VAR1 and VAR2. When we use dotenv, these are loaded into the process.env object in Node.js.
So, when we write const { var1 } = process.env;, it’s trying to destructure var1 from process.env, but var1 doesn’t exist in process.env. What we have in process.env are VAR1 and VAR2.
If we want to access VAR1 and VAR2
In the code, const { var2 } = process.env.VAR1; is trying to destructure var2 from process.env.VAR1, but process.env.VAR1 is a string ("NameForVar1"), not an object, so it can’t be destructured, This why we get undefined.
Always Remember, the keys in process.env are the variable names in your .env file, and the values in process.env are the corresponding values from your .env file. So, we should use the exact variable names from our .env file when accessing them in process.env.
Verify that your.env file contains no spaces around the = symbol. similar to the code below
Verify that the package.json file and the.env file are both stored in the root directory of your project. If it’s somewhere else, you’ll have to call dotenv.config() with the path specified, like in the code below.
Accessing Variables: Verify that you are using the right case when attempting to access the variables. You must use VAR1 and VAR2 (not var1 and var2) when accessing process.env if your.env file contains VAR1 and VAR2.
Environment: Make sure that certain environment variables are configured in a certain environment before trying to access these variables there. Generally, only development environments need the.env file.