What is a .env file, and when should you stop using one?
By Maria Otworowska,
What it looks like
PORT=3000
LOG_LEVEL=debug
DATABASE_URL=postgres://localhost/myapp
STRIPE_KEY=sk_test_...The idea comes from the Twelve-Factor App, which stores config in environment variables and asks for strict separation of config from code. Its test: could the code be made open source at any moment without exposing any credentials? A .env file is a convenient way to set those variables on your own machine.
How each tool loads it
| Tool | How | Existing variables win? |
|---|---|---|
| dotenv (Node) | require("dotenv").config() | Yes, unless override: true |
| Node.js | node --env-file=.env app.js, added in v20.6.0, stable since v24.10.0 and v22.21.0 | Yes |
| python-dotenv | load_dotenv() | Yes, unless override=True |
| Next.js | Automatic: .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV), .env (.env.local is skipped when NODE_ENV=test) | Yes, process.env comes first |
| Vite | Automatic: .env, .env.local, .env.[mode], .env.[mode].local | Yes |
That last column matters: by default, a variable already set in the environment beats the file, so a runner that sets variables for a command usually works without code changes. Check for override settings, and for code or flags like --env-file that expect the file to exist.
The browser trap
Two prefixes send values to the browser. Next.js inlines NEXT_PUBLIC_ variables into the JavaScript it ships, and Vite exposes VITE_ variables to client code. Vite's docs say those variables should not contain sensitive information such as API keys. Anything with those prefixes is public, whatever file it came from.
Should you commit it?
Not a plain-text one. dotenv's README answers "Should I commit my .env file?" with "No.", making an exception for files encrypted with dotenvx, and the Next.js docs say you almost never want to commit these files. Commit a .env.example with the names and placeholder values so others know what to set. If you already committed one, see I committed my .env file to GitHub.
When to stop keeping keys in it
For ports, log levels and local URLs, a .env is fine. For real API keys, the file has become a liability:
- AI coding agents read project files without asking, and some, like Gemini CLI, load .env themselves. See can Claude Code read your .env file?
- It's copied into backups, zips, screenshots and the next project you start by copying this one.
- .gitignore keeps it out of git only until someone runs git add -f or the rule gets lost.
You don't have to give up environment variables, just the file that holds the keys. Keep the keys in the Keychain, a password manager or a secrets manager and set them for the command, with a runner that masks them when your coding agent reads the output (accio does this for Claude Code and Codex, and for other agents that set FIDELIUS_MASK=1):
$ accio myapp npm run dev