Mohnish.dev Logo

Mohnish.dev

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

Mohnish Vishwakarma Avatar

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.

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

But from Node.js v20.6.0+, things have changed for the better.

Now you can:

  • Use built-in support for .env files (no more dotenv)
  • Enable hot reloading using --watch (no more nodemon)

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:

EnvironmentFile 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.

Mohnish.dev Logo

Mohnish.dev

Β© 2025 Mohnish Vishwakarma. All rights reserved.

How to Set Up Environment Variables in Node.js (Without dotenv or nodemon)