How to manage environment variables in Node.js

· Category: Node.js

Short answer

Use the dotenv package to load variables from a .env file into process.env, and validate required variables at startup.

Steps

  1. Install dotenv: npm install dotenv.
  2. Create a .env file with key-value pairs: PORT=3000.
  3. Load it early in your app: require('dotenv').config();.
  4. Access variables: const port = process.env.PORT || 3000;.
  5. Validate required variables and throw if any are missing.

Tips

  • Never commit .env files to version control; add them to .gitignore.
  • Use a schema validator like envalid or joi to ensure variables are the correct type.

Common issues

  • process.env values are always strings; cast numbers and booleans explicitly.
  • Variables set in the shell take precedence over .env files by default in dotenv.