SecurityToken.env3 min read

Token security and best practices

Protect your token with .env files, avoid accidental commits, token rotation, 2FA and detecting compromises.


Why is token protection critical?

Your bot's token is like a master password. Anyone who has it can fully control your bot: send messages, ban users, delete channels. If it leaks, act immediately.

Step 1: Use .env files

Never hardcode the token in your source code:

javascript
// NEVER do this
client.login('MTIzNDU2Nzg5MDEyMzQ1Njc4.XXXXXX.XXXXXXX');

// Always use environment variables
require('dotenv').config();
client.login(process.env.DISCORD_TOKEN);

Create the .env file:

bash
DISCORD_TOKEN=your_token_here
CLIENT_ID=your_client_id

Step 2: Configure .gitignore

Make sure .env is never pushed to Git:

gitignore
# .gitignore
.env
.env.local
.env.production
node_modules/

If you already committed the token by mistake:

bash
# Remove from Git history
git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch .env' HEAD

# Or use BFG Repo-Cleaner (faster)
bfg --delete-files .env

Important: After removing from history, regenerate the token immediately.

Step 3: Token rotation

Rotate the token periodically or if you suspect a compromise:

  1. Go to Discord Developer Portal → your application → Bot
  2. Click Reset Token
  3. Copy the new token
  4. Update the .env on your VPS:
bash
ssh deploy@your-vps
nano /opt/bots/my-bot/.env
# Paste the new token
pm2 restart my-bot

Step 4: Enable 2FA on your account

If your bot is in servers with mandatory 2FA, your developer account needs 2FA:

  1. Discord → Settings → My Account → Enable 2FA
  2. Use an app like Google Authenticator or Authy
  3. Store backup codes in a secure location

Step 5: Detect compromised tokens

Signs your token was exposed:

  • The bot sends messages you didn't program
  • New servers appear in the bot's server list
  • Users report strange behavior
  • GitHub notifies you of an exposed secret

Immediate actions:

bash
# 1. Regenerate token NOW
# Discord Developer Portal -> Bot -> Reset Token

# 2. Update in production
ssh deploy@your-vps
cd /opt/bots/my-bot
echo 'DISCORD_TOKEN=new_token' > .env
pm2 restart my-bot

# 3. Review server audit logs
# Discord -> Server Settings -> Audit Log

Step 6: GitHub Secret Scanning

GitHub detects Discord tokens automatically. If you receive an alert:

  1. The token has already been revoked by Discord automatically
  2. Generate a new one in the Developer Portal
  3. Update your production environment

Recommendations

  • Never share the token via Discord, email or chat
  • Use GitHub Secrets for CI/CD instead of hardcoding
  • Configure GitHub Secret Scanning alerts
  • Rotate tokens every 3-6 months as a preventive practice
  • Keep 2FA active on all accounts with bot access

Was this guide helpful?