Setting Up Environment Variables in Node.js (No dotenv, No nodemon)

Mohnish Vishwakarma
20 Jul 2025
Managing environment variables and hot-reloading has always been a bit messy in Node.js. We had to install third-party tools like dotenv to read .env files and nodemon to restart the server on changes.
But from Node.js v20.6.0+, things have changed for the better.
Now you can:
- Use built-in support for
.env
files (no moredotenv
) - Enable hot reloading using
--watch
(no morenodemon
)
Letβs see how to use these features in a clean way to manage environments like development
and production
.
π Project Structure
Here's a simple folder structure you can follow:
my-app/
βββ api/
β βββ index.js
βββ src/
β βββ (your other files)
βββ .env.development
βββ .env.production
βββ package.json
Step 1: Create Environment Files
.env.development
PORT=3000
DB_URI=mongodb://localhost/dev-db
.env.production
PORT=8080
DB_URI=mongodb+srv://user:pass@cluster.mongodb.net/prod-db
Step 2: Create Your Server
api/index.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`);
});
app.listen(process.env.PORT, () => {
console.log('App started');
console.log('Environment:', process.env.NODE_ENV);
console.log('Port:', process.env.PORT);
console.log('Database URI:', process.env.DB_URI);
});
Notice how we directly access process.env
β no need to use the dotenv
package!
Step 3: Add Scripts in package.json
Update your package.json:
"scripts": {
"start": "node --env-file=.env.production api/index.js",
"dev": "node --env-file=.env.development --watch api/index.js"
}
What these scripts do:
npm run start
β Runs the app in production using.env.production
npm run dev
β Runs the app in development mode, with auto-reload using the built-in--watch
flag
No more nodemon
, no more dotenv
. It's all handled natively by Node.js π
Tips for Naming .env Files
Stick to a consistent naming pattern:
Environment | File Name |
---|---|
Development | .env.development |
Production | .env.production |
Staging | .env.staging |
Testing | .env.test |
You can also use .env.local
for personal overrides (just donβt commit it).
Final Thoughts
With Node.js 20.6.0 and later, you no longer need to rely on extra packages to manage environment variables or watch your files. Using native features like --env-file
and --watch
, you can keep your setup clean, modern, and production-ready.
β¨ Try it today β and let your project breathe a little cleaner.