process.env

Read environment variables to configure your app.

Syntaxprocess.env.PORT

process.env is an object holding the environment variables available to your program. It is the standard way to pass configuration such as ports, database URLs, and secret keys.

Why use environment variables?

  • Keep secrets out of your source code.
  • Change settings without editing code.
  • Use different values in development and production.

Example

Example · javascript
// Run: PORT=8080 NODE_ENV=production node server.js
const port = process.env.PORT || 3000;
const mode = process.env.NODE_ENV || 'development';

console.log(`Starting in ${mode} mode on port ${port}`);

When to use it

  • A production API reads `process.env.DATABASE_URL` so the connection string is never hard-coded in source code or committed to version control.
  • A CI/CD pipeline sets `NODE_ENV=test` before running Jest so the app loads a test database configuration instead of the production one.
  • A Docker container passes secrets as environment variables that are injected at runtime and read via `process.env` inside the Node process.

More examples

Read an environment variable

Reads `PORT` and `NODE_ENV` from the environment with safe fallback defaults.

Example · js
// Reads PORT from the environment, falls back to 3000
const PORT = process.env.PORT || 3000;
const NODE_ENV = process.env.NODE_ENV || 'development';

console.log(`Starting server on port ${PORT} in ${NODE_ENV} mode`);

Set env variable when starting Node

Passes environment variables inline when launching Node -- useful for one-off overrides in development.

Example · bash
# Inline assignment (Linux/macOS)
PORT=8080 NODE_ENV=production node server.js

# Windows PowerShell
$env:PORT=8080; node server.js

Guard against missing required vars

Validates that all required environment variables are present at startup and exits early if any are missing.

Example · js
const REQUIRED = ['DATABASE_URL', 'JWT_SECRET', 'PORT'];
const missing = REQUIRED.filter(k => !process.env[k]);
if (missing.length > 0) {
  console.error('Missing env vars:', missing.join(', '));
  process.exit(1);
}

Discussion

  • Be the first to comment on this lesson.