Environment Variables (Node.js)

Environment variables are external configuration values your Node.js app reads from process.env. They keep secrets and per-environment settings (database URLs, API keys, ports) out of your code.

Node.js

Hard-coding configuration is inflexible and insecure. Environment variables let the same code run differently in development, staging, and production without edits: you read values like process.env.PORT, process.env.DATABASE_URL, and process.env.JWT_SECRET, and set them outside the code in the shell or the host platform.

All values from process.env are strings, so you parse numbers and booleans yourself (Number(process.env.PORT) || 3000, process.env.DEBUG === 'true'). A convention is process.env.NODE_ENV ('development' or 'production'), which many libraries check to enable optimizations.

Crucially, secrets belong in environment variables, never in source control. Locally you keep them in a .env file (git-ignored) loaded by dotenv, while in production the hosting platform sets them. This separation is a core twelve-factor app practice.

Syntax

const port = process.env.PORT || 3000;

Examples

JavaScript

const port = Number(process.env.PORT) || 3000;
const isProd = process.env.NODE_ENV === "production";
const dbUrl = process.env.DATABASE_URL;

app.listen(port, () => console.log(`on ${port}, prod=${isProd}`));

Learn it in a lesson

See also

Back to the Dictionary