Explain Codes LogoExplain Codes Logo

Read environment variables in Node.js

javascript
environment-variables
node-js
variable-access
Anton ShumikhinbyAnton Shumikhin·Jan 22, 2025
TLDR

Fetch environment variables in Node.js using process.env. For instance, you can get the PORT variable using process.env.PORT. If you prefer managing your environment variables, use a .env file combined with the dotenv package.

console.log(process.env.PORT);

Start your file with dotenv to inject the variables from .env file into process.env:

require('dotenv').config(); console.log(process.env.PORT);

Pro-tip: Use environment variables to safeguard sensitive data like API keys, instead of embedding them in your code.

String nature of environment variables

Remember, environment variables in Node.js are always strings. This string nature can cause pitfalls when your code anticipates different data types, such as booleans or numbers.

Dealing with boolean values

Keep calm and explicitly handle string-based truthiness:

const isProduction = process.env.NODE_ENV === 'production'; // Strictly enforced string check

Working with numeric values

Leverage the Number() function or the unary + operator to perform numeric conversion:

const port = Number(process.env.PORT) || 3000; // Numeric fallback faster than a cheetah

Security watch outs

Don't play with fire! Security ranks high when using environment variables. Remember to omit .env from source control by adding it to .gitignore. Access your variables strictly when needed and use packages that blur sensitive data in logs.

Advanced dotenv usage

In case your use cases demand more power, consider using dotenv-expand. It enables variable expansion within your .env files.

Cross-platform quirks

While working across different platforms, keep an eye for differences in setting environment variables. Use packages like cross-env to handle syntax differences between Windows and Unix-like systems.

Dynamic variable access

Retrieving environment variables can be done dynamically by utilizing bracket notation, handy for variable key names:

const secretPassage = 'SECRET_ROOM'; console.log(process.env[secretPassage]); // Secret passage detected

Remember, assigning a value to process.env will convert it to a string:

process.env.UNIVERSE_ANSWER = 42; console.log(typeof process.env.UNIVERSE_ANSWER); // 'string', not 'universe-answer'!

Application configuration using env vars

Environment variables are essential for configuring Node.js applications. They help in setting up different environments like development, testing, and production, without touching the core codebase.

Use variable assignment in your scripts or package.json to set the variables for different deployment environments.