Home > Enterprise >  error with discord.js when reading .env variables
error with discord.js when reading .env variables

Time:02-06

I'm using discord.js to learn java script, but I'm having a problem with variables stored in .env

apparently they are not being read correctly; and honestly, I don't know if I'm doing something wrong because I don't really know how it works.

my variable in .env is written like this:

TOKEN = xxXxxXXXXxXXXxXXXxXXxXXX
LOG_CHANNEL = 1071616980039249920

i know dotenv is working fine because this line works perfectly: client.login(process.env.TOKEN)

while I have this line in index.js:

client.channels.cache.get(process.env.LOG_CHANNEL).send({
            embeds: [
                // random embed here
            ]
        })

and i receive this error:

        client.channels.cache.get(process.env.LOG_CHANNEL).send({
                                                          ^

TypeError: Cannot read properties of undefined (reading 'send')

but it works perfectly when i change it to:

client.channels.cache.get('1071616980039249920').send({
            embeds: [
                // random embed here
            ]
        })

I tried changing the way the code is written in the .env by adding ` to the variable declaration, but apparently it didn't make any difference.

I'm looking for a way to make this work, as this snippet in index.js recurs frequently and I plan to change the log channel a few times.

Also, I would love a basic explanation of how these declarations work in the .env: are they all considered strings, even without quotes?

CodePudding user response:

Environment variables from .env file are not loaded into Node by default. You can use npm package dotenv to load the variables from the file.

To do so, install the package:

npm install dotenv --save

Then, in your main file, at the beginning, add the following code:

require('dotenv').config();

After this line of code is called, your variables from .env file are available as properties of process.env, i.e. process.env.LOG_CHANNEL. They are of string type. If you want to use them as numbers, you need to convert them in your code.

Also, you might need to keep your variables in .env without additional spaces and with quotes:

LOG_CHANNEL="1071616980039249920"
  • Related