Find us on social media
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:
// 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:
DISCORD_TOKEN=your_token_here
CLIENT_ID=your_client_idStep 2: Configure .gitignore
Make sure .env is never pushed to Git:
# .gitignore
.env
.env.local
.env.production
node_modules/If you already committed the token by mistake:
# 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 .envImportant: After removing from history, regenerate the token immediately.
Step 3: Token rotation
Rotate the token periodically or if you suspect a compromise:
- Go to Discord Developer Portal → your application → Bot
- Click Reset Token
- Copy the new token
- Update the
.envon your VPS:
ssh deploy@your-vps
nano /opt/bots/my-bot/.env
# Paste the new token
pm2 restart my-botStep 4: Enable 2FA on your account
If your bot is in servers with mandatory 2FA, your developer account needs 2FA:
- Discord → Settings → My Account → Enable 2FA
- Use an app like Google Authenticator or Authy
- 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:
# 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 LogStep 6: GitHub Secret Scanning
GitHub detects Discord tokens automatically. If you receive an alert:
- The token has already been revoked by Discord automatically
- Generate a new one in the Developer Portal
- 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