Node.js Environment Variables

Here is a complete and easy-to-understand guide on Node.js Environment Variables — covering .env usage, process.env, configuration patterns, security, and best practices.


🌱 Node.js Environment Variables

Environment variables allow you to store sensitive data and configuration outside your source code.

Examples of what they store:

  • Database credentials

  • API keys

  • JWT secrets

  • Port numbers

  • Mode (development / production)

Node.js reads them using:

process.env.VARIABLE_NAME

⭐ 1. Using Environment Variables Without Any Library

Set variables temporarily:

On Linux / macOS:

PORT=5000 node app.js

On Windows CMD:

set PORT=5000 && node app.js

In your Node.js file:

console.log(process.env.PORT);

⭐ 2. Using .env File (Recommended)

Most Node.js apps use dotenv package.

Install:

npm install dotenv

Create .env file:

PORT=5000
DB_HOST=localhost
DB_USER=root
DB_PASS=12345
JWT_SECRET=mysecretkey

Load .env in app:

require("dotenv").config();

Access variables:

console.log(process.env.DB_USER);

⭐ 3. Basic Example with Express

📁 app.js


 


⭐ 4. Environment Modes (dev / prod / test)

Set environment mode:

NODE_ENV=production node app.js

Access:

console.log(process.env.NODE_ENV);

Common values:

  • development

  • production

  • test


⭐ 5. Multiple .env Files

Many apps use:

.env
.env.development
.env.production
.env.test

Load based on environment:



 


⭐ 6. Never Commit .env to Git

Add to .gitignore:

.env
.env.*

⭐ 7. Default Values

Use fallback:

const PORT = process.env.PORT ?? 3000;

⭐ 8. Type Conversion

Environment variables are strings. Convert as needed:

const PORT = Number(process.env.PORT);

Boolean conversion example:

const DEBUG = process.env.DEBUG === "true";

⭐ 9. Using Environment Variables in Scripts

In package.json:



 

For Windows users (cross-platform):

npm install cross-env


 


⭐ 10. Security Best Practices

✔ Never commit .env
✔ Use .env.example as a template
✔ Use environment variables in production (Heroku, AWS, Vercel)
✔ Encrypt secrets using Vault or Docker secrets
✔ Load secrets only at startup


⭐ 11. Environment Variable Validation

Use Joi or Zod for required variables.

Example with Joi:


 


⭐ 12. Safe Config Pattern (Recommended)

Instead of using process.env everywhere, create a config file.

📁 config.js


 

Use it:


 


⭐ 13. Using Environment Variables in Docker

Dockerfile:

ENV PORT=4000

docker-compose.yml:

environment:
- DB_HOST=localhost
- DB_USER=root

🎉 Summary

Environment variables provide:

✔ Security
✔ Clean configuration
✔ Production-ready app setup
✔ Easy portability

Use:

  • .env + dotenv for development

  • process.env directly in production

You may also like...