Node.js with native support for .env files — you may not need dotenv anymore
The dotenv package is the most popular way to load environment variables from a .env
file in the Node.js ecosystem. From now on, you may not need it anymore. Node v20.6.0 comes with native support for .env
configuration files.
A storage mechanism for key/value vars is handy, but we can also use it to configure the runtime via NODE_OPTIONS
. This method is a lot easier to manage than long scripts in the package.json
file.
Here is a simple example of invoking a node script with the new --env-file
flag.
# config.env
NODE_OPTIONS='--title="Testing Node v20.6.0"'
USER_NAME='Paweł Grzybek'
// index.js
console.log(process.title);
console.log(`Hi ${process.env.USER_NAME} 👋`);
node --env-file=config.env index.js
Testing Node v20.6.0
Hi Paweł Grzybek 👋
Can you add dark theme for this site? :)
Ah, there is one. It changes according to the operating system's appearance preferences.
Thank you! It works!
Hi there and thank you for the post. While using typescript and ts-node, it throw an error : Error: Unknown or unexpected option: --env-file. So i guess this is still not fully implemented in all tools we use.
Otherwise, it works perfectly with the classic node command.
Highly possible if you execute it directly using
ts-node
CLI. There is a hope though — try executing it using node and ats-node
loader. It may work 🤷♂️ Like so: