---
title: "Keep your Discord bot token safe: .env, .gitignore and what to do if it leaks | StreetHosting"
description: "Store your Discord bot token in an environment variable with a .env file, protect it with .gitignore and reset it in the Developer Portal if it leaks."
url: "https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables"
type: "page"
language: "en-US"
---

Discord Bots · 8 min · Beginner

Published on Nov 13, 2026 · Updated on Nov 13, 2026

# How to keep your Discord bot token safe with environment variables

The bot token is its password. Whoever has the token controls the bot. Learn how to move the token out of your code with a .env file, keep it off GitHub and what to do when it leaks.

By [Equipe StreetHosting](https://streethosting.com.br/en/autores#equipe-streethosting) · StreetHosting infrastructure and support team

[Security and hardening](https://streethosting.com.br/en/guides/topics/security) [Deploying and running apps](https://streethosting.com.br/en/guides/topics/deploy)

Summarize with:

[](https://chat.openai.com/?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "ChatGPT") [](https://claude.ai/new?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Claude") [](https://www.google.com/search?udm=50&aep=11&q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Google AI Mode") [](https://x.com/i/grok?text=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Grok") [](https://www.perplexity.ai/search/new?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Perplexity")

Share:

[](https://x.com/intent/tweet?text=Keep%20your%20Discord%20bot%20token%20safe%3A%20.env%2C%20.gitignore%20and%20what%20to%20do%20if%20it%20leaks&url=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables "Share on X") [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables "Share on Facebook") [](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables "Share on LinkedIn") [](https://wa.me/?text=Keep%20your%20Discord%20bot%20token%20safe%3A%20.env%2C%20.gitignore%20and%20what%20to%20do%20if%20it%20leaks%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fdiscord-bots%2Fdiscord-bot-token-environment-variables "Share on WhatsApp")

For agents: Copy as Markdown [.md](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables.md)

In this guide 7 sections

* [Why the token must stay out of your code](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#por-que-proteger)
* [Create the .env file](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#arquivo-env)
* [Read the token in Node.js](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-nodejs)
* [Read the token in Python](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-python)
* [Protect it with .gitignore](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#gitignore)
* [What to do if the token leaks](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#token-vazou)
* [Variables on your hosting](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#onde-rodar)

Quick answer

The bot token is its password: whoever has it controls the bot. Never write the token in your code. Save it in a `.env` file, read it with `process.env.DISCORD_TOKEN` in Node.js or `os.getenv("DISCORD_TOKEN")` in Python, and add `.env` to `.gitignore` before the first commit. If the token leaks, click Reset Token on the Bot tab of the Developer Portal and swap the value on your server.

## Why the token must stay out of your code[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#por-que-proteger)

The token is the credential your program uses to sign in to Discord as the bot. There is no second factor and no confirmation: whoever presents the token is the bot. With it, someone else can send messages, ban members, delete channels and use any permission your bot has in every server it belongs to.

The classic mistake is writing the token straight into the main file, like `client.login("MTIz...")`, and then pushing the project to GitHub. Even a private repository carries risk, because the code ends up in backups, in a colleague's fork and in screenshots. Separating the secret from the code solves this: the code can be public, and the token lives only on the machine where the bot runs.

That separation has a name, environment variable. It is a value the system hands to the program when it starts, without being written in any project file that goes to Git. The same bot runs on your computer and on the server, each with its own value.

## Create the .env file[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#arquivo-env)

The simplest way to define variables in development is a text file called `.env` in the project root, one variable per line, in the format `NAME=value`. No spaces around the equals sign and, usually, no quotes.

`DISCORD_TOKEN=cole_o_token_do_bot_aqui CLIENT_ID=123456789012345678 GUILD_ID=123456789012345678`

To get the token, open the Discord Developer Portal, pick your application, go to the **Bot** tab and click **Reset Token**. The portal shows the full value only once. Copy it right away and paste it into the `.env`. If you close the page without copying, just reset it again. The old token stops working the same instant, so resetting while the bot is online drops its connection until you restart it with the new value.

Only the token is a secret. The application ID and the server ID show up all over Discord and give no access to anything, but it is common to keep them in the same file so you do not scatter numbers through the code.

Also create a `.env.example` file with the same names and fake values, for example `DISCORD_TOKEN=paste_the_token_here`. That one does go to Git. Anyone who downloads the project, including you six months from now, knows exactly which variables to fill in.

## Read the token in Node.js[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-nodejs)

There are two ways, and both make the value available in `process.env`. The first uses the dotenv package, which works on any Node version:

`npm install dotenv`

`` // index.js (ESM). The first line loads the .env import "dotenv/config"; import { Client, Events, GatewayIntentBits } from "discord.js"; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.once(Events.ClientReady, () => { console.log(`Online como ${client.user.tag}`); }); if (!process.env.DISCORD_TOKEN) { console.error("DISCORD_TOKEN não está definido. Confira o arquivo .env."); process.exit(1); } client.login(process.env.DISCORD_TOKEN); ``

In a CommonJS project, replace the import with `require("dotenv").config();` on the first line of the file. Order matters: the `.env` must be loaded before any module of yours that reads `process.env`.

The second way needs no package. From Node 20.6 on, Node itself reads the file if you ask for it on the command line:

`node --env-file=.env index.js`

In that case the code needs no extra import. So you do not have to memorize the command, keep it in `package.json` as a script: `"start": "node --env-file=.env index.js"`. If the file does not exist, Node stops with a clear error, which is good: better to fail at startup than to run without a token.

Never print the token to a log, not even to debug. A forgotten `console.log(process.env)` sends the secret to the log file, to the terminal and, if you paste the error in a forum, to the whole internet.

## Read the token in Python[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-python)

In Python the equivalent is the python-dotenv package. It reads the `.env` and puts its lines into the process environment:

`pip install python-dotenv discord.py`

`import os import discord from dotenv import load_dotenv load_dotenv() # reads the .env file in the current folder token = os.getenv("DISCORD_TOKEN") if not token: raise SystemExit("DISCORD_TOKEN não está definido. Confira o arquivo .env.") intents = discord.Intents.default() client = discord.Client(intents=intents) @client.event async def on_ready(): print(f"Online como {client.user}") client.run(token)`

`load_dotenv()` looks for the file starting from the folder the program was launched in. If the bot runs as a service and cannot find the token, the most common cause is a different working folder. In that case pass the full path: `load_dotenv("/caminho/do/bot/.env")`. The step by step for keeping the process alive is in [hosting a Python Discord bot 24/7](https://streethosting.com.br/en/guides/discord-bots/host-python-discord-bot).

## Protect it with .gitignore[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#gitignore)

The `.env` file fixes the code, but it only protects the token as long as it does not enter Git. The order of the steps matters more than it seems: create the `.gitignore` before the first commit.

1. Create the `.gitignore` file in the project root with the lines below.
2. Only then run `git init` and the first `git add`.
3. Before pushing, run `git status` and confirm the `.env` does not appear in the list of files to commit.

`# .gitignore .env .env.* !.env.example node_modules/ __pycache__/ venv/`

The `.env.*` pattern covers variations like `.env.local` and `.env.production`, and the line with the exclamation mark makes an exception for `.env.example`, which should go into the repository.

If the project already has commits and the `.env` went in by mistake, adding the line to `.gitignore` is not enough, because Git keeps tracking a file it already knows. You have to take the file out of the index without deleting it from disk:

`git rm --cached .env git commit -m "Remove .env do controle de versão"`

That command stops the file from being sent from now on, but the token stays in the history of the old commits. If any of them already went to GitHub, treat the token as leaked and follow the next section.

## What to do if the token leaks[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#token-vazou)

Consider the token leaked whenever it shows up in a repository (even a private one and even for a few minutes), in a screenshot, in a log pasted in a forum or in a conversation. The steps, in order:

1. **Reset the token now.** In the Developer Portal, open the application, go to the **Bot** tab and click **Reset Token**. The old value stops being valid at the same instant, and that is what actually stops the abuse.
2. **Update the .env and restart the bot.** Paste the new token and restart the process. If you use PM2, remember it keeps the environment from the first start: use `pm2 restart nome --update-env`.
3. **Check what happened while the token was exposed.** Review the audit log of your servers, look for channels, roles or webhooks you did not create and remove anything strange.
4. **Clean the history, if it is public.** After the reset, the token in the history no longer works, so cleaning becomes hygiene. Tools like `git filter-repo` rewrite the history, but they require a force push and anyone with an old clone keeps the copy.

There is a safety net. GitHub scans public repositories for secrets, and Discord is one of the partners that receive those alerts: a bot token found in a public repository is usually invalidated by Discord itself, and the application owner gets a notice. If your bot went offline for no reason and the login failed with an invalid token, that may be why. Still, do not treat the scan as a plan: it only covers public GitHub repositories, it does not catch leaks in screenshots, logs or forums and it does not stop someone from copying the token in the minutes before the alert.

If the bot went down and you do not know why, the checklist for a [Discord bot that is offline or not responding](https://streethosting.com.br/en/guides/discord-bots/discord-bot-offline-not-responding) helps tell an invalid token from a stopped process.

* Token reset in the Developer Portal, on the Bot tab
* New token saved in the server's .env and bot restarted
* Audit log of your servers reviewed
* .env listed in .gitignore and out of the Git index
* No token in screenshots, logs or shared error messages

## Variables on your hosting[](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#onde-rodar)

The principle holds wherever the bot runs: the secret stays on the server, not in the repository. On your computer that is the `.env` file. In production you have two options. You can create the `.env` directly on the server, with permissions restricted to your user, or you can define the variables in the service's own environment, when the panel or the process manager offers that field.

* **On a VPS:** with root access and a full Linux, you can keep the token in an environment file read by systemd or PM2, with `chmod 600` so only your user can read it. The full deploy is in [deploying a Discord bot with Node.js and PM2](https://streethosting.com.br/en/guides/discord-bots/deploy-discord-bot-pm2).
* **On bot hosting:** the [StreetHosting bot hosting](https://streethosting.com.br/en/bots) plans run in containers with a panel for Node.js and Python, from R$ 9.99 per month on Discord Essential. Upload the bot files without the `.env` from your computer and set the token only on the server, by creating the `.env` there or by using a variables field, if the panel offers one.

In either case, never put the token in the repository the server downloads. For the big picture on keeping a bot up with automatic restarts and logs, see [24/7 Discord bot hosting](https://streethosting.com.br/en/guides/discord-bots/discord-bot-hosting-24-7).

In this guide

* [Why the token must stay out of your code](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#por-que-proteger)
* [Create the .env file](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#arquivo-env)
* [Read the token in Node.js](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-nodejs)
* [Read the token in Python](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#ler-python)
* [Protect it with .gitignore](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#gitignore)
* [What to do if the token leaks](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#token-vazou)
* [Variables on your hosting](https://streethosting.com.br/en/guides/discord-bots/discord-bot-token-environment-variables#onde-rodar)

## Frequently asked questions

Where is the bot token in Discord?

In the Discord Developer Portal, inside your application, on the Bot tab. The full token is only shown once, at the moment you click Reset Token. After that the portal does not show the value again, so copy it and store it in your .env right away.

Does Discord invalidate a token that leaked on GitHub by itself?

In many cases, yes. Discord is a partner of GitHub's secret scanning: when a bot token shows up in a public repository, Discord gets the alert, usually invalidates the token and notifies the owner. Do not count on it as protection, because the scan only covers public repositories and the token may have been copied before. Reset it yourself.

I deleted the token from the code and made another commit. Is it safe?

No. The token is still in the Git history, and anyone who clones the repository can read old commits. The only step that fixes it is resetting the token in the Developer Portal. Cleaning the history is a complement, never the fix.

What is the difference between dotenv and node --env-file?

dotenv is a package you install with npm and it works on any Node version. node --env-file=.env is a feature of Node itself, available from version 20.6, that removes the dependency. The result is the same: the lines in .env become properties of process.env.

Can I commit a .env.example file?

You can, and it is good practice. The .env.example shows which variables the project needs, with fake values such as DISCORD\_TOKEN=paste\_the\_token\_here. Whoever clones the project copies the file to .env and fills it in. The real .env stays out of Git.

Next step

See bot plans

24/7 Discord bots with fast activation and support in Portuguese.

[See bot plans](https://streethosting.com.br/en/bots)

## Related guides

[Discord bots Beginner How to create your first Discord bot from scratch Never built a bot and not sure where to start? Here is the path from zero: create the application, get the token, invite the bot with the right permissions, and make it reply. 3 min Read guide](https://streethosting.com.br/en/guides/discord-bots/create-discord-bot) [Discord bots Beginner 24/7 Discord bot hosting in Brazil Discord bot hosting 24/7 combines a process manager with automatic restart, a token kept out of your code, logs and a server in Brazil for low latency to the API and your players. 6 min Read guide](https://streethosting.com.br/en/guides/discord-bots/discord-bot-hosting-24-7) [Discord bots Intermediate Deploy a Discord bot with Node.js and PM2: env vars and auto restart PM2 is a popular Node process manager for Discord bots because it restarts after a crash, survives reboots when paired with the startup hook and centralizes basic logs without standing up a whole Kubernetes cluster. This guide covers the ecosystem file, env vars for the token and how it fits hosting in Brazil. 4 min Read guide](https://streethosting.com.br/en/guides/discord-bots/deploy-discord-bot-pm2)

[← Back to the Guide Center](https://streethosting.com.br/en/guides)
