How to Use a .env File For Your Discord Bot

What is a .env File?

A .env file is like a secret stash for your bot’s keys and tokens. It keeps important info hidden from your code, so your bot stays safe, and makes managing secrets simple for anyone just starting out.


Packages You Need:

  • discord.js – The main library to interact with the Discord API.
  • dotenv – Loads your .env file so your bot can access secret tokens and settings.

Refer to this guide for instructions on installing packages: How to add additional JavaScript modules in Pterodactyl.


1. Create a new .env File in Your Panel

  1. Create a new file in your Panel (Tutorial: How to Create a File in Pterodactyl)
  2. Open the file in a text editor and add your secret keys and tokens in this format:

cybranceePanelFilesEnv

Content:

TOKEN=your-bot-token
PREFIX=!

Each line is a variable followed by its value.

3. Once you have added all your variables, save the file with the name .env .


2. Use .env to Run Your Discord Bot

Once your .env file is ready, you can call it using require('dotenv').config();. This is used to get your credentials from the .env file, and then you can access them with process.env.VARIABLE_NAME.

Create a file called index.js. This will be the main file that uses .env for TOKEN and PREFIX.

cybranceePanelFilesIndexJS

Content:

require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

const PREFIX = process.env.PREFIX || "!";

client.once('clientReady', () => {
    console.log(`${client.user.tag} is online!`);
});

client.on('messageCreate', message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(PREFIX)) return;

    const args = message.content.slice(PREFIX.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'ping') {
        message.channel.send('Pong!');
    }
});

client.login(process.env.TOKEN);

Once done, you can now start the bot and test.


Done

When you start your bot, seeing BOT#0000 is online! in the console means your .env file is being correctly read by index.js.

Cybrancee Panel Console

Discord Bot Hosting

Starts at $1.49

External link icon
Was this article helpful?
Please Share Your Feedback
How Can We Improve This Article?
Table of Contents
Error Details*
Cancel