Node.js Environment Variables

Managing configuration with environment variables

Access Environment Variables

const port = process.env.PORT || 3000; # access env variable
const dbUrl = process.env.DATABASE_URL;

dotenv Package

npm install dotenv # install dotenv
require('dotenv').config(); # load .env file

.env File

# .env file
PORT=3000
DATABASE_URL=mongodb://localhost/mydb
API_KEY=secret123

Set Environment Variable

export NODE_ENV=production # Linux/Mac
set NODE_ENV=production # Windows

Check Environment

if (process.env.NODE_ENV === 'production') {
    // production code
} else {
    // development code
}