agyanadda@gmail.com

Node.js Environment Variables and Config

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 24 of 30

Settings such as the port, database password or API keys should not be written in your code. Put them in environment variables.

Reading variables

process.env.PORT — always a string (or undefined). Convert numbers with Number() and give defaults: process.env.PORT ?? 3000.

.env files

Put local settings in a .env file:

PORT=3000 DB_PASSWORD=secret

Load it with either:

  • node --env-file=.env app.js (built into newer Node versions)
  • the dotenv package: import 'dotenv/config' at the top of your entry file

Rules

  • Add .env to .gitignore — never commit secrets
  • Commit a .env.example with the variable names only
  • On the server, set real values in the hosting panel or a server .env
  • Use NODE_ENV=production in production — many libraries run faster and show fewer details

A config module

Read and check all variables in one config.js file, and fail fast at startup if a required one is missing.

Example

Example — Central config with checks JavaScript
// .env  (not committed)
// PORT=4000
// NODE_ENV=development
// DATABASE_URL=mysql://root:secret@localhost/shop
// JWT_SECRET=change-me-to-a-long-random-string

// config.js
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
  if (!process.env[key]) {
    console.error(`Missing environment variable: ${key}`);
    process.exit(1);
  }
}

export const config = {
  port: Number(process.env.PORT ?? 3000),
  isProduction: process.env.NODE_ENV === 'production',
  databaseUrl: process.env.DATABASE_URL,
  jwtSecret: process.env.JWT_SECRET,
};

// Run:  node --env-file=.env app.js

The app starts on port 4000 with the values from .env. If JWT_SECRET is missing it stops immediately with a clear message instead of failing later.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What type is every value in process.env?

Exercise 2 True / False

You should commit your .env file so teammates get the passwords.

Exercise 3 Fill in the Blank

Load a .env file without packages: node --env-___=.env app.js

Frequently Asked Questions

Both load .env files. --env-file needs no package but requires a newer Node version. dotenv works on all versions and has extra options. Either is fine.