Skip to main content
Practice Problems

How to work with environment variables in Node.js?

Environment Variables in Node.js

Environment variables are key-value pairs available to a process at runtime, used to configure applications without hardcoding secrets, URLs, or settings into source code.


Accessing Environment Variables

js
// process.env contains all environment variables console.log(process.env.NODE_ENV); // 'production', 'development', 'test' console.log(process.env.PORT); // '3000' console.log(process.env.DB_URL); // 'postgresql://...'

All process.env values are strings — convert if needed:

js
const port = parseInt(process.env.PORT || '3000', 10); const debug = process.env.DEBUG === 'true';

Setting Variables

In the terminal

bash
# Inline (one command) PORT=4000 node server.js # Export for the session export NODE_ENV=production node server.js # Windows (cmd) set NODE_ENV=production && node server.js # Windows (PowerShell) $env:NODE_ENV="production"; node server.js

.env Files with dotenv

For local development, use a .env file with the dotenv package:

bash
npm install dotenv
ini
# .env — NEVER commit this file! PORT=3000 NODE_ENV=development DATABASE_URL=postgresql://user:password@localhost:5432/mydb JWT_SECRET=super-secret-key OPENAI_API_KEY=sk-...
js
// Load at the very top of your entry file require('dotenv').config(); // or import 'dotenv/config'; console.log(process.env.DATABASE_URL); // works!

Multiple .env Files

bash
.env # default (shared non-secrets) .env.local # local overrides (gitignored) .env.development # development-specific .env.production # production-specific .env.test # test-specific
js
dotenv.config({ path: `.env.${process.env.NODE_ENV}` });

Validation with Joi / Zod

Always validate required env vars at startup:

js
const { z } = require('zod'); const envSchema = z.object({ NODE_ENV: z.enum(['development', 'production', 'test']), PORT: z.string().transform(Number).default('3000'), DATABASE_URL: z.string().url(), JWT_SECRET: z.string().min(32), }); const env = envSchema.parse(process.env); // Throws at startup if required vars are missing ✅

Security Best Practices

bash
# .gitignore — always exclude: .env .env.local .env.*.local
  1. Never commit .env files to version control
  2. Never log process.env (may expose secrets)
  3. Use a secrets manager in production (AWS Secrets Manager, Vault, etc.)
  4. Provide a .env.example with placeholder values for onboarding
ini
# .env.example — safe to commit, no real values PORT=3000 NODE_ENV=development DATABASE_URL=postgresql://user:password@localhost:5432/dbname JWT_SECRET=your-secret-here

Node.js 20.6+ Built-in .env Support

bash
# No dotenv needed in Node.js 20.6+! node --env-file=.env server.js

Summary

Environment variables keep configuration out of code. Use process.env to read them, dotenv to load .env files locally, always validate required vars at startup, and never commit secrets to your repository.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems