Environment variables are very important while developing with Node.js, it essentially allows your application to behave differently based on
the environment you want them to run in. To facilitate this developers have often used a package dotenv
which helped us load environment
variables from a .env
file. Recent updates to the Node.js, have made this package usage reduntant as they have introduced native support for
environment variables.
Built in support for .env
Starting from Node.js v20.6.0, Node.js has built in support for configuring environment variables using the --env-file
flag from the command
line. Your setup file should use the INI file style. Each line must have a key and a value for a setting.
Let's see how we can use this, take the following .env
:
# config.env file
NODE_OPTIONS='--title="My Node App"'
PASSWORD='Asdf@1234'
To be able to initialise your Node.js application with the above .env
you would need to run the following command:
node --env-file=config.env index.js
Inside your index.js you can use the variables using as follows:
console.log(process.title); // My Node App
console.log(process.env.PASSWORD); // Asdf@1234
As shown above, this adjustment lets you set your NODE_OPTIONS
in the .env file instead of adding it to your package.json
.
Loading environment variables with process.loadEnvFile()
As we can access configuration variables by passing a flag while running the node application another use case might be that developers might need to load variables from a file, starting from Node.js 21.7.0 introduced process.loadEnvFile()
method.
Loads the .env
file into process.env
.
const { loadEnvFile } = require('node:process');
loadEnvFile() // will load the variables from .env
loadEnvFile('./config.env') // you can even pass a file path
One thing to keep in mind while using this would be NODE_OPTIONS
in the .env
will not affect Node.js.
In summary, while removing the dotenv dependency from your Node.js applications may require some initial setup, the benefits of streamlined
deployment and reduced complexity can significantly enhance both performance and maintainability.
As we approach the stable release of Node.js 22.0.0, it's evident that Node.js is evolving rapidly, from refreshing its website to introducing a
new mascot. The features included in the latest versions bring a breath of fresh air,
enhancing the platform's capabilities and user experience.
It's also encouraging to see Node.js adopting successful features from modern runtimes like Bun, which shows a healthy approach to innovation
and improvement. This adaptability ensures Node.js remains a top choice for developers seeking robust and up-to-date technology.
Happy configuring your next Node.js Application!
Top comments (3)
informative Thanks
Amazing! Lately been using dotenv a lot๐ will try this out ๐๐พ
Cool, thanks for sharing it!