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
- Install dotenv:
npm install dotenv. - Create a
.envfile with key-value pairs:PORT=3000. - Load it early in your app:
require('dotenv').config();. - Access variables:
const port = process.env.PORT || 3000;. - Validate required variables and throw if any are missing.
Tips
- Never commit
.envfiles to version control; add them to.gitignore. - Use a schema validator like
envalidorjoito ensure variables are the correct type.
Common issues
process.envvalues are always strings; cast numbers and booleans explicitly.- Variables set in the shell take precedence over
.envfiles by default in dotenv.