Setting Up Environment Variables in Node.js (No dotenv, No nodemon)
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
.envfiles (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.jsonStep 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-dbStep 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.productionnpm run dev– Runs the app in development mode, with auto-reload using the built-in--watchflag
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.


