Node.js Environment Variables — Configuration Management

Manage configuration with environment variables in Node.js: dotenv, validation, types, and twelve-factor app principles.

Node.js Beginner 📖 6 min

Using dotenv

npm install dotenv

// At the top of your entry file
require('dotenv').config();

// .env file
PORT=3000
DATABASE_URL=mongodb://localhost:27017/myapp
JWT_SECRET=your-secret-key
NODE_ENV=development

// Access variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;

Validating Environment Variables

const required = ['DATABASE_URL', 'JWT_SECRET', 'PORT'];

for (const key of required) {
  if (!process.env[key]) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
}

// Or use envalid
const { cleanEnv, str, port } = require('envalid');

module.exports = cleanEnv(process.env, {
  DATABASE_URL: str(),
  JWT_SECRET: str(),
  PORT: port({ default: 3000 }),
  NODE_ENV: str({ choices: ['development', 'production', 'test'] })
});

Best Practices

  • Never commit .env files to git
  • Use .env.example to document required variables
  • Provide defaults for non-critical variables
  • Use different .env files per environment

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →