Read environment variables in Node.js
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.
Start your file with dotenv
to inject the variables from .env
file into process.env
:
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:
Working with numeric values
Leverage the Number()
function or the unary +
operator to perform numeric conversion:
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:
Remember, assigning a value to process.env
will convert it to a string:
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.
Was this article helpful?