Node.js: Code Outside the Browser / Environment Variables & Configurations

What are Environment Variables?

πŸ‘€ 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 .env file (more below).

  • Swapping environments just means swapping the .env file β€” 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.env is 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=abc123xyz
  • Lives at the root of your project.

  • Node doesn't read .env files natively (in older versions) β€” you need the dotenv package to load it.

Setting It Up

npm install dotenv
require('dotenv').config();

console.log(process.env.DB_PASSWORD);
// 'mySecret123'
  • .config() reads the .env file and loads every key into process.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.