π The .env File
A .env file contains your environment variables, one per line:
PORT=3000
DB_PASSWORD=mySecret123
API_KEY=abc123xyzPlace it in your project root β the same level as your
package.jsonand main JS files.No quotes needed around values, no spaces around the
=sign, and no semicolons at the end of a line.Comments start with
#:
# Database config
DB_PASSWORD=mySecret123π‘ Variants of .env Files
.envβ the default file, loaded in all environments unless a more specific one overrides it..env.localβ developer-specific overrides. Ignored in version control, so it's ideal for machine-specific settings that shouldn't apply to teammates..env.developmentβ loaded whenNODE_ENV=development..env.productionβ loaded whenNODE_ENV=production..env.testβ loaded whenNODE_ENV=test, typically during automated test runs..env.exampleβ documents which env vars the project needs, with placeholder values instead of real secrets. Safe to commit, and helpful for onboarding other developers.
βοΈ Tools like Vite and Next.js load these environment-specific files automatically based on NODE_ENV. Plain Node with dotenv doesn't do this out of the box β you'd need to point .config() at the right file yourself (see below).
π Loading .env in Your Code
Install the dotenv package:
npm install dotenvLoad it as early as possible in your entry file:
require('dotenv').config();
console.log(process.env.PORT); // 3000
console.log(process.env.DB_PASSWORD); // mySecret123Loading a Specific .env File
By default, dotenv only reads .env. To load a different file (like .env.production), pass a path option:
require('dotenv').config({ path: '.env.production' });A common pattern is to pick the file based on NODE_ENV:
require('dotenv').config({
path: `.env.${process.env.NODE_ENV || 'development'}`
});π‘ Node 20.6+ can skip dotenv entirely for the default file, using node --env-file=.env app.js.
π‘οΈ Pro Tips
Never commit
.env,.env.local, or any file with real secrets β add them to.gitignorebefore your first commit.Do commit
.env.examplewith placeholder values, so collaborators know exactly what to fill in.If a secret ever does get committed, rotate it (change the actual password/key) β removing it from a later commit doesn't erase it from Git history.