π Introduction to Environment Variables
Environment variables are key-value pairs used to configure your application from outside your source code.
Why Use Them?
π Security β hide sensitive data like API keys and database passwords.
βοΈ Flexibility β set different values for development, testing, and production without touching code.
π§Ό Clean code β avoid hardcoding secrets and settings directly into files.
π Portability β the same codebase runs correctly across different machines and deployment environments.
Example: Hardcoded vs Environment Variable
β Bad practice (hardcoding):
const dbPassword = "mySecret123";Anyone with access to the code sees the password.
Changing environments (dev β production) means editing and redeploying code.
β Better with environment variables:
const dbPassword = process.env.DB_PASSWORD;The actual value lives outside the code, in a
.envfile (more below).Swapping environments just means swapping the
.envfile β no code changes.
π§ Using process.env in Node.js
process.env is a built-in Node.js object that gives access to all environment variables currently set on the system.
console.log('Your system username is:', process.env.USERNAME);Every value on
process.envis always a string β even numbers or booleans need manual conversion (Number(process.env.PORT)).If a variable isn't set, accessing it returns
undefined, not an error β good to guard against with a default value.
π The .env File
A .env file stores environment variables locally, outside your source code, in simple KEY=value pairs.
DB_PASSWORD=mySecret123
PORT=3000
API_KEY=abc123xyzLives at the root of your project.
Node doesn't read
.envfiles natively (in older versions) β you need thedotenvpackage to load it.
Setting It Up
npm install dotenvrequire('dotenv').config();
console.log(process.env.DB_PASSWORD);
// 'mySecret123'.config()reads the.envfile and loads every key intoprocess.env.Call this as early as possible β ideally the very first line of your entry file β so every other file that runs afterward can access the variables.
π‘ Node 20.6+ can load .env files natively with node --env-file=.env app.js, without needing dotenv at all.