Built-in .env Support in Node.js v20.6.0
It's always nice to peel dependencies out of projects.
dotenv has been a staple for managing our .env files in our Node applications.
But soon, it'll no longer be needed since with Node.js v20.6.0, we get support for .env files out of the box.
That's all thanks to adding the new --env-file flag.
Usage with Built-in .env Support
In the root of your project, create a
.envfile. Note: You can name this whatever you like, but.envis a typical convention.Run your Node.js application and pass the env file to the
--env-fileflag in the CLI command:
node --env-file .env index.js
Example
Create our .env file with the environment variables:
TOP_SECRET_PASSWORD=POOP1234
Then our Node script in index.js:
console.log(process.env.TOP_SECRET_PASSWORD);
And then run the following:
node -v
And make sure your Node version is higher than 20.6.0, then run:
node --env-file .env index.js
Which will result in a log of POOP1234 in our terminal.
Bonus 🚀
There is another bonus to using this flag.
You can also define your Node CLI options directly in the .env file rather than in your command:
# .env NODE_OPTIONS="--inspect --max-old-space-size=4096"
It will automatically apply those options when you run using this .env.
Happy coding! ⚡️
