Node.js Environment Variables: process.env, .env Files and Configs
The same test suite usually runs against several environments, such as a developer’s laptop, staging and production smoke checks, each with its own URL, users and API keys. Hard-coding those values means editing code for every run and, worse, committing passwords to Git. Environment variables solve both problems: settings live outside the code and are read at runtime through process.env. In this lesson you will read and set environment variables on every OS, load them from .env files with Node.js’s built-in --env-file flag, add defaults and validation, and build a config module that picks the right environment for a test run.
📖 What You’ll Learn: what environment variables are, process.env, setting variables in bash, PowerShell and cmd, why every value is a string, defaults with ??, required variables and validation, .env files with –env-file and process.loadEnvFile(), .env.example, NODE_ENV and per-environment configs, keeping secrets out of Git and logs, and environment variables in CI pipelines.
🌍 What Are Environment Variables?
Definition: an environment variable is a named text value that the operating system passes to every program it starts. Node.js exposes them as properties of the object process.env.
Your system already has many, such as PATH (where to find programs) and HOME or USERPROFILE (your user folder). You add your own for settings such as BASE_URL or API_TOKEN.
📄 env.js
console.log(typeof process.env);
console.log("PATH is set:", Boolean(process.env.PATH));
console.log("BASE_URL:", process.env.BASE_URL); // not set yet -> undefined
⌨️ Terminal
node env.js
🖥️ Output
object
PATH is set: true
BASE_URL: undefined
- Names are conventionally
UPPER_SNAKE_CASE. - A variable that is not set is
undefined, not an error. - A program sees the variables that existed when it started; changing them in another terminal later has no effect.
⌨️ Setting Environment Variables
The syntax depends on your shell. Each line runs app.js with BASE_URL set:
| Shell | For one command | For the rest of the terminal session |
|---|---|---|
| bash / zsh (macOS, Linux, Git Bash) | BASE_URL=https://staging.example.com node app.js | export BASE_URL=https://staging.example.com |
| PowerShell (Windows) | $env:BASE_URL="https://staging.example.com"; node app.js | $env:BASE_URL="https://staging.example.com" |
| Command Prompt (cmd) | set BASE_URL=https://staging.example.com&& node app.js | set BASE_URL=https://staging.example.com |
📄 app.js
const baseURL = process.env.BASE_URL;
const browser = process.env.BROWSER;
console.log(`Running ${browser} tests against ${baseURL}`);
⌨️ Terminal
BASE_URL=https://staging.example.com BROWSER=firefox node app.js
🖥️ Output
Running firefox tests against https://staging.example.com
💡 Tip: The npm package cross-env lets one npm script set variables on every OS: "test:staging": "cross-env BASE_URL=https://staging.example.com playwright test".
🔤 Every Value Is a String
Environment variables are always text. "false" is a non-empty string, so it is truthy, and "3" + 1 is "31". Convert values explicitly:
📄 types.js
console.log(typeof process.env.RETRIES, process.env.RETRIES + 1); // string concatenation!
console.log("HEADLESS truthy?", Boolean(process.env.HEADLESS)); // "false" is truthy!
const retries = Number(process.env.RETRIES);
const headless = process.env.HEADLESS === "true";
const browsers = process.env.BROWSERS.split(",").map((b) => b.trim());
console.log(retries + 1, headless, browsers);
⌨️ Terminal
RETRIES=3 HEADLESS=false BROWSERS="chromium, firefox" node types.js
🖥️ Output
string 31
HEADLESS truthy? true
4 false [ 'chromium', 'firefox' ]
🛡️ Defaults and Required Variables
Give optional settings a default with ?? (it applies only when the value is undefined or null). Fail fast, with a clear message, when a required setting is missing, instead of letting a test fail later with “Cannot read properties of undefined”:
📄 config.js
function required(name) {
const value = process.env[name];
if (value === undefined || value === "") {
throw new Error(`Missing required environment variable ${name}. Add it to your .env file or CI secrets.`);
}
return value;
}
const config = {
baseURL: process.env.BASE_URL ?? "http://localhost:3000",
retries: Number(process.env.RETRIES ?? 0),
apiToken: required("API_TOKEN"),
};
console.log(config);
⌨️ Terminal
node config.js
🖥️ Output
/home/you/js-course/config.js:4
throw new Error(`Missing required environment variable ${name}. Add it to your .env file or CI secrets.`);
^
Error: Missing required environment variable API_TOKEN. Add it to your .env file or CI secrets.
at required (/home/you/js-course/config.js:4:11)
at Object.<anonymous> (/home/you/js-course/config.js:12:13)
Node.js v26.13.0
Run it again with the token set and it starts normally, using the defaults for the rest:
📄 config.js
function required(name) {
const value = process.env[name];
if (value === undefined || value === "") {
throw new Error(`Missing required environment variable ${name}. Add it to your .env file or CI secrets.`);
}
return value;
}
const config = {
baseURL: process.env.BASE_URL ?? "http://localhost:3000",
retries: Number(process.env.RETRIES ?? 0),
apiToken: required("API_TOKEN"),
};
console.log({ ...config, apiToken: config.apiToken.slice(0, 4) + "****" });
⌨️ Terminal
API_TOKEN=test-9f8e7d6c node config.js
🖥️ Output
{ baseURL: 'http://localhost:3000', retries: 0, apiToken: 'test****' }
⚠️ Watch out: Never print secrets in full. Logs end up in CI output, bug reports and screenshots. Mask them, as the example does, or leave them out of logs completely.
📄 .env Files with –env-file
Typing many variables before every command is tedious. A .env file keeps them in one place, one NAME=value per line. Node.js reads it natively with the --env-file flag (Node.js 20.6 and later), so the dotenv package is no longer required:
📄 .env
# staging settings for local test runs
BASE_URL=https://staging.example.com
TEST_USER=tester@sqatools.in
RETRIES=2
GREETING="Hello from .env"
📄 app.js
console.log("BASE_URL:", process.env.BASE_URL);
console.log("USERNAME:", process.env.TEST_USER);
console.log("RETRIES:", Number(process.env.RETRIES));
console.log("GREETING:", process.env.GREETING);
⌨️ Terminal
node --env-file=.env app.js
🖥️ Output
BASE_URL: https://staging.example.com
USERNAME: tester@sqatools.in
RETRIES: 2
GREETING: Hello from .env
- Lines starting with
#are comments; quotes around a value are removed. - Variables already set in the shell take priority over the file.
--env-file-if-exists=.envdoes not fail when the file is missing, which is useful when CI provides real variables instead.- Inside code,
process.loadEnvFile(".env")loads a file at runtime.
📄 .env.staging
BASE_URL=https://staging.example.com
ADMIN_EMAIL=admin@sqatools.in
📄 load.js
process.loadEnvFile(".env.staging"); // load at runtime instead of with a flag
console.log(process.env.BASE_URL, process.env.ADMIN_EMAIL);
⌨️ Terminal
node load.js
🖥️ Output
https://staging.example.com admin@sqatools.in
.env must not be committed
A .env file usually contains passwords and tokens. Add it to .gitignore and commit a .env.example instead, with every variable name and harmless sample values, so teammates know what to fill in:
📄 .env.example
# .env.example - copy to .env and fill in real values
BASE_URL=https://staging.example.com
TEST_USER=
TEST_PASSWORD=
API_TOKEN=
📄 .gitignore
node_modules/
.env
.env.*
!.env.example
🏷️ NODE_ENV and Per-Environment Configs
A common pattern is one variable that names the environment (often TEST_ENV, or NODE_ENV for apps) and a config module that holds the non-secret settings for each one. Secrets still come from environment variables:
📄 config.js
const environments = {
local: { baseURL: "http://localhost:3000", apiURL: "http://localhost:4000", workers: 1 },
staging: { baseURL: "https://staging.example.com", apiURL: "https://api.staging.example.com", workers: 4 },
prod: { baseURL: "https://www.example.com", apiURL: "https://api.example.com", workers: 2 },
};
function loadConfig() {
const name = process.env.TEST_ENV ?? "local";
const env = environments[name];
if (!env) throw new Error(`Unknown TEST_ENV "${name}". Use one of: ${Object.keys(environments).join(", ")}`);
return { name, ...env, password: process.env.TEST_PASSWORD ? "(set)" : "(missing)" };
}
console.log(loadConfig());
⌨️ Terminal
TEST_ENV=staging TEST_PASSWORD=S3cret! node config.js
🖥️ Output
{
name: 'staging',
baseURL: 'https://staging.example.com',
apiURL: 'https://api.staging.example.com',
workers: 4,
password: '(set)'
}
| Put in a config file (committed) | Put in environment variables (not committed) |
|---|---|
| URLs, timeouts, worker counts, feature flags | Passwords, API tokens, keys, connection strings |
| Values that are the same for everyone | Values that differ per person or machine |
🧪 Tester Scenario: Environment Variables in Playwright and CI
Playwright’s config is plain JavaScript or TypeScript, so it reads process.env directly:
📄 playwright.config.ts
// playwright.config.ts
import { defineConfig } from "@playwright/test";
export default defineConfig({
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 2 : undefined,
use: {
baseURL: process.env.BASE_URL ?? "http://localhost:3000",
},
});
CI services (GitHub Actions, GitLab, Jenkins, Azure DevOps) set CI=true automatically and let you store secrets in their settings, then expose them as environment variables to the job:
📄 GitHub Actions
# .github/workflows/tests.yml (excerpt)
- run: npx playwright test
env:
BASE_URL: https://staging.example.com
TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}
Locally the same tests read a git-ignored .env; in CI they read the secrets store. The test code is identical in both places.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Print a greeting using the environment variable TESTER_NAME, or “guest” when it is not set.
Show answer
📄 practice1.js
const name = process.env.TESTER_NAME ?? "guest";
console.log(`Hello, ${name}!`);🖥️ Output
Hello, Asha!Q2. Read TIMEOUT_MS as a number with a default of 30000, and throw an error if it is set but is not a positive number.
Show answer
📄 practice2.js
const raw = process.env.TIMEOUT_MS;
const timeout = raw === undefined ? 30000 : Number(raw);
if (!Number.isFinite(timeout) || timeout <= 0) {
throw new Error(`TIMEOUT_MS must be a positive number, got "${raw}"`);
}
console.log("timeout:", timeout);🖥️ Output
timeout: 45000Q3. Convert HEADLESS to a real boolean so that “true”, “1” and “yes” mean true and anything else means false.
Show answer
📄 practice3.js
const toBool = (v) => ["true", "1", "yes"].includes(String(v).toLowerCase());
console.log(toBool(process.env.HEADLESS), toBool("false"), toBool(undefined), toBool("YES"));🖥️ Output
true false false trueQ4. Create a .env file with BASE_URL and API_KEY, load it with --env-file and print the URL and the key masked as its first 3 characters plus ***.
Show answer
📄 .env
BASE_URL=https://qa.example.com
API_KEY=key-12345
📄 practice4.js
console.log(process.env.BASE_URL);
console.log(process.env.API_KEY.slice(0, 3) + "***");🖥️ Output
https://qa.example.com
key***Q5. Write checkEnv(names) that reports all missing variables at once instead of failing on the first one.
Show answer
📄 practice5.js
function checkEnv(names) {
const missing = names.filter((n) => !process.env[n]);
if (missing.length) throw new Error(`Missing environment variables: ${missing.join(", ")}`);
}
try {
checkEnv(["BASE_URL", "TEST_USER", "TEST_PASSWORD"]);
} catch (e) {
console.log(e.message);
}🖥️ Output
Missing environment variables: TEST_USER, TEST_PASSWORDQ6. A teammate committed .env with a real API token. What should you do?
Show answer
Treat the token as leaked: revoke or rotate it in the service immediately (removing the file does not remove it from Git history). Then remove the file from the repository (git rm --cached .env), add .env to .gitignore, commit a .env.example, and store the new token in a password manager or the CI secrets store.
🧠 MCQ Quiz: Environment Variables
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- How do you read an environment variable named BASE_URL in Node.js?Answer: process.env.BASE_URL. All variables are properties of process.env.
- What type are environment variable values?Answer: Always strings. Convert with Number() or a comparison such as === “true”.
- What does an unset variable return?Answer: undefined. Use ?? to apply a default.
- Why is
if (process.env.HEADLESS)wrong for HEADLESS=false?Answer: “false” is a non-empty string, so it is truthy. Compare with === “true” instead. - How do you set a variable for one command in PowerShell?Answer: $env:BASE_URL=”…”; node app.js. The bash form does not work in PowerShell.
- Which flag loads a .env file without any npm package?Answer: node –env-file=.env app.js. Available since Node.js 20.6.
- Should the .env file be committed to Git?Answer: No, commit a .env.example instead. It usually contains secrets.
- Which values belong in environment variables rather than in a committed config file?Answer: Passwords and API tokens. Secrets and per-machine values go in env vars.
- What does
process.env.PORT ?? 3000give when PORT is “8080”?Answer: “8080” (a string). ?? only replaces undefined or null; the value is still a string. - Which variable do most CI services set automatically?Answer: CI. Playwright’s default config uses process.env.CI.
💼 Interview Questions and Answers
Q1. How do you run the same test suite against different environments?
Keep environment-specific, non-secret settings (URLs, timeouts, worker counts) in a config module keyed by an environment name, select it with a variable such as TEST_ENV, and read secrets from environment variables. Locally they come from a git-ignored .env loaded with --env-file or dotenv; in CI they come from the secrets store. The test code never changes, only the variables do.
Q2. How do you keep secrets out of test code?
Never hard-code them. Read them from process.env, keep local values in a git-ignored .env, commit only a .env.example with names, store CI values as masked secrets, avoid printing them in logs and reports, and rotate any secret that was ever committed. Secret-scanning tools (such as GitHub secret scanning) add a safety net.
Q3. What problems can environment variables cause, and how do you prevent them?
Values are strings, so "false" is truthy and numbers concatenate. Missing variables become undefined and fail far from the cause. Typos in names fail silently. Prevent this with one config module that reads every variable once, converts types, applies defaults, validates required values and fails fast with a message that lists what is missing.
Q4. What is the difference between dotenv and –env-file?
Both load NAME=value lines into process.env. dotenv is an npm package you import (require("dotenv").config()). --env-file is built into Node.js 20.6+ and needs no dependency; process.loadEnvFile() is the runtime equivalent. Neither overrides variables that are already set in the environment.
❓ Frequently Asked Questions
🤔 Can a browser page read process.env?
No. process.env exists only in Node.js. Front-end build tools (Vite, webpack) replace specific variables at build time; anything shipped to the browser is public, so never put secrets there.
🤔 Do I still need the dotenv package?
Not for new projects on Node.js 20.6 or later: use node --env-file=.env or process.loadEnvFile(). dotenv is still common in existing projects and works fine.
🤔 Why does my change to an environment variable have no effect?
Programs read environment variables when they start. Restart the terminal, the IDE or the test runner after changing system variables, and check that a variable set in the shell is not overriding your .env file.
🤔 Are environment variable names case-sensitive?
On macOS and Linux, yes. On Windows, no. Use one consistent UPPER_SNAKE_CASE spelling so your code works everywhere.
🏁 Summary
- Environment variables are text settings passed to a program at start; Node.js reads them from
process.env. - Set them per command (
NAME=value node app.jsin bash,$env:NAME="value"in PowerShell) or load a.envfile withnode --env-file=.env. - Every value is a string: convert numbers and booleans explicitly, add defaults with
??and fail fast on missing required values. - Keep URLs and timeouts in a committed config; keep secrets in env vars, a git-ignored
.envand CI secrets. - Select environments with a variable such as
TEST_ENV, and never print secrets in logs.
Next, continue with Lesson 56: ESLint and Prettier.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in