Node.js Basics
Node.js Environment Variables and dotenv
Environment variables keep configuration and secrets out of the source code. Node reads them from process.env, and in development a .env file loaded by dotenv — or Node’s own --env-file flag — populates them.
What is Environment Variables and dotenv in Node.js?
Environment variables keep configuration and secrets out of the source code. Node reads them from process.env, and in development a .env file loaded by dotenv — or Node’s own --env-file flag — populates them.
Environment Variables and dotenv example
PORT=5000
MONGODB_URI=mongodb://127.0.0.1:27017/jobs
JWT_SECRET=change-me-in-production
NODE_ENV=developmentHow this works
Failing fast on a missing variable at startup is far better than discovering it when the first request tries to sign a token.
Loading and validating
import 'dotenv/config'; // or: node --env-file=.env src/index.js
const required = ['MONGODB_URI', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required env var: ${key}`);
process.exit(1);
}
}
export const config = {
port: Number(process.env.PORT ?? 3000),
mongoUri: process.env.MONGODB_URI,
jwtSecret: process.env.JWT_SECRET,
};Key points to remember
- Add .env to .gitignore and commit a .env.example listing the names only.
- Every environment variable is a string — convert numbers and booleans explicitly.
- In production, set variables through the host or process manager rather than a file.
Common mistakes with Environment Variables and dotenv
- Committing .env with real credentials — assume anything pushed to a public repo is compromised.
- Loading dotenv after the code that reads process.env.
Node.js Environment Variables and dotenv— Interview Questions & FAQs
Do I still need dotenv?+
Not necessarily — Node 20.6 and later support --env-file=.env natively. dotenv remains useful for older versions and for its expansion and multi-file features.
