An environment variable is a named value that your app reads at runtime from its environment rather than from its source code. Secrets like API keys and database URLs are kept in environment variables, usually loaded from a gitignored .env file locally and set in your host's dashboard in production, so the real values never live in your code or git history.
Why not just put secrets in code
A secret written into source is in every copy of the repo forever, including its history, and if the repo is ever public it is scraped within minutes. Reading the secret from an environment variable means the code references a name, process.env.STRIPE_KEY, while the value stays outside the codebase.
The .env and .env.example pattern
Keep real values in a .env that is listed in .gitignore, so it is never committed. Commit a .env.example with the variable names and empty values, so anyone (or any AI tool) can see the shape of the config without seeing the secrets. Confirm .env is gitignored before your first commit.
Safe vs unsafe ways to handle .env
| Practice | Result |
|---|---|
| .env listed in .gitignore | Secrets stay out of git (correct) |
| .env committed to the repo | Secrets exposed in history, rotate them |
| Real values placed in .env.example | Secrets leak through the committed example |
| Server-only var, no public prefix | Value stays on the server |
What this means for AI-generated code
AI tools often create a .env with real values but forget the matching .gitignore entry, so the secrets get committed on the first push. They also inline keys directly when an integration needs one, because that is the shortest path to running code.
Common questions
How do I keep my .env file out of git?
Add a line with .env to your .gitignore before your first commit, and confirm git is not already tracking it by running git status. If it was committed earlier, removing it now is not enough: it stays in history, so rotate the secrets too.
What is the difference between .env and .env.example?
.env holds the real secret values and is gitignored, so it never leaves your machine or host. .env.example is committed and lists only the variable names with empty or placeholder values, so collaborators and AI tools can see what config is needed without seeing the secrets.
I already committed my .env file. What should I do?
Rotate every secret that was in it, because it now lives in your git history and may have been scraped. Then add .env to .gitignore and remove it from tracking. Deleting the file in a later commit does not remove it from history.
Is an environment variable enough to keep a secret private?
It keeps the secret out of your source and git history, but not out of the browser. If a client-side component reads the variable, the value is bundled and shipped to every visitor. A secret is only private if it is read and used in server code.